github.com/stafiprotocol/go-substrate-rpc-client@v1.4.7/pkg/gethrpc/websocket_test.go (about) 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 17 package rpc 18 19 import ( 20 "context" 21 "net" 22 "net/http" 23 "net/http/httptest" 24 "reflect" 25 "strings" 26 "testing" 27 "time" 28 29 "github.com/gorilla/websocket" 30 ) 31 32 func TestWebsocketClientHeaders(t *testing.T) { 33 t.Parallel() 34 35 endpoint, header, err := wsClientHeaders("wss://testuser:test-PASS_01@example.com:1234", "https://example.com") 36 if err != nil { 37 t.Fatalf("wsGetConfig failed: %s", err) 38 } 39 if endpoint != "wss://example.com:1234" { 40 t.Fatal("User should have been stripped from the URL") 41 } 42 if header.Get("authorization") != "Basic dGVzdHVzZXI6dGVzdC1QQVNTXzAx" { 43 t.Fatal("Basic auth header is incorrect") 44 } 45 if header.Get("origin") != "https://example.com" { 46 t.Fatal("Origin not set") 47 } 48 } 49 50 // This test checks that the server rejects connections from disallowed origins. 51 func TestWebsocketOriginCheck(t *testing.T) { 52 t.Parallel() 53 54 var ( 55 srv = newTestServer() 56 httpsrv = httptest.NewServer(srv.WebsocketHandler([]string{"http://example.com"})) 57 wsURL = "ws:" + strings.TrimPrefix(httpsrv.URL, "http:") 58 ) 59 defer srv.Stop() 60 defer httpsrv.Close() 61 62 client, err := DialWebsocket(context.Background(), wsURL, "http://ekzample.com") 63 if err == nil { 64 client.Close() 65 t.Fatal("no error for wrong origin") 66 } 67 wantErr := wsHandshakeError{websocket.ErrBadHandshake, "403 Forbidden"} 68 if !reflect.DeepEqual(err, wantErr) { 69 t.Fatalf("wrong error for wrong origin: %q", err) 70 } 71 72 // Connections without origin header should work. 73 client, err = DialWebsocket(context.Background(), wsURL, "") 74 if err != nil { 75 t.Fatal("error for empty origin") 76 } 77 client.Close() 78 } 79 80 // This test checks whether calls exceeding the request size limit are rejected. 81 func TestWebsocketLargeCall(t *testing.T) { 82 t.Parallel() 83 84 var ( 85 srv = newTestServer() 86 httpsrv = httptest.NewServer(srv.WebsocketHandler([]string{"*"})) 87 wsURL = "ws:" + strings.TrimPrefix(httpsrv.URL, "http:") 88 ) 89 defer srv.Stop() 90 defer httpsrv.Close() 91 92 client, err := DialWebsocket(context.Background(), wsURL, "") 93 if err != nil { 94 t.Fatalf("can't dial: %v", err) 95 } 96 defer client.Close() 97 98 // This call sends slightly less than the limit and should work. 99 var result Result 100 arg := strings.Repeat("x", maxRequestContentLength-200) 101 if err := client.Call(&result, "test_echo", arg, 1); err != nil { 102 t.Fatalf("valid call didn't work: %v", err) 103 } 104 if result.String != arg { 105 t.Fatal("wrong string echoed") 106 } 107 108 // This call sends twice the allowed size and shouldn't work. 109 arg = strings.Repeat("x", maxRequestContentLength*2) 110 err = client.Call(&result, "test_echo", arg) 111 if err == nil { 112 t.Fatal("no error for too large call") 113 } 114 } 115 116 // This test checks that client handles WebSocket ping frames correctly. 117 118 // wsPingTestServer runs a WebSocket server which accepts a single subscription request. 119 // When a value arrives on sendPing, the server sends a ping frame, waits for a matching 120 // pong and finally delivers a single subscription result. 121 func wsPingTestServer(t *testing.T, sendPing <-chan struct{}) *http.Server { 122 var srv http.Server 123 shutdown := make(chan struct{}) 124 srv.RegisterOnShutdown(func() { 125 close(shutdown) 126 }) 127 srv.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 128 // Upgrade to WebSocket. 129 upgrader := websocket.Upgrader{ 130 CheckOrigin: func(r *http.Request) bool { return true }, 131 } 132 conn, err := upgrader.Upgrade(w, r, nil) 133 if err != nil { 134 t.Errorf("server WS upgrade error: %v", err) 135 return 136 } 137 defer conn.Close() 138 139 // Handle the connection. 140 wsPingTestHandler(t, conn, shutdown, sendPing) 141 }) 142 143 // Start the server. 144 listener, err := net.Listen("tcp", "127.0.0.1:0") 145 if err != nil { 146 t.Fatal("can't listen:", err) 147 } 148 srv.Addr = listener.Addr().String() 149 go srv.Serve(listener) 150 return &srv 151 } 152 153 func wsPingTestHandler(t *testing.T, conn *websocket.Conn, shutdown, sendPing <-chan struct{}) { 154 // Canned responses for the eth_subscribe call in TestClientWebsocketPing. 155 const ( 156 subResp = `{"jsonrpc":"2.0","id":1,"result":"0x00"}` 157 subNotify = `{"jsonrpc":"2.0","method":"eth_subscription","params":{"subscription":"0x00","result":1}}` 158 ) 159 160 // Handle subscribe request. 161 if _, _, err := conn.ReadMessage(); err != nil { 162 t.Errorf("server read error: %v", err) 163 return 164 } 165 if err := conn.WriteMessage(websocket.TextMessage, []byte(subResp)); err != nil { 166 t.Errorf("server write error: %v", err) 167 return 168 } 169 170 // Read from the connection to process control messages. 171 var pongCh = make(chan string) 172 conn.SetPongHandler(func(d string) error { 173 t.Logf("server got pong: %q", d) 174 pongCh <- d 175 return nil 176 }) 177 go func() { 178 for { 179 typ, msg, err := conn.ReadMessage() 180 if err != nil { 181 return 182 } 183 t.Logf("server got message (%d): %q", typ, msg) 184 } 185 }() 186 187 // Write messages. 188 var ( 189 sendResponse <-chan time.Time 190 wantPong string 191 ) 192 for { 193 select { 194 case _, open := <-sendPing: 195 if !open { 196 sendPing = nil 197 } 198 t.Logf("server sending ping") 199 conn.WriteMessage(websocket.PingMessage, []byte("ping")) 200 wantPong = "ping" 201 case data := <-pongCh: 202 if wantPong == "" { 203 t.Errorf("unexpected pong") 204 } else if data != wantPong { 205 t.Errorf("got pong with wrong data %q", data) 206 } 207 wantPong = "" 208 sendResponse = time.NewTimer(200 * time.Millisecond).C 209 case <-sendResponse: 210 t.Logf("server sending response") 211 conn.WriteMessage(websocket.TextMessage, []byte(subNotify)) 212 sendResponse = nil 213 case <-shutdown: 214 conn.Close() 215 return 216 } 217 } 218 }