-
Notifications
You must be signed in to change notification settings - Fork 97
/
proxy_test.go
353 lines (321 loc) · 9.69 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package libproxy
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/mccutchen/go-httpbin/v2/httpbin"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
type RespResult struct {
proxyResponse httptest.ResponseRecorder
err error
requestResponse Response
}
func getResultDef(request Request) RespResult {
return getResult(request, "validorigin1.com")
}
var (
testServerUrl string
)
func getResult(_req Request, origin string) RespResult {
var respResult RespResult
marshal, err := json.Marshal(_req)
respResult.proxyResponse = *httptest.NewRecorder()
respResult.err = err
if err != nil {
return respResult
}
request := httptest.NewRequest("POST", "/", bytes.NewReader(marshal))
request.Header.Set("Origin", origin)
proxyHandler(&respResult.proxyResponse, request)
result := respResult.proxyResponse.Result()
err = json.NewDecoder(result.Body).Decode(&respResult.requestResponse)
respResult.err = err
return respResult
}
func init() {
allowedOrigins = []string{"validorigin1.com", "validorigin2.com"}
app := httpbin.New()
testServer := httptest.NewServer(app.Handler())
testServerUrl = testServer.URL
}
func checkErrorNUnmarshalHTTPBinResponse(data string, t *testing.T) HTTPBinResponse {
var r HTTPBinResponse
err := json.Unmarshal([]byte(data), &r)
assert.Nil(t, err)
return r
}
type HTTPBinResponse struct {
Args url.Values `json:"args"`
Headers http.Header `json:"headers"`
Origin string `json:"origin"`
URL string `json:"url"`
Data string `json:"data"`
Files map[string]interface{} `json:"files"`
Form map[string]interface{} `json:"form"`
JSON map[string]interface{} `json:"json"`
}
// TestRedirectInCaseOriginNotSpecified
func TestNotAllowedOrigin(t *testing.T) {
result := getResult(Request{
Url: testServerUrl + "/get",
Method: "GET",
}, "invalidorigin.com")
// redirect in case of unknown origin
assert.Equal(t, 301, result.proxyResponse.Code)
}
func TestWildCardOrigin(t *testing.T) {
_allowedOrigins := allowedOrigins
allowedOrigins = []string{"*"}
defer func() {
// reset allowedOrigins
// for rest of test cases are not thread safe, will have to run one after others
allowedOrigins = _allowedOrigins
}()
result := getResult(Request{
Method: "GET",
Url: testServerUrl + "/get",
}, "invalidorigin.com")
// valid origin => 200 status
assert.Equal(t, 200, result.proxyResponse.Code)
}
func TestUrlParamsInUrl(t *testing.T) {
resp := getResultDef(Request{
Method: "GET",
Url: testServerUrl + "/get?ram=ranga",
})
assert.Equal(t, 200, resp.proxyResponse.Code)
httpBinResponse := checkErrorNUnmarshalHTTPBinResponse(resp.requestResponse.Data, t)
// url params are sent
assert.Equal(t, "ranga", httpBinResponse.Args.Get("ram"))
}
func TestUrlParamsInParams(t *testing.T) {
resp := getResultDef(Request{
Method: "GET",
Url: testServerUrl + "/get",
Params: map[string]string{
"ram": "ranga",
},
})
assert.Equal(t, 200, resp.proxyResponse.Code)
httpBinResponse := checkErrorNUnmarshalHTTPBinResponse(resp.requestResponse.Data, t)
// url params are sent
assert.Equal(t, "ranga", httpBinResponse.Args.Get("ram"))
}
func TestHeaders(t *testing.T) {
resp := getResultDef(Request{
Method: "GET",
Url: testServerUrl + "/get",
Headers: map[string]string{
"testheaderkey": "testheadervalue",
},
})
assert.Equal(t, 200, resp.proxyResponse.Code)
httpBinResponse := checkErrorNUnmarshalHTTPBinResponse(resp.requestResponse.Data, t)
// headers are sent
assert.Equal(t, "testheadervalue", httpBinResponse.Headers.Get("testheaderkey"))
}
func TestAccessControlHeaders(t *testing.T) {
resp := getResult(Request{
Method: "GET",
Url: testServerUrl + "/get",
}, "validorigin2.com")
assert.Equal(t, 200, resp.proxyResponse.Code)
// These headers are required for browser client to read response and headers
assert.Equal(t, "validorigin2.com", resp.proxyResponse.Header().Get("Access-Control-Allow-Origin"))
}
func TestPreflightOptionsRequest(t *testing.T) {
request := httptest.NewRequest("OPTIONS", "/", nil)
resp := httptest.ResponseRecorder{}
proxyHandler(&resp, request)
headers := resp.Header()
// preflight request allow all origins
assert.Equal(t, "*", headers.Get("Access-Control-Allow-Origin"))
// preflight request allow set headers from browser
assert.Equal(t, "*", headers.Get("Access-Control-Allow-Headers"))
}
func TestPostMethod(t *testing.T) {
resp := getResultDef(Request{
Method: "POST",
Url: testServerUrl + "/post",
})
// post method
assert.Equal(t, 200, resp.proxyResponse.Code)
checkErrorNUnmarshalHTTPBinResponse(resp.requestResponse.Data, t)
}
func TestPutMethod(t *testing.T) {
resp := getResultDef(Request{
Method: "PUT",
Url: testServerUrl + "/put",
})
assert.Equal(t, 200, resp.proxyResponse.Code)
// putMethod
checkErrorNUnmarshalHTTPBinResponse(resp.requestResponse.Data, t)
}
func TestWantsBinary(t *testing.T) {
resp := getResultDef(Request{
Method: "GET",
Url: testServerUrl + "/get",
WantsBinary: true,
})
// WantsBinary: true => response will be base64encoded
decodeString, err := base64.RawStdEncoding.DecodeString(resp.requestResponse.Data)
assert.Nil(t, err)
checkErrorNUnmarshalHTTPBinResponse(string(decodeString), t)
}
func TestPostDataJson(t *testing.T) {
request := Request{
Method: "POST",
Url: testServerUrl + "/post",
Headers: map[string]string{
"content-type": "application/json",
},
Data: `{
"string": "simple",
"list": [
"dothttp",
"azure"
],
"null": null,
"bool": false,
"bool2": true,
"float": 1.121212,
"float2": 1
}`,
}
resp := getResultDef(request)
response := checkErrorNUnmarshalHTTPBinResponse(resp.requestResponse.Data, t)
assert.Equal(t, request.Data, response.Data)
}
func TestPostDataUrlencoded(t *testing.T) {
request := Request{
Method: "POST",
Url: testServerUrl + "/post",
Headers: map[string]string{
"content-type": "application/x-www-form-urlencoded",
},
Data: `ram=ranga`,
}
resp := getResultDef(request)
response := checkErrorNUnmarshalHTTPBinResponse(resp.requestResponse.Data, t)
assert.Equal(t, request.Data, response.Data)
assert.Equal(t, "[ranga]", fmt.Sprintf("%v", response.Form["ram"]))
}
func TestPostMultipart(t *testing.T) {
request := httptest.NewRequest("POST", "/",
bytes.NewReader([]byte(fmt.Sprintf(`--61ed834ef57e878fad0a3d27d2b04fb1
Content-Disposition: form-data; name="proxyRequestData"
{
"method": "POST",
"url": "%v/post",
"headers": {
"content-type": "application/x-www-form-urlencoded"
},
"params": {
"ram":"ranga"
},
"data": "",
"wantsBinary": false
}
--61ed834ef57e878fad0a3d27d2b04fb1
Content-Disposition: form-data; name="hasi"
ranga
--61ed834ef57e878fad0a3d27d2b04fb1--
`, testServerUrl))))
request.Header.Set("content-type", "multipart/form-data; boundary=61ed834ef57e878fad0a3d27d2b04fb1")
request.Header.Set("origin", "validorigin1.com")
resp := *httptest.NewRecorder()
proxyHandler(&resp, request)
var result Response
err := json.NewDecoder(resp.Body).Decode(&result)
assert.Nil(t, err)
var r HTTPBinResponse
json.Unmarshal([]byte(result.Data), &r)
assert.Equal(t, "[ranga]", fmt.Sprintf("%v", r.Form["hasi"]))
}
func TestAccessTokenDisallowIncasNotAvailable(t *testing.T) {
accessToken = "some-access-token"
defer func() {
accessToken = "" // delete access token(cleanup)
}()
request := Request{
Method: "POST",
Url: testServerUrl + "/",
}
proxyResult := getResultDef(request)
if proxyResult.err == nil {
t.Error("access token is not availablie, it should error out")
}
var proxyRespParse map[string]interface{}
err := json.NewDecoder(proxyResult.proxyResponse.Body).Decode(&proxyRespParse)
assert.Nil(t, err)
success := proxyRespParse["success"]
assert.Equal(t, "false", fmt.Sprintf("%v", success))
}
func TestAllowWithValidAccessToken(t *testing.T) {
accessToken = "some-access-token"
defer func() {
accessToken = "" // delete access token(cleanup)
}()
request := Request{
Method: "POST",
Url: testServerUrl + "/post",
AccessToken: accessToken,
}
proxyResult := getResultDef(request)
checkErrorNUnmarshalHTTPBinResponse(proxyResult.requestResponse.Data, t)
}
func TestInvalidAccessTokenRequestShouldFail(t *testing.T) {
accessToken = "some-access-token"
defer func() {
accessToken = ""
}()
request := Request{
Method: "POST",
Url: testServerUrl + "/",
AccessToken: accessToken + "1",
}
proxyResult := getResultDef(request)
assert.NotNil(t, proxyResult.err)
var proxyRespParse map[string]interface{}
json.NewDecoder(proxyResult.proxyResponse.Body).Decode(&proxyRespParse)
success := proxyRespParse["success"]
assert.Equal(t, "false", fmt.Sprintf("%v", success))
}
//func TestBannedOutputs(t *testing.T) {
// // TODO
// // need clear understanding on banned outputs
//}
func TestBasicAuth(t *testing.T) {
request := Request{
Method: "GET",
Url: testServerUrl + "/basic-auth/username/password",
Auth: struct {
Username string
Password string
}{
Username: "username",
Password: "password",
},
}
resp := getResultDef(request)
assert.Equal(t, 200, resp.requestResponse.Status)
checkErrorNUnmarshalHTTPBinResponse(resp.requestResponse.Data, t)
}
func TestBasicAuthIncorrectParams(t *testing.T) {
// just to confirm above auth is working fine if username and password is sent wrong
request := Request{
Method: "GET",
Url: testServerUrl + "/basic-auth/username/password2",
}
request.Auth.Username = "username"
request.Auth.Password = "password"
resp := getResultDef(request)
assert.Equal(t, 401, resp.requestResponse.Status)
checkErrorNUnmarshalHTTPBinResponse(resp.requestResponse.Data, t)
}