websocket_test.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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. resultChan := make(chan int)
  116. sub, err := client.EthSubscribe(ctx, resultChan, "foo")
  117. if err != nil {
  118. t.Fatalf("client subscribe error: %v", err)
  119. }
  120. // Wait for the context's deadline to be reached before proceeding.
  121. // This is important for reproducing https://github.com/ethereum/go-ethereum/issues/19798
  122. <-ctx.Done()
  123. close(sendPing)
  124. // Wait for the subscription result.
  125. timeout := time.NewTimer(5 * time.Second)
  126. defer timeout.Stop()
  127. for {
  128. select {
  129. case err := <-sub.Err():
  130. t.Error("client subscription error:", err)
  131. case result := <-resultChan:
  132. t.Log("client got result:", result)
  133. return
  134. case <-timeout.C:
  135. t.Error("didn't get any result within the test timeout")
  136. return
  137. }
  138. }
  139. }
  140. // This checks that the websocket transport can deal with large messages.
  141. func TestClientWebsocketLargeMessage(t *testing.T) {
  142. var (
  143. srv = NewServer()
  144. httpsrv = httptest.NewServer(srv.WebsocketHandler(nil))
  145. wsURL = "ws:" + strings.TrimPrefix(httpsrv.URL, "http:")
  146. )
  147. defer srv.Stop()
  148. defer httpsrv.Close()
  149. respLength := wsMessageSizeLimit - 50
  150. srv.RegisterName("test", largeRespService{respLength})
  151. c, err := DialWebsocket(context.Background(), wsURL, "")
  152. if err != nil {
  153. t.Fatal(err)
  154. }
  155. var r string
  156. if err := c.Call(&r, "test_largeResp"); err != nil {
  157. t.Fatal("call failed:", err)
  158. }
  159. if len(r) != respLength {
  160. t.Fatalf("response has wrong length %d, want %d", len(r), respLength)
  161. }
  162. }
  163. // wsPingTestServer runs a WebSocket server which accepts a single subscription request.
  164. // When a value arrives on sendPing, the server sends a ping frame, waits for a matching
  165. // pong and finally delivers a single subscription result.
  166. func wsPingTestServer(t *testing.T, sendPing <-chan struct{}) *http.Server {
  167. var srv http.Server
  168. shutdown := make(chan struct{})
  169. srv.RegisterOnShutdown(func() {
  170. close(shutdown)
  171. })
  172. srv.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  173. // Upgrade to WebSocket.
  174. upgrader := websocket.Upgrader{
  175. CheckOrigin: func(r *http.Request) bool { return true },
  176. }
  177. conn, err := upgrader.Upgrade(w, r, nil)
  178. if err != nil {
  179. t.Errorf("server WS upgrade error: %v", err)
  180. return
  181. }
  182. defer conn.Close()
  183. // Handle the connection.
  184. wsPingTestHandler(t, conn, shutdown, sendPing)
  185. })
  186. // Start the server.
  187. listener, err := net.Listen("tcp", "127.0.0.1:0")
  188. if err != nil {
  189. t.Fatal("can't listen:", err)
  190. }
  191. srv.Addr = listener.Addr().String()
  192. go srv.Serve(listener)
  193. return &srv
  194. }
  195. func wsPingTestHandler(t *testing.T, conn *websocket.Conn, shutdown, sendPing <-chan struct{}) {
  196. // Canned responses for the eth_subscribe call in TestClientWebsocketPing.
  197. const (
  198. subResp = `{"jsonrpc":"2.0","id":1,"result":"0x00"}`
  199. subNotify = `{"jsonrpc":"2.0","method":"eth_subscription","params":{"subscription":"0x00","result":1}}`
  200. )
  201. // Handle subscribe request.
  202. if _, _, err := conn.ReadMessage(); err != nil {
  203. t.Errorf("server read error: %v", err)
  204. return
  205. }
  206. if err := conn.WriteMessage(websocket.TextMessage, []byte(subResp)); err != nil {
  207. t.Errorf("server write error: %v", err)
  208. return
  209. }
  210. // Read from the connection to process control messages.
  211. var pongCh = make(chan string)
  212. conn.SetPongHandler(func(d string) error {
  213. t.Logf("server got pong: %q", d)
  214. pongCh <- d
  215. return nil
  216. })
  217. go func() {
  218. for {
  219. typ, msg, err := conn.ReadMessage()
  220. if err != nil {
  221. return
  222. }
  223. t.Logf("server got message (%d): %q", typ, msg)
  224. }
  225. }()
  226. // Write messages.
  227. var (
  228. wantPong string
  229. timer = time.NewTimer(0)
  230. )
  231. defer timer.Stop()
  232. <-timer.C
  233. for {
  234. select {
  235. case _, open := <-sendPing:
  236. if !open {
  237. sendPing = nil
  238. }
  239. t.Logf("server sending ping")
  240. conn.WriteMessage(websocket.PingMessage, []byte("ping"))
  241. wantPong = "ping"
  242. case data := <-pongCh:
  243. if wantPong == "" {
  244. t.Errorf("unexpected pong")
  245. } else if data != wantPong {
  246. t.Errorf("got pong with wrong data %q", data)
  247. }
  248. wantPong = ""
  249. timer.Reset(200 * time.Millisecond)
  250. case <-timer.C:
  251. t.Logf("server sending response")
  252. conn.WriteMessage(websocket.TextMessage, []byte(subNotify))
  253. case <-shutdown:
  254. conn.Close()
  255. return
  256. }
  257. }
  258. }