Debian Codegraph @

proxy_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 package goproxy_test
2
3 import (
4 "bufio"
5 "bytes"
6 "context"
7 "crypto/tls"
8 "crypto/x509"
9 "encoding/base64"
10 "fmt"
11 "image"
12 "io"
13 "io/ioutil"
14 "net"
15 "net/http"
16 "net/http/httptest"
17 "net/url"
18 "os"
19 "os/exec"
20 "regexp"
21 "strings"
22 "testing"
23 "time"
24
25 "github.com/elazarl/goproxy"
26 goproxy_image "github.com/elazarl/goproxy/ext/image"
27 )
28
29 var acceptAllCerts = &tls.Config{InsecureSkipVerify: true}
30
31 var noProxyClient = &http.Client{Transport: &http.Transport{TLSClientConfig: acceptAllCerts}}
32
33 var https = httptest.NewTLSServer(nil)
34 var srv = httptest.NewServer(nil)
35 var fs = httptest.NewServer(http.FileServer(http.Dir(".")))
36
37 type QueryHandler struct{}
38
39 func (QueryHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
40 if err := req.ParseForm(); err != nil {
41 panic(err)
42 }
43 io.WriteString(w, req.Form.Get("result"))
44 }
45
46 func init() {
47 http.DefaultServeMux.Handle("/bobo", ConstantHanlder("bobo"))
48 http.DefaultServeMux.Handle("/query", QueryHandler{})
49 }
50
51 type ConstantHanlder string
52
53 func (h ConstantHanlder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
54 io.WriteString(w, string(h))
55 }
56
57 func get(url string, client *http.Client) ([]byte, error) {
58 resp, err := client.Get(url)
59 if err != nil {
60 return nil, err
61 }
62 txt, err := ioutil.ReadAll(resp.Body)
63 defer resp.Body.Close()
64 if err != nil {
65 return nil, err
66 }
67 return txt, nil
68 }
69
70 func getOrFail(url string, client *http.Client, t *testing.T) []byte {
71 txt, err := get(url, client)
72 if err != nil {
73 t.Fatal("Can't fetch url", url, err)
74 }
75 return txt
76 }
77
78 func localFile(url string) string { return fs.URL + "/" + url }
79 func localTls(url string) string { return https.URL + url }
80
81 func TestSimpleHttpReqWithProxy(t *testing.T) {
82 client, s := oneShotProxy(goproxy.NewProxyHttpServer(), t)
83 defer s.Close()
84
85 if r := string(getOrFail(srv.URL+"/bobo", client, t)); r != "bobo" {
86 t.Error("proxy server does not serve constant handlers", r)
87 }
88 if r := string(getOrFail(srv.URL+"/bobo", client, t)); r != "bobo" {
89 t.Error("proxy server does not serve constant handlers", r)
90 }
91
92 if string(getOrFail(https.URL+"/bobo", client, t)) != "bobo" {
93 t.Error("TLS server does not serve constant handlers, when proxy is used")
94 }
95 }
96
97 func oneShotProxy(proxy *goproxy.ProxyHttpServer, t *testing.T) (client *http.Client, s *httptest.Server) {
98 s = httptest.NewServer(proxy)
99
100 proxyUrl, _ := url.Parse(s.URL)
101 tr := &http.Transport{TLSClientConfig: acceptAllCerts, Proxy: http.ProxyURL(proxyUrl)}
102 client = &http.Client{Transport: tr}
103 return
104 }
105
106 func TestSimpleHook(t *testing.T) {
107 proxy := goproxy.NewProxyHttpServer()
108 proxy.OnRequest(goproxy.SrcIpIs("127.0.0.1")).DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
109 req.URL.Path = "/bobo"
110 return req, nil
111 })
112 client, l := oneShotProxy(proxy, t)
113 defer l.Close()
114
115 if result := string(getOrFail(srv.URL+("/momo"), client, t)); result != "bobo" {
116 t.Error("Redirecting all requests from 127.0.0.1 to bobo, didn't work." +
117 " (Might break if Go's client sets RemoteAddr to IPv6 address). Got: " +
118 result)
119 }
120 }
121
122 func TestAlwaysHook(t *testing.T) {
123 proxy := goproxy.NewProxyHttpServer()
124 proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
125 req.URL.Path = "/bobo"
126 return req, nil
127 })
128 client, l := oneShotProxy(proxy, t)
129 defer l.Close()
130
131 if result := string(getOrFail(srv.URL+("/momo"), client, t)); result != "bobo" {
132 t.Error("Redirecting all requests from 127.0.0.1 to bobo, didn't work." +
133 " (Might break if Go's client sets RemoteAddr to IPv6 address). Got: " +
134 result)
135 }
136 }
137
138 func TestReplaceResponse(t *testing.T) {
139 proxy := goproxy.NewProxyHttpServer()
140 proxy.OnResponse().DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
141 resp.StatusCode = http.StatusOK
142 resp.Body = ioutil.NopCloser(bytes.NewBufferString("chico"))
143 return resp
144 })
145
146 client, l := oneShotProxy(proxy, t)
147 defer l.Close()
148
149 if result := string(getOrFail(srv.URL+("/momo"), client, t)); result != "chico" {
150 t.Error("hooked response, should be chico, instead:", result)
151 }
152 }
153
154 func TestReplaceReponseForUrl(t *testing.T) {
155 proxy := goproxy.NewProxyHttpServer()
156 proxy.OnResponse(goproxy.UrlIs("/koko")).DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
157 resp.StatusCode = http.StatusOK
158 resp.Body = ioutil.NopCloser(bytes.NewBufferString("chico"))
159 return resp
160 })
161
162 client, l := oneShotProxy(proxy, t)
163 defer l.Close()
164
165 if result := string(getOrFail(srv.URL+("/koko"), client, t)); result != "chico" {
166 t.Error("hooked 'koko', should be chico, instead:", result)
167 }
168 if result := string(getOrFail(srv.URL+("/bobo"), client, t)); result != "bobo" {
169 t.Error("still, bobo should stay as usual, instead:", result)
170 }
171 }
172
173 func TestOneShotFileServer(t *testing.T) {
174 client, l := oneShotProxy(goproxy.NewProxyHttpServer(), t)
175 defer l.Close()
176
177 file := "test_data/panda.png"
178 info, err := os.Stat(file)
179 if err != nil {
180 t.Fatal("Cannot find", file)
181 }
182 if resp, err := client.Get(fs.URL + "/" + file); err == nil {
183 b, err := ioutil.ReadAll(resp.Body)
184 if err != nil {
185 t.Fatal("got", string(b))
186 }
187 if int64(len(b)) != info.Size() {
188 t.Error("Expected Length", file, info.Size(), "actually", len(b), "starts", string(b[:10]))
189 }
190 } else {
191 t.Fatal("Cannot read from fs server", err)
192 }
193 }
194
195 func TestContentType(t *testing.T) {
196 proxy := goproxy.NewProxyHttpServer()
197 proxy.OnResponse(goproxy.ContentTypeIs("image/png")).DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
198 resp.Header.Set("X-Shmoopi", "1")
199 return resp
200 })
201
202 client, l := oneShotProxy(proxy, t)
203 defer l.Close()
204
205 for _, file := range []string{"test_data/panda.png", "test_data/football.png"} {
206 if resp, err := client.Get(localFile(file)); err != nil || resp.Header.Get("X-Shmoopi") != "1" {
207 if err == nil {
208 t.Error("pngs should have X-Shmoopi header = 1, actually", resp.Header.Get("X-Shmoopi"))
209 } else {
210 t.Error("error reading png", err)
211 }
212 }
213 }
214
215 file := "baby.jpg"
216 if resp, err := client.Get(localFile(file)); err != nil || resp.Header.Get("X-Shmoopi") != "" {
217 if err == nil {
218 t.Error("Non png images should NOT have X-Shmoopi header at all", resp.Header.Get("X-Shmoopi"))
219 } else {
220 t.Error("error reading png", err)
221 }
222 }
223 }
224
225 func getImage(file string, t *testing.T) image.Image {
226 newimage, err := ioutil.ReadFile(file)
227 if err != nil {
228 t.Fatal("Cannot read file", file, err)
229 }
230 img, _, err := image.Decode(bytes.NewReader(newimage))
231 if err != nil {
232 t.Fatal("Cannot decode image", file, err)
233 }
234 return img
235 }
236
237 func readAll(r io.Reader, t *testing.T) []byte {
238 b, err := ioutil.ReadAll(r)
239 if err != nil {
240 t.Fatal("Cannot read", err)
241 }
242 return b
243 }
244 func readFile(file string, t *testing.T) []byte {
245 b, err := ioutil.ReadFile(file)
246 if err != nil {
247 t.Fatal("Cannot read", err)
248 }
249 return b
250 }
251 func fatalOnErr(err error, msg string, t *testing.T) {
252 if err != nil {
253 t.Fatal(msg, err)
254 }
255 }
256 func panicOnErr(err error, msg string) {
257 if err != nil {
258 println(err.Error() + ":-" + msg)
259 os.Exit(-1)
260 }
261 }
262
263 func compareImage(eImg, aImg image.Image, t *testing.T) {
264 if eImg.Bounds().Dx() != aImg.Bounds().Dx() || eImg.Bounds().Dy() != aImg.Bounds().Dy() {
265 t.Error("image sizes different")
266 return
267 }
268 for i := 0; i < eImg.Bounds().Dx(); i++ {
269 for j := 0; j < eImg.Bounds().Dy(); j++ {
270 er, eg, eb, ea := eImg.At(i, j).RGBA()
271 ar, ag, ab, aa := aImg.At(i, j).RGBA()
272 if er != ar || eg != ag || eb != ab || ea != aa {
273 t.Error("images different at", i, j, "vals\n", er, eg, eb, ea, "\n", ar, ag, ab, aa, aa)
274 return
275 }
276 }
277 }
278 }
279
280 func TestConstantImageHandler(t *testing.T) {
281 proxy := goproxy.NewProxyHttpServer()
282 //panda := getImage("panda.png", t)
283 football := getImage("test_data/football.png", t)
284 proxy.OnResponse().Do(goproxy_image.HandleImage(func(img image.Image, ctx *goproxy.ProxyCtx) image.Image {
285 return football
286 }))
287
288 client, l := oneShotProxy(proxy, t)
289 defer l.Close()
290
291 resp, err := client.Get(localFile("test_data/panda.png"))
292 if err != nil {
293 t.Fatal("Cannot get panda.png", err)
294 }
295
296 img, _, err := image.Decode(resp.Body)
297 if err != nil {
298 t.Error("decode", err)
299 } else {
300 compareImage(football, img, t)
301 }
302 }
303
304 func TestImageHandler(t *testing.T) {
305 proxy := goproxy.NewProxyHttpServer()
306 football := getImage("test_data/football.png", t)
307
308 proxy.OnResponse(goproxy.UrlIs("/test_data/panda.png")).Do(goproxy_image.HandleImage(func(img image.Image, ctx *goproxy.ProxyCtx) image.Image {
309 return football
310 }))
311
312 client, l := oneShotProxy(proxy, t)
313 defer l.Close()
314
315 resp, err := client.Get(localFile("test_data/panda.png"))
316 if err != nil {
317 t.Fatal("Cannot get panda.png", err)
318 }
319
320 img, _, err := image.Decode(resp.Body)
321 if err != nil {
322 t.Error("decode", err)
323 } else {
324 compareImage(football, img, t)
325 }
326
327 // and again
328 resp, err = client.Get(localFile("test_data/panda.png"))
329 if err != nil {
330 t.Fatal("Cannot get panda.png", err)
331 }
332
333 img, _, err = image.Decode(resp.Body)
334 if err != nil {
335 t.Error("decode", err)
336 } else {
337 compareImage(football, img, t)
338 }
339 }
340
341 func TestChangeResp(t *testing.T) {
342 proxy := goproxy.NewProxyHttpServer()
343 proxy.OnResponse().DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
344 resp.Body.Read([]byte{0})
345 resp.Body = ioutil.NopCloser(new(bytes.Buffer))
346 return resp
347 })
348
349 client, l := oneShotProxy(proxy, t)
350 defer l.Close()
351
352 resp, err := client.Get(localFile("test_data/panda.png"))
353 if err != nil {
354 t.Fatal(err)
355 }
356 ioutil.ReadAll(resp.Body)
357 _, err = client.Get(localFile("/bobo"))
358 if err != nil {
359 t.Fatal(err)
360 }
361 }
362 func TestReplaceImage(t *testing.T) {
363 proxy := goproxy.NewProxyHttpServer()
364
365 panda := getImage("test_data/panda.png", t)
366 football := getImage("test_data/football.png", t)
367
368 proxy.OnResponse(goproxy.UrlIs("/test_data/panda.png")).Do(goproxy_image.HandleImage(func(img image.Image, ctx *goproxy.ProxyCtx) image.Image {
369 return football
370 }))
371 proxy.OnResponse(goproxy.UrlIs("/test_data/football.png")).Do(goproxy_image.HandleImage(func(img image.Image, ctx *goproxy.ProxyCtx) image.Image {
372 return panda
373 }))
374
375 client, l := oneShotProxy(proxy, t)
376 defer l.Close()
377
378 imgByPandaReq, _, err := image.Decode(bytes.NewReader(getOrFail(localFile("test_data/panda.png"), client, t)))
379 fatalOnErr(err, "decode panda", t)
380 compareImage(football, imgByPandaReq, t)
381
382 imgByFootballReq, _, err := image.Decode(bytes.NewReader(getOrFail(localFile("test_data/football.png"), client, t)))
383 fatalOnErr(err, "decode football", t)
384 compareImage(panda, imgByFootballReq, t)
385 }
386
387 func getCert(c *tls.Conn, t *testing.T) []byte {
388 if err := c.Handshake(); err != nil {
389 t.Fatal("cannot handshake", err)
390 }
391 return c.ConnectionState().PeerCertificates[0].Raw
392 }
393
394 func TestSimpleMitm(t *testing.T) {
395 proxy := goproxy.NewProxyHttpServer()
396 proxy.OnRequest(goproxy.ReqHostIs(https.Listener.Addr().String())).HandleConnect(goproxy.AlwaysMitm)
397 proxy.OnRequest(goproxy.ReqHostIs("no such host exists")).HandleConnect(goproxy.AlwaysMitm)
398
399 client, l := oneShotProxy(proxy, t)
400 defer l.Close()
401
402 c, err := tls.Dial("tcp", https.Listener.Addr().String(), &tls.Config{InsecureSkipVerify: true})
403 if err != nil {
404 t.Fatal("cannot dial to tcp server", err)
405 }
406 origCert := getCert(c, t)
407 c.Close()
408
409 c2, err := net.Dial("tcp", l.Listener.Addr().String())
410 if err != nil {
411 t.Fatal("dialing to proxy", err)
412 }
413 creq, err := http.NewRequest("CONNECT", https.URL, nil)
414 //creq,err := http.NewRequest("CONNECT","https://google.com:443",nil)
415 if err != nil {
416 t.Fatal("create new request", creq)
417 }
418 creq.Write(c2)
419 c2buf := bufio.NewReader(c2)
420 resp, err := http.ReadResponse(c2buf, creq)
421 if err != nil || resp.StatusCode != 200 {
422 t.Fatal("Cannot CONNECT through proxy", err)
423 }
424 c2tls := tls.Client(c2, &tls.Config{InsecureSkipVerify: true})
425 proxyCert := getCert(c2tls, t)
426
427 if bytes.Equal(proxyCert, origCert) {
428 t.Errorf("Certificate after mitm is not different\n%v\n%v",
429 base64.StdEncoding.EncodeToString(origCert),
430 base64.StdEncoding.EncodeToString(proxyCert))
431 }
432
433 if resp := string(getOrFail(https.URL+"/bobo", client, t)); resp != "bobo" {
434 t.Error("Wrong response when mitm", resp, "expected bobo")
435 }
436 if resp := string(getOrFail(https.URL+"/query?result=bar", client, t)); resp != "bar" {
437 t.Error("Wrong response when mitm", resp, "expected bar")
438 }
439 }
440
441 func TestConnectHandler(t *testing.T) {
442 proxy := goproxy.NewProxyHttpServer()
443 althttps := httptest.NewTLSServer(ConstantHanlder("althttps"))
444 proxy.OnRequest().HandleConnectFunc(func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
445 u, _ := url.Parse(althttps.URL)
446 return goproxy.OkConnect, u.Host
447 })
448
449 client, l := oneShotProxy(proxy, t)
450 defer l.Close()
451 if resp := string(getOrFail(https.URL+"/alturl", client, t)); resp != "althttps" {
452 t.Error("Proxy should redirect CONNECT requests to local althttps server, expected 'althttps' got ", resp)
453 }
454 }
455
456 func TestMitmIsFiltered(t *testing.T) {
457 proxy := goproxy.NewProxyHttpServer()
458 //proxy.Verbose = true
459 proxy.OnRequest(goproxy.ReqHostIs(https.Listener.Addr().String())).HandleConnect(goproxy.AlwaysMitm)
460 proxy.OnRequest(goproxy.UrlIs("/momo")).DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
461 return nil, goproxy.TextResponse(req, "koko")
462 })
463
464 client, l := oneShotProxy(proxy, t)
465 defer l.Close()
466
467 if resp := string(getOrFail(https.URL+"/momo", client, t)); resp != "koko" {
468 t.Error("Proxy should capture /momo to be koko and not", resp)
469 }
470
471 if resp := string(getOrFail(https.URL+"/bobo", client, t)); resp != "bobo" {
472 t.Error("But still /bobo should be bobo and not", resp)
473 }
474 }
475
476 func TestFirstHandlerMatches(t *testing.T) {
477 proxy := goproxy.NewProxyHttpServer()
478 proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
479 return nil, goproxy.TextResponse(req, "koko")
480 })
481 proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
482 panic("should never get here, previous response is no null")
483 })
484
485 client, l := oneShotProxy(proxy, t)
486 defer l.Close()
487
488 if resp := string(getOrFail(srv.URL+"/", client, t)); resp != "koko" {
489 t.Error("should return always koko and not", resp)
490 }
491 }
492
493 func constantHttpServer(content []byte) (addr string) {
494 l, err := net.Listen("tcp", "localhost:0")
495 panicOnErr(err, "listen")
496 go func() {
497 c, err := l.Accept()
498 panicOnErr(err, "accept")
499 buf := bufio.NewReader(c)
500 _, err = http.ReadRequest(buf)
501 panicOnErr(err, "readReq")
502 c.Write(content)
503 c.Close()
504 l.Close()
505 }()
506 return l.Addr().String()
507 }
508
509 func TestIcyResponse(t *testing.T) {
510 // TODO: fix this test
511 /*s := constantHttpServer([]byte("ICY 200 OK\r\n\r\nblablabla"))
512 proxy := goproxy.NewProxyHttpServer()
513 proxy.Verbose = true
514 _, l := oneShotProxy(proxy, t)
515 defer l.Close()
516 req, err := http.NewRequest("GET", "http://"+s, nil)
517 panicOnErr(err, "newReq")
518 proxyip := l.URL[len("http://"):]
519 println("got ip: " + proxyip)
520 c, err := net.Dial("tcp", proxyip)
521 panicOnErr(err, "dial")
522 defer c.Close()
523 req.WriteProxy(c)
524 raw, err := ioutil.ReadAll(c)
525 panicOnErr(err, "readAll")
526 if string(raw) != "ICY 200 OK\r\n\r\nblablabla" {
527 t.Error("Proxy did not send the malformed response received")
528 }*/
529 }
530
531 type VerifyNoProxyHeaders struct {
532 *testing.T
533 }
534
535 func (v VerifyNoProxyHeaders) ServeHTTP(w http.ResponseWriter, r *http.Request) {
536 if r.Header.Get("Connection") != "" || r.Header.Get("Proxy-Connection") != "" ||
537 r.Header.Get("Proxy-Authenticate") != "" || r.Header.Get("Proxy-Authorization") != "" {
538 v.Error("Got Connection header from goproxy", r.Header)
539 }
540 }
541
542 func TestNoProxyHeaders(t *testing.T) {
543 t.Skip("DM-skipped")
544 s := httptest.NewServer(VerifyNoProxyHeaders{t})
545 client, l := oneShotProxy(goproxy.NewProxyHttpServer(), t)
546 defer l.Close()
547 req, err := http.NewRequest("GET", s.URL, nil)
548 panicOnErr(err, "bad request")
549 req.Header.Add("Connection", "close")
550 req.Header.Add("Proxy-Connection", "close")
551 req.Header.Add("Proxy-Authenticate", "auth")
552 req.Header.Add("Proxy-Authorization", "auth")
553 client.Do(req)
554 }
555
556 func TestNoProxyHeadersHttps(t *testing.T) {
557 t.Skip("DM-skipped")
558 s := httptest.NewTLSServer(VerifyNoProxyHeaders{t})
559 proxy := goproxy.NewProxyHttpServer()
560 proxy.OnRequest().HandleConnect(goproxy.AlwaysMitm)
561 client, l := oneShotProxy(proxy, t)
562 defer l.Close()
563 req, err := http.NewRequest("GET", s.URL, nil)
564 panicOnErr(err, "bad request")
565 req.Header.Add("Connection", "close")
566 req.Header.Add("Proxy-Connection", "close")
567 client.Do(req)
568 }
569
570 func TestHeadReqHasContentLength(t *testing.T) {
571 client, l := oneShotProxy(goproxy.NewProxyHttpServer(), t)
572 defer l.Close()
573
574 resp, err := client.Head(localFile("test_data/panda.png"))
575 panicOnErr(err, "resp to HEAD")
576 if resp.Header.Get("Content-Length") == "" {
577 t.Error("Content-Length should exist on HEAD requests")
578 }
579 }
580
581 func TestChunkedResponse(t *testing.T) {
582 l, err := net.Listen("tcp", ":10234")
583 panicOnErr(err, "listen")
584 defer l.Close()
585 go func() {
586 for i := 0; i < 2; i++ {
587 c, err := l.Accept()
588 panicOnErr(err, "accept")
589 _, err = http.ReadRequest(bufio.NewReader(c))
590 panicOnErr(err, "readrequest")
591 io.WriteString(c, "HTTP/1.1 200 OK\r\n"+
592 "Content-Type: text/plain\r\n"+
593 "Transfer-Encoding: chunked\r\n\r\n"+
594 "25\r\n"+
595 "This is the data in the first chunk\r\n\r\n"+
596 "1C\r\n"+
597 "and this is the second one\r\n\r\n"+
598 "3\r\n"+
599 "con\r\n"+
600 "8\r\n"+
601 "sequence\r\n0\r\n\r\n")
602 c.Close()
603 }
604 }()
605
606 c, err := net.Dial("tcp", "localhost:10234")
607 panicOnErr(err, "dial")
608 defer c.Close()
609 req, _ := http.NewRequest("GET", "/", nil)
610 req.Write(c)
611 resp, err := http.ReadResponse(bufio.NewReader(c), req)
612 panicOnErr(err, "readresp")
613 b, err := ioutil.ReadAll(resp.Body)
614 panicOnErr(err, "readall")
615 expected := "This is the data in the first chunk\r\nand this is the second one\r\nconsequence"
616 if string(b) != expected {
617 t.Errorf("Got `%v` expected `%v`", string(b), expected)
618 }
619
620 proxy := goproxy.NewProxyHttpServer()
621 proxy.OnResponse().DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
622 panicOnErr(ctx.Error, "error reading output")
623 b, err := ioutil.ReadAll(resp.Body)
624 resp.Body.Close()
625 panicOnErr(err, "readall onresp")
626 if enc := resp.Header.Get("Transfer-Encoding"); enc != "" {
627 t.Fatal("Chunked response should be received as plaintext", enc)
628 }
629 resp.Body = ioutil.NopCloser(bytes.NewBufferString(strings.Replace(string(b), "e", "E", -1)))
630 return resp
631 })
632
633 client, s := oneShotProxy(proxy, t)
634 defer s.Close()
635
636 resp, err = client.Get("http://localhost:10234/")
637 panicOnErr(err, "client.Get")
638 b, err = ioutil.ReadAll(resp.Body)
639 panicOnErr(err, "readall proxy")
640 if string(b) != strings.Replace(expected, "e", "E", -1) {
641 t.Error("expected", expected, "w/ e->E. Got", string(b))
642 }
643 }
644
645 func TestGoproxyThroughProxy(t *testing.T) {
646 proxy := goproxy.NewProxyHttpServer()
647 proxy2 := goproxy.NewProxyHttpServer()
648 doubleString := func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
649 b, err := ioutil.ReadAll(resp.Body)
650 panicOnErr(err, "readAll resp")
651 resp.Body = ioutil.NopCloser(bytes.NewBufferString(string(b) + " " + string(b)))
652 return resp
653 }
654 proxy.OnRequest().HandleConnect(goproxy.AlwaysMitm)
655 proxy.OnResponse().DoFunc(doubleString)
656
657 _, l := oneShotProxy(proxy, t)
658 defer l.Close()
659
660 proxy2.ConnectDial = proxy2.NewConnectDialToProxy(l.URL)
661
662 client, l2 := oneShotProxy(proxy2, t)
663 defer l2.Close()
664 if r := string(getOrFail(https.URL+"/bobo", client, t)); r != "bobo bobo" {
665 t.Error("Expected bobo doubled twice, got", r)
666 }
667
668 }
669
670 func TestGoproxyHijackConnect(t *testing.T) {
671 t.Skip("DM-skipped")
672 proxy := goproxy.NewProxyHttpServer()
673 proxy.OnRequest(goproxy.ReqHostIs(srv.Listener.Addr().String())).
674 HijackConnect(func(req *http.Request, client net.Conn, ctx *goproxy.ProxyCtx) {
675 t.Logf("URL %+#v\nSTR %s", req.URL, req.URL.String())
676 resp, err := http.Get("http:" + req.URL.String() + "/bobo")
677 panicOnErr(err, "http.Get(CONNECT url)")
678 panicOnErr(resp.Write(client), "resp.Write(client)")
679 resp.Body.Close()
680 client.Close()
681 })
682 client, l := oneShotProxy(proxy, t)
683 defer l.Close()
684 proxyAddr := l.Listener.Addr().String()
685 conn, err := net.Dial("tcp", proxyAddr)
686 panicOnErr(err, "conn "+proxyAddr)
687 buf := bufio.NewReader(conn)
688 writeConnect(conn)
689 if txt := readResponse(buf); txt != "bobo" {
690 t.Error("Expected bobo for CONNECT /foo, got", txt)
691 }
692
693 if r := string(getOrFail(https.URL+"/bobo", client, t)); r != "bobo" {
694 t.Error("Expected bobo would keep working with CONNECT", r)
695 }
696 }
697
698 func readResponse(buf *bufio.Reader) string {
699 req, err := http.NewRequest("GET", srv.URL, nil)
700 panicOnErr(err, "NewRequest")
701 resp, err := http.ReadResponse(buf, req)
702 panicOnErr(err, "resp.Read")
703 defer resp.Body.Close()
704 txt, err := ioutil.ReadAll(resp.Body)
705 panicOnErr(err, "resp.Read")
706 return string(txt)
707 }
708
709 func writeConnect(w io.Writer) {
710 // this will let us use IP address of server as url in http.NewRequest by
711 // passing it as //127.0.0.1:64584 (prefixed with //).
712 // Passing IP address with port alone (without //) will raise error:
713 // "first path segment in URL cannot contain colon" more details on this
714 // here: https://github.com/golang/go/issues/18824
715 validSrvURL := srv.URL[len("http:"):]
716
717 req, err := http.NewRequest("CONNECT", validSrvURL, nil)
718 panicOnErr(err, "NewRequest")
719 req.Write(w)
720 panicOnErr(err, "req(CONNECT).Write")
721 }
722
723 func TestCurlMinusP(t *testing.T) {
724 proxy := goproxy.NewProxyHttpServer()
725 proxy.OnRequest().HandleConnectFunc(func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
726 return goproxy.HTTPMitmConnect, host
727 })
728 called := false
729 proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
730 called = true
731 return req, nil
732 })
733 _, l := oneShotProxy(proxy, t)
734 defer l.Close()
735 cmd := exec.Command("curl", "-p", "-sS", "--proxy", l.URL, srv.URL+"/bobo")
736 output, err := cmd.CombinedOutput()
737 if err != nil {
738 t.Fatal(err)
739 }
740 if string(output) != "bobo" {
741 t.Error("Expected bobo, got", string(output))
742 }
743 if !called {
744 t.Error("handler not called")
745 }
746 }
747
748 func TestSelfRequest(t *testing.T) {
749 proxy := goproxy.NewProxyHttpServer()
750 _, l := oneShotProxy(proxy, t)
751 defer l.Close()
752 if !strings.Contains(string(getOrFail(l.URL, http.DefaultClient, t)), "non-proxy") {
753 t.Fatal("non proxy requests should fail")
754 }
755 }
756
757 func TestHasGoproxyCA(t *testing.T) {
758 proxy := goproxy.NewProxyHttpServer()
759 proxy.OnRequest().HandleConnect(goproxy.AlwaysMitm)
760 s := httptest.NewServer(proxy)
761
762 proxyUrl, _ := url.Parse(s.URL)
763 goproxyCA := x509.NewCertPool()
764 goproxyCA.AddCert(goproxy.GoproxyCa.Leaf)
765
766 tr := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: goproxyCA}, Proxy: http.ProxyURL(proxyUrl)}
767 client := &http.Client{Transport: tr}
768
769 if resp := string(getOrFail(https.URL+"/bobo", client, t)); resp != "bobo" {
770 t.Error("Wrong response when mitm", resp, "expected bobo")
771 }
772 }
773
774 type TestCertStorage struct {
775 certs map[string]*tls.Certificate
776 hits int
777 misses int
778 }
779
780 func (tcs *TestCertStorage) Fetch(hostname string, gen func() (*tls.Certificate, error)) (*tls.Certificate, error) {
781 var cert *tls.Certificate
782 var err error
783 cert, ok := tcs.certs[hostname]
784 if ok {
785 fmt.Printf("hit %v\n", cert == nil)
786 tcs.hits++
787 } else {
788 cert, err = gen()
789 if err != nil {
790 return nil, err
791 }
792 fmt.Printf("miss %v\n", cert == nil)
793 tcs.certs[hostname] = cert
794 tcs.misses++
795 }
796 return cert, err
797 }
798
799 func (tcs *TestCertStorage) statHits() int {
800 return tcs.hits
801 }
802
803 func (tcs *TestCertStorage) statMisses() int {
804 return tcs.misses
805 }
806
807 func newTestCertStorage() *TestCertStorage {
808 tcs := &TestCertStorage{}
809 tcs.certs = make(map[string]*tls.Certificate)
810
811 return tcs
812 }
813
814 func TestProxyWithCertStorage(t *testing.T) {
815 tcs := newTestCertStorage()
816 t.Logf("TestProxyWithCertStorage started")
817 proxy := goproxy.NewProxyHttpServer()
818 proxy.CertStore = tcs
819 proxy.OnRequest().HandleConnect(goproxy.AlwaysMitm)
820 proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
821 req.URL.Path = "/bobo"
822 return req, nil
823 })
824
825 s := httptest.NewServer(proxy)
826
827 proxyUrl, _ := url.Parse(s.URL)
828 goproxyCA := x509.NewCertPool()
829 goproxyCA.AddCert(goproxy.GoproxyCa.Leaf)
830
831 tr := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: goproxyCA}, Proxy: http.ProxyURL(proxyUrl)}
832 client := &http.Client{Transport: tr}
833
834 if resp := string(getOrFail(https.URL+"/bobo", client, t)); resp != "bobo" {
835 t.Error("Wrong response when mitm", resp, "expected bobo")
836 }
837
838 if tcs.statHits() != 0 {
839 t.Fatalf("Expected 0 cache hits, got %d", tcs.statHits())
840 }
841 if tcs.statMisses() != 1 {
842 t.Fatalf("Expected 1 cache miss, got %d", tcs.statMisses())
843 }
844
845 // Another round - this time the certificate can be loaded
846 if resp := string(getOrFail(https.URL+"/bobo", client, t)); resp != "bobo" {
847 t.Error("Wrong response when mitm", resp, "expected bobo")
848 }
849
850 if tcs.statHits() != 1 {
851 t.Fatalf("Expected 1 cache hit, got %d", tcs.statHits())
852 }
853 if tcs.statMisses() != 1 {
854 t.Fatalf("Expected 1 cache miss, got %d", tcs.statMisses())
855 }
856 }
857
858 func TestHttpsMitmURLRewrite(t *testing.T) {
859 scheme := "https"
860
861 testCases := []struct {
862 Host string
863 RawPath string
864 AddOpaque bool
865 }{
866 {
867 Host: "example.com",
868 RawPath: "/blah/v1/data/realtime",
869 AddOpaque: true,
870 },
871 {
872 Host: "example.com:443",
873 RawPath: "/blah/v1/data/realtime?encodedURL=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile",
874 },
875 {
876 Host: "example.com:443",
877 RawPath: "/blah/v1/data/realtime?unencodedURL=https://www.googleapis.com/auth/userinfo.profile",
878 },
879 }
880
881 for _, tc := range testCases {
882 proxy := goproxy.NewProxyHttpServer()
883 proxy.OnRequest().HandleConnect(goproxy.AlwaysMitm)
884
885 proxy.OnRequest(goproxy.DstHostIs(tc.Host)).DoFunc(
886 func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
887 return nil, goproxy.TextResponse(req, "Dummy response")
888 })
889
890 client, s := oneShotProxy(proxy, t)
891 defer s.Close()
892
893 fullURL := scheme + "://" + tc.Host + tc.RawPath
894 req, err := http.NewRequest("GET", fullURL, nil)
895 if err != nil {
896 t.Fatal(err)
897 }
898
899 if tc.AddOpaque {
900 req.URL.Scheme = scheme
901 req.URL.Opaque = "//" + tc.Host + tc.RawPath
902 }
903
904 resp, err := client.Do(req)
905
906 if err != nil {
907 t.Fatal(err)
908 }
909
910 b, err := ioutil.ReadAll(resp.Body)
911 defer resp.Body.Close()
912 if err != nil {
913 t.Fatal(err)
914 }
915
916 body := string(b)
917 if body != "Dummy response" {
918 t.Errorf("Expected proxy to return dummy body content but got %s", body)
919 }
920
921 if resp.StatusCode != http.StatusAccepted {
922 t.Errorf("Expected status: %d, got: %d", http.StatusAccepted, resp.StatusCode)
923 }
924 }
925 }
926
927 func TestSimpleHttpRequest(t *testing.T) {
928 proxy := goproxy.NewProxyHttpServer()
929
930 var server *http.Server
931 go func() {
932 fmt.Println("serving end proxy server at localhost:5000")
933 server = &http.Server{
934 Addr: "localhost:5000",
935 Handler: proxy,
936 }
937 err := server.ListenAndServe()
938 if err == nil {
939 t.Error("Error shutdown should always return error", err)
940 }
941 }()
942
943 time.Sleep(1 * time.Second)
944 u, _ := url.Parse("http://localhost:5000")
945 tr := &http.Transport{
946 Proxy: http.ProxyURL(u),
947 // Disable HTTP/2.
948 TLSNextProto: make(map[string]func(authority string, c *tls.Conn) http.RoundTripper),
949 }
950 client := http.Client{Transport: tr}
951
952 resp, err := client.Get("http://example.com")
953 if err != nil {
954 t.Error("Error requesting http site", err)
955 } else if resp.StatusCode != 200 {
956 t.Error("Non-OK status requesting http site", err)
957 }
958 resp, _ = client.Get("http://example.invalid")
959 if resp == nil {
960 t.Error("No response requesting invalid http site")
961 }
962
963 returnNil := func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
964 return nil
965 }
966 proxy.OnResponse(goproxy.UrlMatches(regexp.MustCompile(".*"))).DoFunc(returnNil)
967
968 resp, _ = client.Get("http://example.invalid")
969 if resp == nil {
970 t.Error("No response requesting invalid http site")
971 }
972
973 server.Shutdown(context.TODO())
974 }
975
976 func TestResponseContentLength(t *testing.T) {
977 // target server
978 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
979 _, _ = w.Write([]byte("hello world"))
980 }))
981 defer srv.Close()
982
983 // proxy server
984 proxy := goproxy.NewProxyHttpServer()
985 proxy.OnResponse().DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
986 buf := &bytes.Buffer{}
987 buf.Write([]byte("change"))
988 resp.Body = ioutil.NopCloser(buf)
989 return resp
990 })
991 proxySrv := httptest.NewServer(proxy)
992 defer proxySrv.Close()
993
994 // send request
995 http.DefaultClient.Transport = &http.Transport{
996 Proxy: func(req *http.Request) (*url.URL, error) {
997 return url.Parse(proxySrv.URL)
998 },
999 }
1000 req, _ := http.NewRequest(http.MethodGet, srv.URL, nil)
1001 resp, _ := http.DefaultClient.Do(req)
1002
1003 body, _ := ioutil.ReadAll(resp.Body)
1004 defer resp.Body.Close()
1005
1006 if int64(len(body)) != resp.ContentLength {
1007 t.Logf("response body: %s", string(body))
1008 t.Logf("response body Length: %d", len(body))
1009 t.Logf("response Content-Length: %d", resp.ContentLength)
1010 t.Fatalf("Wrong response Content-Length.")
1011 }
1012 }