websocket_test.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package rpc
  17. import (
  18. "context"
  19. "net"
  20. "net/http"
  21. "net/http/httptest"
  22. "reflect"
  23. "strings"
  24. "testing"
  25. "time"
  26. "github.com/gorilla/websocket"
  27. )
  28. func TestWebsocketClientHeaders(t *testing.T) {
  29. t.Parallel()
  30. endpoint, header, err := wsClientHeaders("wss://testuser:test-PASS_01@example.com:1234", "https://example.com")
  31. if err != nil {
  32. t.Fatalf("wsGetConfig failed: %s", err)
  33. }
  34. if endpoint != "wss://example.com:1234" {
  35. t.Fatal("User should have been stripped from the URL")
  36. }
  37. if header.Get("authorization") != "Basic dGVzdHVzZXI6dGVzdC1QQVNTXzAx" {
  38. t.Fatal("Basic auth header is incorrect")
  39. }
  40. if header.Get("origin") != "https://example.com" {
  41. t.Fatal("Origin not set")
  42. }
  43. }
  44. // This test checks that the server rejects connections from disallowed origins.
  45. func TestWebsocketOriginCheck(t *testing.T) {
  46. t.Parallel()
  47. var (
  48. srv = newTestServer()
  49. httpsrv = httptest.NewServer(srv.WebsocketHandler([]string{"http://example.com"}))
  50. wsURL = "ws:" + strings.TrimPrefix(httpsrv.URL, "http:")
  51. )
  52. defer srv.Stop()
  53. defer httpsrv.Close()
  54. client, err := DialWebsocket(context.Background(), wsURL, "http://ekzample.com")
  55. if err == nil {
  56. client.Close()
  57. t.Fatal("no error for wrong origin")
  58. }
  59. wantErr := wsHandshakeError{websocket.ErrBadHandshake, "403 Forbidden"}
  60. if !reflect.DeepEqual(err, wantErr) {
  61. t.Fatalf("wrong error for wrong origin: %q", err)
  62. }
  63. // Connections without origin header should work.
  64. client, err = DialWebsocket(context.Background(), wsURL, "")
  65. if err != nil {
  66. t.Fatal("error for empty origin")
  67. }
  68. client.Close()
  69. }
  70. // This test checks whether calls exceeding the request size limit are rejected.
  71. func TestWebsocketLargeCall(t *testing.T) {
  72. t.Parallel()
  73. var (
  74. srv = newTestServer()
  75. httpsrv = httptest.NewServer(srv.WebsocketHandler([]string{"*"}))
  76. wsURL = "ws:" + strings.TrimPrefix(httpsrv.URL, "http:")
  77. )
  78. defer srv.Stop()
  79. defer httpsrv.Close()
  80. client, err := DialWebsocket(context.Background(), wsURL, "")
  81. if err != nil {
  82. t.Fatalf("can't dial: %v", err)
  83. }
  84. defer client.Close()
  85. // This call sends slightly less than the limit and should work.
  86. var result echoResult
  87. arg := strings.Repeat("x", maxRequestContentLength-200)
  88. if err := client.Call(&result, "test_echo", arg, 1); err != nil {
  89. t.Fatalf("valid call didn't work: %v", err)
  90. }
  91. if result.String != arg {
  92. t.Fatal("wrong string echoed")
  93. }
  94. // This call sends twice the allowed size and shouldn't work.
  95. arg = strings.Repeat("x", maxRequestContentLength*2)
  96. err = client.Call(&result, "test_echo", arg)
  97. if err == nil {
  98. t.Fatal("no error for too large call")
  99. }
  100. }
  101. // This test checks that client handles WebSocket ping frames correctly.
  102. func TestClientWebsocketPing(t *testing.T) {
  103. t.Parallel()
  104. var (
  105. sendPing = make(chan struct{})
  106. server = wsPingTestServer(t, sendPing)
  107. ctx, cancel = context.WithTimeout(context.Background(), 1*time.Second)
  108. )
  109. defer cancel()
  110. defer server.Shutdown(ctx)
  111. client, err := DialContext(ctx, "ws://"+server.Addr)
  112. if err != nil {
  113. t.Fatalf("client dial error: %v", err)
  114. }
  115. defer client.Close()
  116. resultChan := make(chan int)
  117. sub, err := client.EthSubscribe(ctx, resultChan, "foo")
  118. if err != nil {
  119. t.Fatalf("client subscribe error: %v", err)
  120. }
  121. // Note: Unsubscribe is not called on this subscription because the mockup
  122. // server can't handle the request.
  123. // Wait for the context's deadline to be reached before proceeding.
  124. // This is important for reproducing https://github.com/ethereum/go-ethereum/issues/19798
  125. <-ctx.Done()
  126. close(sendPing)
  127. // Wait for the subscription result.
  128. timeout := time.NewTimer(5 * time.Second)
  129. defer timeout.Stop()
  130. for {
  131. select {
  132. case err := <-sub.Err():
  133. t.Error("client subscription error:", err)
  134. case result := <-resultChan:
  135. t.Log("client got result:", result)
  136. return
  137. case <-timeout.C:
  138. t.Error("didn't get any result within the test timeout")
  139. return
  140. }
  141. }
  142. }
  143. // This checks that the websocket transport can deal with large messages.
  144. func TestClientWebsocketLargeMessage(t *testing.T) {
  145. var (
  146. srv = NewServer()
  147. httpsrv = httptest.NewServer(srv.WebsocketHandler(nil))
  148. wsURL = "ws:" + strings.TrimPrefix(httpsrv.URL, "http:")
  149. )
  150. defer srv.Stop()
  151. defer httpsrv.Close()
  152. respLength := wsMessageSizeLimit - 50
  153. srv.RegisterName("test", largeRespService{respLength})
  154. c, err := DialWebsocket(context.Background(), wsURL, "")
  155. if err != nil {
  156. t.Fatal(err)
  157. }
  158. var r string
  159. if err := c.Call(&r, "test_largeResp"); err != nil {
  160. t.Fatal("call failed:", err)
  161. }
  162. if len(r) != respLength {
  163. t.Fatalf("response has wrong length %d, want %d", len(r), respLength)
  164. }
  165. }
  166. // wsPingTestServer runs a WebSocket server which accepts a single subscription request.
  167. // When a value arrives on sendPing, the server sends a ping frame, waits for a matching
  168. // pong and finally delivers a single subscription result.
  169. func wsPingTestServer(t *testing.T, sendPing <-chan struct{}) *http.Server {
  170. var srv http.Server
  171. shutdown := make(chan struct{})
  172. srv.RegisterOnShutdown(func() {
  173. close(shutdown)
  174. })
  175. srv.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  176. // Upgrade to WebSocket.
  177. upgrader := websocket.Upgrader{
  178. CheckOrigin: func(r *http.Request) bool { return true },
  179. }
  180. conn, err := upgrader.Upgrade(w, r, nil)
  181. if err != nil {
  182. t.Errorf("server WS upgrade error: %v", err)
  183. return
  184. }
  185. defer conn.Close()
  186. // Handle the connection.
  187. wsPingTestHandler(t, conn, shutdown, sendPing)
  188. })
  189. // Start the server.
  190. listener, err := net.Listen("tcp", "127.0.0.1:0")
  191. if err != nil {
  192. t.Fatal("can't listen:", err)
  193. }
  194. srv.Addr = listener.Addr().String()
  195. go srv.Serve(listener)
  196. return &srv
  197. }
  198. func wsPingTestHandler(t *testing.T, conn *websocket.Conn, shutdown, sendPing <-chan struct{}) {
  199. // Canned responses for the eth_subscribe call in TestClientWebsocketPing.
  200. const (
  201. subResp = `{"jsonrpc":"2.0","id":1,"result":"0x00"}`
  202. subNotify = `{"jsonrpc":"2.0","method":"eth_subscription","params":{"subscription":"0x00","result":1}}`
  203. )
  204. // Handle subscribe request.
  205. if _, _, err := conn.ReadMessage(); err != nil {
  206. t.Errorf("server read error: %v", err)
  207. return
  208. }
  209. if err := conn.WriteMessage(websocket.TextMessage, []byte(subResp)); err != nil {
  210. t.Errorf("server write error: %v", err)
  211. return
  212. }
  213. // Read from the connection to process control messages.
  214. var pongCh = make(chan string)
  215. conn.SetPongHandler(func(d string) error {
  216. t.Logf("server got pong: %q", d)
  217. pongCh <- d
  218. return nil
  219. })
  220. go func() {
  221. for {
  222. typ, msg, err := conn.ReadMessage()
  223. if err != nil {
  224. return
  225. }
  226. t.Logf("server got message (%d): %q", typ, msg)
  227. }
  228. }()
  229. // Write messages.
  230. var (
  231. wantPong string
  232. timer = time.NewTimer(0)
  233. )
  234. defer timer.Stop()
  235. <-timer.C
  236. for {
  237. select {
  238. case _, open := <-sendPing:
  239. if !open {
  240. sendPing = nil
  241. }
  242. t.Logf("server sending ping")
  243. conn.WriteMessage(websocket.PingMessage, []byte("ping"))
  244. wantPong = "ping"
  245. case data := <-pongCh:
  246. if wantPong == "" {
  247. t.Errorf("unexpected pong")
  248. } else if data != wantPong {
  249. t.Errorf("got pong with wrong data %q", data)
  250. }
  251. wantPong = ""
  252. timer.Reset(200 * time.Millisecond)
  253. case <-timer.C:
  254. t.Logf("server sending response")
  255. conn.WriteMessage(websocket.TextMessage, []byte(subNotify))
  256. case <-shutdown:
  257. conn.Close()
  258. return
  259. }
  260. }
  261. }