proxy_test.go 5.6 KB

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