rpcstack_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. // Copyright 2020 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 node
  17. import (
  18. "bytes"
  19. "fmt"
  20. "net/http"
  21. "net/url"
  22. "strconv"
  23. "strings"
  24. "testing"
  25. "time"
  26. "github.com/ethereum/go-ethereum/internal/testlog"
  27. "github.com/ethereum/go-ethereum/log"
  28. "github.com/ethereum/go-ethereum/rpc"
  29. "github.com/golang-jwt/jwt/v4"
  30. "github.com/gorilla/websocket"
  31. "github.com/stretchr/testify/assert"
  32. )
  33. // TestCorsHandler makes sure CORS are properly handled on the http server.
  34. func TestCorsHandler(t *testing.T) {
  35. srv := createAndStartServer(t, &httpConfig{CorsAllowedOrigins: []string{"test", "test.com"}}, false, &wsConfig{})
  36. defer srv.stop()
  37. url := "http://" + srv.listenAddr()
  38. resp := rpcRequest(t, url, "origin", "test.com")
  39. assert.Equal(t, "test.com", resp.Header.Get("Access-Control-Allow-Origin"))
  40. resp2 := rpcRequest(t, url, "origin", "bad")
  41. assert.Equal(t, "", resp2.Header.Get("Access-Control-Allow-Origin"))
  42. }
  43. // TestVhosts makes sure vhosts are properly handled on the http server.
  44. func TestVhosts(t *testing.T) {
  45. srv := createAndStartServer(t, &httpConfig{Vhosts: []string{"test"}}, false, &wsConfig{})
  46. defer srv.stop()
  47. url := "http://" + srv.listenAddr()
  48. resp := rpcRequest(t, url, "host", "test")
  49. assert.Equal(t, resp.StatusCode, http.StatusOK)
  50. resp2 := rpcRequest(t, url, "host", "bad")
  51. assert.Equal(t, resp2.StatusCode, http.StatusForbidden)
  52. }
  53. type originTest struct {
  54. spec string
  55. expOk []string
  56. expFail []string
  57. }
  58. // splitAndTrim splits input separated by a comma
  59. // and trims excessive white space from the substrings.
  60. // Copied over from flags.go
  61. func splitAndTrim(input string) (ret []string) {
  62. l := strings.Split(input, ",")
  63. for _, r := range l {
  64. r = strings.TrimSpace(r)
  65. if len(r) > 0 {
  66. ret = append(ret, r)
  67. }
  68. }
  69. return ret
  70. }
  71. // TestWebsocketOrigins makes sure the websocket origins are properly handled on the websocket server.
  72. func TestWebsocketOrigins(t *testing.T) {
  73. tests := []originTest{
  74. {
  75. spec: "*", // allow all
  76. expOk: []string{"", "http://test", "https://test", "http://test:8540", "https://test:8540",
  77. "http://test.com", "https://foo.test", "http://testa", "http://atestb:8540", "https://atestb:8540"},
  78. },
  79. {
  80. spec: "test",
  81. expOk: []string{"http://test", "https://test", "http://test:8540", "https://test:8540"},
  82. expFail: []string{"http://test.com", "https://foo.test", "http://testa", "http://atestb:8540", "https://atestb:8540"},
  83. },
  84. // scheme tests
  85. {
  86. spec: "https://test",
  87. expOk: []string{"https://test", "https://test:9999"},
  88. expFail: []string{
  89. "test", // no scheme, required by spec
  90. "http://test", // wrong scheme
  91. "http://test.foo", "https://a.test.x", // subdomain variations
  92. "http://testx:8540", "https://xtest:8540"},
  93. },
  94. // ip tests
  95. {
  96. spec: "https://12.34.56.78",
  97. expOk: []string{"https://12.34.56.78", "https://12.34.56.78:8540"},
  98. expFail: []string{
  99. "http://12.34.56.78", // wrong scheme
  100. "http://12.34.56.78:443", // wrong scheme
  101. "http://1.12.34.56.78", // wrong 'domain name'
  102. "http://12.34.56.78.a", // wrong 'domain name'
  103. "https://87.65.43.21", "http://87.65.43.21:8540", "https://87.65.43.21:8540"},
  104. },
  105. // port tests
  106. {
  107. spec: "test:8540",
  108. expOk: []string{"http://test:8540", "https://test:8540"},
  109. expFail: []string{
  110. "http://test", "https://test", // spec says port required
  111. "http://test:8541", "https://test:8541", // wrong port
  112. "http://bad", "https://bad", "http://bad:8540", "https://bad:8540"},
  113. },
  114. // scheme and port
  115. {
  116. spec: "https://test:8540",
  117. expOk: []string{"https://test:8540"},
  118. expFail: []string{
  119. "https://test", // missing port
  120. "http://test", // missing port, + wrong scheme
  121. "http://test:8540", // wrong scheme
  122. "http://test:8541", "https://test:8541", // wrong port
  123. "http://bad", "https://bad", "http://bad:8540", "https://bad:8540"},
  124. },
  125. // several allowed origins
  126. {
  127. spec: "localhost,http://127.0.0.1",
  128. expOk: []string{"localhost", "http://localhost", "https://localhost:8443",
  129. "http://127.0.0.1", "http://127.0.0.1:8080"},
  130. expFail: []string{
  131. "https://127.0.0.1", // wrong scheme
  132. "http://bad", "https://bad", "http://bad:8540", "https://bad:8540"},
  133. },
  134. }
  135. for _, tc := range tests {
  136. srv := createAndStartServer(t, &httpConfig{}, true, &wsConfig{Origins: splitAndTrim(tc.spec)})
  137. url := fmt.Sprintf("ws://%v", srv.listenAddr())
  138. for _, origin := range tc.expOk {
  139. if err := wsRequest(t, url, "Origin", origin); err != nil {
  140. t.Errorf("spec '%v', origin '%v': expected ok, got %v", tc.spec, origin, err)
  141. }
  142. }
  143. for _, origin := range tc.expFail {
  144. if err := wsRequest(t, url, "Origin", origin); err == nil {
  145. t.Errorf("spec '%v', origin '%v': expected not to allow, got ok", tc.spec, origin)
  146. }
  147. }
  148. srv.stop()
  149. }
  150. }
  151. // TestIsWebsocket tests if an incoming websocket upgrade request is handled properly.
  152. func TestIsWebsocket(t *testing.T) {
  153. r, _ := http.NewRequest("GET", "/", nil)
  154. assert.False(t, isWebsocket(r))
  155. r.Header.Set("upgrade", "websocket")
  156. assert.False(t, isWebsocket(r))
  157. r.Header.Set("connection", "upgrade")
  158. assert.True(t, isWebsocket(r))
  159. r.Header.Set("connection", "upgrade,keep-alive")
  160. assert.True(t, isWebsocket(r))
  161. r.Header.Set("connection", " UPGRADE,keep-alive")
  162. assert.True(t, isWebsocket(r))
  163. }
  164. func Test_checkPath(t *testing.T) {
  165. tests := []struct {
  166. req *http.Request
  167. prefix string
  168. expected bool
  169. }{
  170. {
  171. req: &http.Request{URL: &url.URL{Path: "/test"}},
  172. prefix: "/test",
  173. expected: true,
  174. },
  175. {
  176. req: &http.Request{URL: &url.URL{Path: "/testing"}},
  177. prefix: "/test",
  178. expected: true,
  179. },
  180. {
  181. req: &http.Request{URL: &url.URL{Path: "/"}},
  182. prefix: "/test",
  183. expected: false,
  184. },
  185. {
  186. req: &http.Request{URL: &url.URL{Path: "/fail"}},
  187. prefix: "/test",
  188. expected: false,
  189. },
  190. {
  191. req: &http.Request{URL: &url.URL{Path: "/"}},
  192. prefix: "",
  193. expected: true,
  194. },
  195. {
  196. req: &http.Request{URL: &url.URL{Path: "/fail"}},
  197. prefix: "",
  198. expected: false,
  199. },
  200. {
  201. req: &http.Request{URL: &url.URL{Path: "/"}},
  202. prefix: "/",
  203. expected: true,
  204. },
  205. {
  206. req: &http.Request{URL: &url.URL{Path: "/testing"}},
  207. prefix: "/",
  208. expected: true,
  209. },
  210. }
  211. for i, tt := range tests {
  212. t.Run(strconv.Itoa(i), func(t *testing.T) {
  213. assert.Equal(t, tt.expected, checkPath(tt.req, tt.prefix))
  214. })
  215. }
  216. }
  217. func createAndStartServer(t *testing.T, conf *httpConfig, ws bool, wsConf *wsConfig) *httpServer {
  218. t.Helper()
  219. srv := newHTTPServer(testlog.Logger(t, log.LvlDebug), rpc.DefaultHTTPTimeouts)
  220. assert.NoError(t, srv.enableRPC(nil, *conf))
  221. if ws {
  222. assert.NoError(t, srv.enableWS(nil, *wsConf))
  223. }
  224. assert.NoError(t, srv.setListenAddr("localhost", 0))
  225. assert.NoError(t, srv.start())
  226. return srv
  227. }
  228. // wsRequest attempts to open a WebSocket connection to the given URL.
  229. func wsRequest(t *testing.T, url string, extraHeaders ...string) error {
  230. t.Helper()
  231. //t.Logf("checking WebSocket on %s (origin %q)", url, browserOrigin)
  232. headers := make(http.Header)
  233. // Apply extra headers.
  234. if len(extraHeaders)%2 != 0 {
  235. panic("odd extraHeaders length")
  236. }
  237. for i := 0; i < len(extraHeaders); i += 2 {
  238. key, value := extraHeaders[i], extraHeaders[i+1]
  239. headers.Set(key, value)
  240. }
  241. conn, _, err := websocket.DefaultDialer.Dial(url, headers)
  242. if conn != nil {
  243. conn.Close()
  244. }
  245. return err
  246. }
  247. // rpcRequest performs a JSON-RPC request to the given URL.
  248. func rpcRequest(t *testing.T, url string, extraHeaders ...string) *http.Response {
  249. t.Helper()
  250. // Create the request.
  251. body := bytes.NewReader([]byte(`{"jsonrpc":"2.0","id":1,"method":"rpc_modules","params":[]}`))
  252. req, err := http.NewRequest("POST", url, body)
  253. if err != nil {
  254. t.Fatal("could not create http request:", err)
  255. }
  256. req.Header.Set("content-type", "application/json")
  257. // Apply extra headers.
  258. if len(extraHeaders)%2 != 0 {
  259. panic("odd extraHeaders length")
  260. }
  261. for i := 0; i < len(extraHeaders); i += 2 {
  262. key, value := extraHeaders[i], extraHeaders[i+1]
  263. if strings.EqualFold(key, "host") {
  264. req.Host = value
  265. } else {
  266. req.Header.Set(key, value)
  267. }
  268. }
  269. // Perform the request.
  270. t.Logf("checking RPC/HTTP on %s %v", url, extraHeaders)
  271. resp, err := http.DefaultClient.Do(req)
  272. if err != nil {
  273. t.Fatal(err)
  274. }
  275. return resp
  276. }
  277. type testClaim map[string]interface{}
  278. func (testClaim) Valid() error {
  279. return nil
  280. }
  281. func TestJWT(t *testing.T) {
  282. var secret = []byte("secret")
  283. issueToken := func(secret []byte, method jwt.SigningMethod, input map[string]interface{}) string {
  284. if method == nil {
  285. method = jwt.SigningMethodHS256
  286. }
  287. ss, _ := jwt.NewWithClaims(method, testClaim(input)).SignedString(secret)
  288. return ss
  289. }
  290. srv := createAndStartServer(t, &httpConfig{jwtSecret: []byte("secret")},
  291. true, &wsConfig{Origins: []string{"*"}, jwtSecret: []byte("secret")})
  292. wsUrl := fmt.Sprintf("ws://%v", srv.listenAddr())
  293. htUrl := fmt.Sprintf("http://%v", srv.listenAddr())
  294. expOk := []func() string{
  295. func() string {
  296. return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix()}))
  297. },
  298. func() string {
  299. return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix() + 4}))
  300. },
  301. func() string {
  302. return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix() - 4}))
  303. },
  304. func() string {
  305. return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{
  306. "iat": time.Now().Unix(),
  307. "exp": time.Now().Unix() + 2,
  308. }))
  309. },
  310. func() string {
  311. return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{
  312. "iat": time.Now().Unix(),
  313. "bar": "baz",
  314. }))
  315. },
  316. }
  317. for i, tokenFn := range expOk {
  318. token := tokenFn()
  319. if err := wsRequest(t, wsUrl, "Authorization", token); err != nil {
  320. t.Errorf("test %d-ws, token '%v': expected ok, got %v", i, token, err)
  321. }
  322. token = tokenFn()
  323. if resp := rpcRequest(t, htUrl, "Authorization", token); resp.StatusCode != 200 {
  324. t.Errorf("test %d-http, token '%v': expected ok, got %v", i, token, resp.StatusCode)
  325. }
  326. }
  327. expFail := []func() string{
  328. // future
  329. func() string {
  330. return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix() + int64(jwtExpiryTimeout.Seconds()) + 1}))
  331. },
  332. // stale
  333. func() string {
  334. return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix() - int64(jwtExpiryTimeout.Seconds()) - 1}))
  335. },
  336. // wrong algo
  337. func() string {
  338. return fmt.Sprintf("Bearer %v", issueToken(secret, jwt.SigningMethodHS512, testClaim{"iat": time.Now().Unix() + 4}))
  339. },
  340. // expired
  341. func() string {
  342. return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix(), "exp": time.Now().Unix()}))
  343. },
  344. // missing mandatory iat
  345. func() string {
  346. return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{}))
  347. },
  348. // wrong secret
  349. func() string {
  350. return fmt.Sprintf("Bearer %v", issueToken([]byte("wrong"), nil, testClaim{"iat": time.Now().Unix()}))
  351. },
  352. func() string {
  353. return fmt.Sprintf("Bearer %v", issueToken([]byte{}, nil, testClaim{"iat": time.Now().Unix()}))
  354. },
  355. func() string {
  356. return fmt.Sprintf("Bearer %v", issueToken(nil, nil, testClaim{"iat": time.Now().Unix()}))
  357. },
  358. // Various malformed syntax
  359. func() string {
  360. return fmt.Sprintf("%v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix()}))
  361. },
  362. func() string {
  363. return fmt.Sprintf("Bearer %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix()}))
  364. },
  365. func() string {
  366. return fmt.Sprintf("bearer %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix()}))
  367. },
  368. func() string {
  369. return fmt.Sprintf("Bearer: %v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix()}))
  370. },
  371. func() string {
  372. return fmt.Sprintf("Bearer:%v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix()}))
  373. },
  374. func() string {
  375. return fmt.Sprintf("Bearer\t%v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix()}))
  376. },
  377. func() string {
  378. return fmt.Sprintf("Bearer \t%v", issueToken(secret, nil, testClaim{"iat": time.Now().Unix()}))
  379. },
  380. }
  381. for i, tokenFn := range expFail {
  382. token := tokenFn()
  383. if err := wsRequest(t, wsUrl, "Authorization", token); err == nil {
  384. t.Errorf("tc %d-ws, token '%v': expected not to allow, got ok", i, token)
  385. }
  386. token = tokenFn()
  387. if resp := rpcRequest(t, htUrl, "Authorization", token); resp.StatusCode != 403 {
  388. t.Errorf("tc %d-http, token '%v': expected not to allow, got %v", i, token, resp.StatusCode)
  389. }
  390. }
  391. srv.stop()
  392. }