rpcstack_test.go 13.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Copyright 2020 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

17 18 19
package node

import (
20
	"bytes"
21
	"fmt"
22
	"net/http"
23 24
	"net/url"
	"strconv"
25
	"strings"
26
	"testing"
27
	"time"
28

29 30
	"github.com/ethereum/go-ethereum/internal/testlog"
	"github.com/ethereum/go-ethereum/log"
31
	"github.com/ethereum/go-ethereum/rpc"
32
	"github.com/golang-jwt/jwt/v4"
33
	"github.com/gorilla/websocket"
34 35 36
	"github.com/stretchr/testify/assert"
)

37 38
// TestCorsHandler makes sure CORS are properly handled on the http server.
func TestCorsHandler(t *testing.T) {
39
	srv := createAndStartServer(t, &httpConfig{CorsAllowedOrigins: []string{"test", "test.com"}}, false, &wsConfig{})
40
	defer srv.stop()
41
	url := "http://" + srv.listenAddr()
42

43
	resp := rpcRequest(t, url, "origin", "test.com")
44 45
	assert.Equal(t, "test.com", resp.Header.Get("Access-Control-Allow-Origin"))

46
	resp2 := rpcRequest(t, url, "origin", "bad")
47 48 49 50 51
	assert.Equal(t, "", resp2.Header.Get("Access-Control-Allow-Origin"))
}

// TestVhosts makes sure vhosts are properly handled on the http server.
func TestVhosts(t *testing.T) {
52
	srv := createAndStartServer(t, &httpConfig{Vhosts: []string{"test"}}, false, &wsConfig{})
53
	defer srv.stop()
54
	url := "http://" + srv.listenAddr()
55

56
	resp := rpcRequest(t, url, "host", "test")
57 58
	assert.Equal(t, resp.StatusCode, http.StatusOK)

59
	resp2 := rpcRequest(t, url, "host", "bad")
60 61
	assert.Equal(t, resp2.StatusCode, http.StatusForbidden)
}
62

63 64 65 66 67
type originTest struct {
	spec    string
	expOk   []string
	expFail []string
}
68

69 70 71 72 73 74 75 76 77 78 79 80 81
// splitAndTrim splits input separated by a comma
// and trims excessive white space from the substrings.
// Copied over from flags.go
func splitAndTrim(input string) (ret []string) {
	l := strings.Split(input, ",")
	for _, r := range l {
		r = strings.TrimSpace(r)
		if len(r) > 0 {
			ret = append(ret, r)
		}
	}
	return ret
}
82

83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
// TestWebsocketOrigins makes sure the websocket origins are properly handled on the websocket server.
func TestWebsocketOrigins(t *testing.T) {
	tests := []originTest{
		{
			spec: "*", // allow all
			expOk: []string{"", "http://test", "https://test", "http://test:8540", "https://test:8540",
				"http://test.com", "https://foo.test", "http://testa", "http://atestb:8540", "https://atestb:8540"},
		},
		{
			spec:    "test",
			expOk:   []string{"http://test", "https://test", "http://test:8540", "https://test:8540"},
			expFail: []string{"http://test.com", "https://foo.test", "http://testa", "http://atestb:8540", "https://atestb:8540"},
		},
		// scheme tests
		{
			spec:  "https://test",
			expOk: []string{"https://test", "https://test:9999"},
			expFail: []string{
				"test",                                // no scheme, required by spec
				"http://test",                         // wrong scheme
103
				"http://test.foo", "https://a.test.x", // subdomain variations
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
				"http://testx:8540", "https://xtest:8540"},
		},
		// ip tests
		{
			spec:  "https://12.34.56.78",
			expOk: []string{"https://12.34.56.78", "https://12.34.56.78:8540"},
			expFail: []string{
				"http://12.34.56.78",     // wrong scheme
				"http://12.34.56.78:443", // wrong scheme
				"http://1.12.34.56.78",   // wrong 'domain name'
				"http://12.34.56.78.a",   // wrong 'domain name'
				"https://87.65.43.21", "http://87.65.43.21:8540", "https://87.65.43.21:8540"},
		},
		// port tests
		{
			spec:  "test:8540",
			expOk: []string{"http://test:8540", "https://test:8540"},
			expFail: []string{
				"http://test", "https://test", // spec says port required
				"http://test:8541", "https://test:8541", // wrong port
				"http://bad", "https://bad", "http://bad:8540", "https://bad:8540"},
		},
		// scheme and port
		{
			spec:  "https://test:8540",
			expOk: []string{"https://test:8540"},
			expFail: []string{
				"https://test",                          // missing port
				"http://test",                           // missing port, + wrong scheme
				"http://test:8540",                      // wrong scheme
				"http://test:8541", "https://test:8541", // wrong port
				"http://bad", "https://bad", "http://bad:8540", "https://bad:8540"},
		},
		// several allowed origins
		{
			spec: "localhost,http://127.0.0.1",
			expOk: []string{"localhost", "http://localhost", "https://localhost:8443",
				"http://127.0.0.1", "http://127.0.0.1:8080"},
			expFail: []string{
				"https://127.0.0.1", // wrong scheme
				"http://bad", "https://bad", "http://bad:8540", "https://bad:8540"},
		},
	}
	for _, tc := range tests {
148 149
		srv := createAndStartServer(t, &httpConfig{}, true, &wsConfig{Origins: splitAndTrim(tc.spec)})
		url := fmt.Sprintf("ws://%v", srv.listenAddr())
150
		for _, origin := range tc.expOk {
151
			if err := wsRequest(t, url, "Origin", origin); err != nil {
152 153 154 155
				t.Errorf("spec '%v', origin '%v': expected ok, got %v", tc.spec, origin, err)
			}
		}
		for _, origin := range tc.expFail {
156
			if err := wsRequest(t, url, "Origin", origin); err == nil {
157 158 159 160 161
				t.Errorf("spec '%v', origin '%v': expected not to allow,  got ok", tc.spec, origin)
			}
		}
		srv.stop()
	}
162 163
}

164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
// TestIsWebsocket tests if an incoming websocket upgrade request is handled properly.
func TestIsWebsocket(t *testing.T) {
	r, _ := http.NewRequest("GET", "/", nil)

	assert.False(t, isWebsocket(r))
	r.Header.Set("upgrade", "websocket")
	assert.False(t, isWebsocket(r))
	r.Header.Set("connection", "upgrade")
	assert.True(t, isWebsocket(r))
	r.Header.Set("connection", "upgrade,keep-alive")
	assert.True(t, isWebsocket(r))
	r.Header.Set("connection", " UPGRADE,keep-alive")
	assert.True(t, isWebsocket(r))
}

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
func Test_checkPath(t *testing.T) {
	tests := []struct {
		req      *http.Request
		prefix   string
		expected bool
	}{
		{
			req:      &http.Request{URL: &url.URL{Path: "/test"}},
			prefix:   "/test",
			expected: true,
		},
		{
			req:      &http.Request{URL: &url.URL{Path: "/testing"}},
			prefix:   "/test",
			expected: true,
		},
		{
			req:      &http.Request{URL: &url.URL{Path: "/"}},
			prefix:   "/test",
			expected: false,
		},
		{
			req:      &http.Request{URL: &url.URL{Path: "/fail"}},
			prefix:   "/test",
			expected: false,
		},
		{
			req:      &http.Request{URL: &url.URL{Path: "/"}},
			prefix:   "",
			expected: true,
		},
		{
			req:      &http.Request{URL: &url.URL{Path: "/fail"}},
			prefix:   "",
			expected: false,
		},
		{
			req:      &http.Request{URL: &url.URL{Path: "/"}},
			prefix:   "/",
			expected: true,
		},
		{
			req:      &http.Request{URL: &url.URL{Path: "/testing"}},
			prefix:   "/",
			expected: true,
		},
	}

	for i, tt := range tests {
		t.Run(strconv.Itoa(i), func(t *testing.T) {
			assert.Equal(t, tt.expected, checkPath(tt.req, tt.prefix))
		})
	}
}

func createAndStartServer(t *testing.T, conf *httpConfig, ws bool, wsConf *wsConfig) *httpServer {
235 236 237
	t.Helper()

	srv := newHTTPServer(testlog.Logger(t, log.LvlDebug), rpc.DefaultHTTPTimeouts)
238
	assert.NoError(t, srv.enableRPC(nil, *conf))
239
	if ws {
240
		assert.NoError(t, srv.enableWS(nil, *wsConf))
241 242 243 244 245
	}
	assert.NoError(t, srv.setListenAddr("localhost", 0))
	assert.NoError(t, srv.start())
	return srv
}
246

247
// wsRequest attempts to open a WebSocket connection to the given URL.
248
func wsRequest(t *testing.T, url string, extraHeaders ...string) error {
249
	t.Helper()
250
	//t.Logf("checking WebSocket on %s (origin %q)", url, browserOrigin)
251 252

	headers := make(http.Header)
253 254 255 256 257 258 259
	// Apply extra headers.
	if len(extraHeaders)%2 != 0 {
		panic("odd extraHeaders length")
	}
	for i := 0; i < len(extraHeaders); i += 2 {
		key, value := extraHeaders[i], extraHeaders[i+1]
		headers.Set(key, value)
260 261 262 263 264
	}
	conn, _, err := websocket.DefaultDialer.Dial(url, headers)
	if conn != nil {
		conn.Close()
	}
265 266 267
	return err
}

268 269
// rpcRequest performs a JSON-RPC request to the given URL.
func rpcRequest(t *testing.T, url string, extraHeaders ...string) *http.Response {
270
	t.Helper()
271

272 273 274 275 276 277
	// Create the request.
	body := bytes.NewReader([]byte(`{"jsonrpc":"2.0","id":1,"method":"rpc_modules","params":[]}`))
	req, err := http.NewRequest("POST", url, body)
	if err != nil {
		t.Fatal("could not create http request:", err)
	}
278
	req.Header.Set("content-type", "application/json")
279 280 281 282

	// Apply extra headers.
	if len(extraHeaders)%2 != 0 {
		panic("odd extraHeaders length")
283
	}
284 285
	for i := 0; i < len(extraHeaders); i += 2 {
		key, value := extraHeaders[i], extraHeaders[i+1]
286
		if strings.EqualFold(key, "host") {
287 288 289 290
			req.Host = value
		} else {
			req.Header.Set(key, value)
		}
291
	}
292

293 294 295
	// Perform the request.
	t.Logf("checking RPC/HTTP on %s %v", url, extraHeaders)
	resp, err := http.DefaultClient.Do(req)
296 297 298 299
	if err != nil {
		t.Fatal(err)
	}
	return resp
300
}
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316

type testClaim map[string]interface{}

func (testClaim) Valid() error {
	return nil
}

func TestJWT(t *testing.T) {
	var secret = []byte("secret")
	issueToken := func(secret []byte, method jwt.SigningMethod, input map[string]interface{}) string {
		if method == nil {
			method = jwt.SigningMethodHS256
		}
		ss, _ := jwt.NewWithClaims(method, testClaim(input)).SignedString(secret)
		return ss
	}
317 318 319 320 321
	srv := createAndStartServer(t, &httpConfig{jwtSecret: []byte("secret")},
		true, &wsConfig{Origins: []string{"*"}, jwtSecret: []byte("secret")})
	wsUrl := fmt.Sprintf("ws://%v", srv.listenAddr())
	htUrl := fmt.Sprintf("http://%v", srv.listenAddr())

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
	expOk := []func() string{
		func() string {
			return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix()}))
		},
		func() string {
			return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix() + 4}))
		},
		func() string {
			return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix() - 4}))
		},
		func() string {
			return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{
				"iat": time.Now().Unix(),
				"exp": time.Now().Unix() + 2,
			}))
		},
		func() string {
			return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{
				"iat": time.Now().Unix(),
				"bar": "baz",
			}))
		},
344
	}
345 346
	for i, tokenFn := range expOk {
		token := tokenFn()
347 348 349
		if err := wsRequest(t, wsUrl, "Authorization", token); err != nil {
			t.Errorf("test %d-ws, token '%v': expected ok, got %v", i, token, err)
		}
350
		token = tokenFn()
351 352 353 354
		if resp := rpcRequest(t, htUrl, "Authorization", token); resp.StatusCode != 200 {
			t.Errorf("test %d-http, token '%v': expected ok, got %v", i, token, resp.StatusCode)
		}
	}
355 356

	expFail := []func() string{
357
		// future
358
		func() string {
359
			return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix() + int64(jwtExpiryTimeout.Seconds()) + 1}))
360
		},
361
		// stale
362
		func() string {
363
			return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix() - int64(jwtExpiryTimeout.Seconds()) - 1}))
364
		},
365
		// wrong algo
366 367 368
		func() string {
			return fmt.Sprintf("Bearer %v", issueToken(secret, jwt.SigningMethodHS512, testClaim{"iat": time.Now().Unix() + 4}))
		},
369
		// expired
370 371 372
		func() string {
			return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix(), "exp": time.Now().Unix()}))
		},
373
		// missing mandatory iat
374 375 376 377 378 379 380 381 382 383 384 385 386
		func() string {
			return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{}))
		},
		//  wrong secret
		func() string {
			return fmt.Sprintf("Bearer %v", issueToken([]byte("wrong"), nil, testClaim{"iat": time.Now().Unix()}))
		},
		func() string {
			return fmt.Sprintf("Bearer %v", issueToken([]byte{}, nil, testClaim{"iat": time.Now().Unix()}))
		},
		func() string {
			return fmt.Sprintf("Bearer %v", issueToken(nil, nil, testClaim{"iat": time.Now().Unix()}))
		},
387
		// Various malformed syntax
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
		func() string {
			return fmt.Sprintf("%v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix()}))
		},
		func() string {
			return fmt.Sprintf("Bearer  %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix()}))
		},
		func() string {
			return fmt.Sprintf("bearer %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix()}))
		},
		func() string {
			return fmt.Sprintf("Bearer: %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix()}))
		},
		func() string {
			return fmt.Sprintf("Bearer:%v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix()}))
		},
		func() string {
			return fmt.Sprintf("Bearer\t%v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix()}))
		},
		func() string {
			return fmt.Sprintf("Bearer \t%v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix()}))
		},
409
	}
410 411
	for i, tokenFn := range expFail {
		token := tokenFn()
412 413 414
		if err := wsRequest(t, wsUrl, "Authorization", token); err == nil {
			t.Errorf("tc %d-ws, token '%v': expected not to allow,  got ok", i, token)
		}
415

416
		token = tokenFn()
417 418
		resp := rpcRequest(t, htUrl, "Authorization", token)
		if resp.StatusCode != http.StatusUnauthorized {
419 420 421 422 423
			t.Errorf("tc %d-http, token '%v': expected not to allow,  got %v", i, token, resp.StatusCode)
		}
	}
	srv.stop()
}