proxy_test.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. "google.golang.org/grpc/internal/leakcheck"
  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. defer leakcheck.Check(t)
  93. plis, err := net.Listen("tcp", "localhost:0")
  94. if err != nil {
  95. t.Fatalf("failed to listen: %v", err)
  96. }
  97. p := &proxyServer{
  98. t: t,
  99. lis: plis,
  100. requestCheck: proxyReqCheck,
  101. }
  102. go p.run()
  103. defer p.stop()
  104. blis, err := net.Listen("tcp", "localhost:0")
  105. if err != nil {
  106. t.Fatalf("failed to listen: %v", err)
  107. }
  108. msg := []byte{4, 3, 5, 2}
  109. recvBuf := make([]byte, len(msg))
  110. done := make(chan struct{})
  111. go func() {
  112. in, err := blis.Accept()
  113. if err != nil {
  114. t.Errorf("failed to accept: %v", err)
  115. return
  116. }
  117. defer in.Close()
  118. in.Read(recvBuf)
  119. close(done)
  120. }()
  121. // Overwrite the function in the test and restore them in defer.
  122. hpfe := func(req *http.Request) (*url.URL, error) {
  123. return proxyURLModify(&url.URL{Host: plis.Addr().String()}), nil
  124. }
  125. defer overwrite(hpfe)()
  126. // Dial to proxy server.
  127. dialer := newProxyDialer(func(ctx context.Context, addr string) (net.Conn, error) {
  128. if deadline, ok := ctx.Deadline(); ok {
  129. return net.DialTimeout("tcp", addr, deadline.Sub(time.Now()))
  130. }
  131. return net.Dial("tcp", addr)
  132. })
  133. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  134. defer cancel()
  135. c, err := dialer(ctx, blis.Addr().String())
  136. if err != nil {
  137. t.Fatalf("http connect Dial failed: %v", err)
  138. }
  139. defer c.Close()
  140. // Send msg on the connection.
  141. c.Write(msg)
  142. <-done
  143. // Check received msg.
  144. if string(recvBuf) != string(msg) {
  145. t.Fatalf("received msg: %v, want %v", recvBuf, msg)
  146. }
  147. }
  148. func 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 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 TestMapAddressEnv(t *testing.T) {
  192. defer leakcheck.Check(t)
  193. // Overwrite the function in the test and restore them in defer.
  194. hpfe := func(req *http.Request) (*url.URL, error) {
  195. if req.URL.Host == envTestAddr {
  196. return &url.URL{
  197. Scheme: "https",
  198. Host: envProxyAddr,
  199. }, nil
  200. }
  201. return nil, nil
  202. }
  203. defer overwrite(hpfe)()
  204. // envTestAddr should be handled by ProxyFromEnvironment.
  205. got, err := mapAddress(context.Background(), envTestAddr)
  206. if err != nil {
  207. t.Error(err)
  208. }
  209. if got.Host != envProxyAddr {
  210. t.Errorf("want %v, got %v", envProxyAddr, got)
  211. }
  212. }