proxy_test.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. //go:build !race
  2. // +build !race
  3. /*
  4. *
  5. * Copyright 2017 gRPC authors.
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. */
  20. package transport
  21. import (
  22. "bufio"
  23. "context"
  24. "encoding/base64"
  25. "fmt"
  26. "io"
  27. "net"
  28. "net/http"
  29. "net/url"
  30. "testing"
  31. "time"
  32. )
  33. const (
  34. envTestAddr = "1.2.3.4:8080"
  35. envProxyAddr = "2.3.4.5:7687"
  36. )
  37. // overwriteAndRestore overwrite function httpProxyFromEnvironment and
  38. // returns a function to restore the default values.
  39. func overwrite(hpfe func(req *http.Request) (*url.URL, error)) func() {
  40. backHPFE := httpProxyFromEnvironment
  41. httpProxyFromEnvironment = hpfe
  42. return func() {
  43. httpProxyFromEnvironment = backHPFE
  44. }
  45. }
  46. type proxyServer struct {
  47. t *testing.T
  48. lis net.Listener
  49. in net.Conn
  50. out net.Conn
  51. requestCheck func(*http.Request) error
  52. }
  53. func (p *proxyServer) run() {
  54. in, err := p.lis.Accept()
  55. if err != nil {
  56. return
  57. }
  58. p.in = in
  59. req, err := http.ReadRequest(bufio.NewReader(in))
  60. if err != nil {
  61. p.t.Errorf("failed to read CONNECT req: %v", err)
  62. return
  63. }
  64. if err := p.requestCheck(req); err != nil {
  65. resp := http.Response{StatusCode: http.StatusMethodNotAllowed}
  66. resp.Write(p.in)
  67. p.in.Close()
  68. p.t.Errorf("get wrong CONNECT req: %+v, error: %v", req, err)
  69. return
  70. }
  71. out, err := net.Dial("tcp", req.URL.Host)
  72. if err != nil {
  73. p.t.Errorf("failed to dial to server: %v", err)
  74. return
  75. }
  76. resp := http.Response{StatusCode: http.StatusOK, Proto: "HTTP/1.0"}
  77. resp.Write(p.in)
  78. p.out = out
  79. go io.Copy(p.in, p.out)
  80. go io.Copy(p.out, p.in)
  81. }
  82. func (p *proxyServer) stop() {
  83. p.lis.Close()
  84. if p.in != nil {
  85. p.in.Close()
  86. }
  87. if p.out != nil {
  88. p.out.Close()
  89. }
  90. }
  91. func testHTTPConnect(t *testing.T, proxyURLModify func(*url.URL) *url.URL, proxyReqCheck func(*http.Request) error) {
  92. plis, err := net.Listen("tcp", "localhost:0")
  93. if err != nil {
  94. t.Fatalf("failed to listen: %v", err)
  95. }
  96. p := &proxyServer{
  97. t: t,
  98. lis: plis,
  99. requestCheck: proxyReqCheck,
  100. }
  101. go p.run()
  102. defer p.stop()
  103. blis, err := net.Listen("tcp", "localhost:0")
  104. if err != nil {
  105. t.Fatalf("failed to listen: %v", err)
  106. }
  107. msg := []byte{4, 3, 5, 2}
  108. recvBuf := make([]byte, len(msg))
  109. done := make(chan error, 1)
  110. go func() {
  111. in, err := blis.Accept()
  112. if err != nil {
  113. done <- err
  114. return
  115. }
  116. defer in.Close()
  117. in.Read(recvBuf)
  118. done <- nil
  119. }()
  120. // Overwrite the function in the test and restore them in defer.
  121. hpfe := func(req *http.Request) (*url.URL, error) {
  122. return proxyURLModify(&url.URL{Host: plis.Addr().String()}), nil
  123. }
  124. defer overwrite(hpfe)()
  125. // Dial to proxy server.
  126. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  127. defer cancel()
  128. c, err := proxyDial(ctx, blis.Addr().String(), "test")
  129. if err != nil {
  130. t.Fatalf("http connect Dial failed: %v", err)
  131. }
  132. defer c.Close()
  133. // Send msg on the connection.
  134. c.Write(msg)
  135. if err := <-done; err != nil {
  136. t.Fatalf("failed to accept: %v", err)
  137. }
  138. // Check received msg.
  139. if string(recvBuf) != string(msg) {
  140. t.Fatalf("received msg: %v, want %v", recvBuf, msg)
  141. }
  142. }
  143. func (s) TestHTTPConnect(t *testing.T) {
  144. testHTTPConnect(t,
  145. func(in *url.URL) *url.URL {
  146. return in
  147. },
  148. func(req *http.Request) error {
  149. if req.Method != http.MethodConnect {
  150. return fmt.Errorf("unexpected Method %q, want %q", req.Method, http.MethodConnect)
  151. }
  152. return nil
  153. },
  154. )
  155. }
  156. func (s) TestHTTPConnectBasicAuth(t *testing.T) {
  157. const (
  158. user = "notAUser"
  159. password = "notAPassword"
  160. )
  161. testHTTPConnect(t,
  162. func(in *url.URL) *url.URL {
  163. in.User = url.UserPassword(user, password)
  164. return in
  165. },
  166. func(req *http.Request) error {
  167. if req.Method != http.MethodConnect {
  168. return fmt.Errorf("unexpected Method %q, want %q", req.Method, http.MethodConnect)
  169. }
  170. wantProxyAuthStr := "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+password))
  171. if got := req.Header.Get(proxyAuthHeaderKey); got != wantProxyAuthStr {
  172. gotDecoded, _ := base64.StdEncoding.DecodeString(got)
  173. wantDecoded, _ := base64.StdEncoding.DecodeString(wantProxyAuthStr)
  174. return fmt.Errorf("unexpected auth %q (%q), want %q (%q)", got, gotDecoded, wantProxyAuthStr, wantDecoded)
  175. }
  176. return nil
  177. },
  178. )
  179. }
  180. func (s) TestMapAddressEnv(t *testing.T) {
  181. // Overwrite the function in the test and restore them in defer.
  182. hpfe := func(req *http.Request) (*url.URL, error) {
  183. if req.URL.Host == envTestAddr {
  184. return &url.URL{
  185. Scheme: "https",
  186. Host: envProxyAddr,
  187. }, nil
  188. }
  189. return nil, nil
  190. }
  191. defer overwrite(hpfe)()
  192. // envTestAddr should be handled by ProxyFromEnvironment.
  193. got, err := mapAddress(envTestAddr)
  194. if err != nil {
  195. t.Error(err)
  196. }
  197. if got.Host != envProxyAddr {
  198. t.Errorf("want %v, got %v", envProxyAddr, got)
  199. }
  200. }