github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/rpc/websocket_test.go (about)

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