rpcstack_test.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. "github.com/ethereum/go-ethereum/internal/testlog"
  26. "github.com/ethereum/go-ethereum/log"
  27. "github.com/ethereum/go-ethereum/rpc"
  28. "github.com/gorilla/websocket"
  29. "github.com/stretchr/testify/assert"
  30. )
  31. // TestCorsHandler makes sure CORS are properly handled on the http server.
  32. func TestCorsHandler(t *testing.T) {
  33. srv := createAndStartServer(t, &httpConfig{CorsAllowedOrigins: []string{"test", "test.com"}}, false, &wsConfig{})
  34. defer srv.stop()
  35. url := "http://" + srv.listenAddr()
  36. resp := rpcRequest(t, url, "origin", "test.com")
  37. assert.Equal(t, "test.com", resp.Header.Get("Access-Control-Allow-Origin"))
  38. resp2 := rpcRequest(t, url, "origin", "bad")
  39. assert.Equal(t, "", resp2.Header.Get("Access-Control-Allow-Origin"))
  40. }
  41. // TestVhosts makes sure vhosts are properly handled on the http server.
  42. func TestVhosts(t *testing.T) {
  43. srv := createAndStartServer(t, &httpConfig{Vhosts: []string{"test"}}, false, &wsConfig{})
  44. defer srv.stop()
  45. url := "http://" + srv.listenAddr()
  46. resp := rpcRequest(t, url, "host", "test")
  47. assert.Equal(t, resp.StatusCode, http.StatusOK)
  48. resp2 := rpcRequest(t, url, "host", "bad")
  49. assert.Equal(t, resp2.StatusCode, http.StatusForbidden)
  50. }
  51. type originTest struct {
  52. spec string
  53. expOk []string
  54. expFail []string
  55. }
  56. // splitAndTrim splits input separated by a comma
  57. // and trims excessive white space from the substrings.
  58. // Copied over from flags.go
  59. func splitAndTrim(input string) (ret []string) {
  60. l := strings.Split(input, ",")
  61. for _, r := range l {
  62. r = strings.TrimSpace(r)
  63. if len(r) > 0 {
  64. ret = append(ret, r)
  65. }
  66. }
  67. return ret
  68. }
  69. // TestWebsocketOrigins makes sure the websocket origins are properly handled on the websocket server.
  70. func TestWebsocketOrigins(t *testing.T) {
  71. tests := []originTest{
  72. {
  73. spec: "*", // allow all
  74. expOk: []string{"", "http://test", "https://test", "http://test:8540", "https://test:8540",
  75. "http://test.com", "https://foo.test", "http://testa", "http://atestb:8540", "https://atestb:8540"},
  76. },
  77. {
  78. spec: "test",
  79. expOk: []string{"http://test", "https://test", "http://test:8540", "https://test:8540"},
  80. expFail: []string{"http://test.com", "https://foo.test", "http://testa", "http://atestb:8540", "https://atestb:8540"},
  81. },
  82. // scheme tests
  83. {
  84. spec: "https://test",
  85. expOk: []string{"https://test", "https://test:9999"},
  86. expFail: []string{
  87. "test", // no scheme, required by spec
  88. "http://test", // wrong scheme
  89. "http://test.foo", "https://a.test.x", // subdomain variatoins
  90. "http://testx:8540", "https://xtest:8540"},
  91. },
  92. // ip tests
  93. {
  94. spec: "https://12.34.56.78",
  95. expOk: []string{"https://12.34.56.78", "https://12.34.56.78:8540"},
  96. expFail: []string{
  97. "http://12.34.56.78", // wrong scheme
  98. "http://12.34.56.78:443", // wrong scheme
  99. "http://1.12.34.56.78", // wrong 'domain name'
  100. "http://12.34.56.78.a", // wrong 'domain name'
  101. "https://87.65.43.21", "http://87.65.43.21:8540", "https://87.65.43.21:8540"},
  102. },
  103. // port tests
  104. {
  105. spec: "test:8540",
  106. expOk: []string{"http://test:8540", "https://test:8540"},
  107. expFail: []string{
  108. "http://test", "https://test", // spec says port required
  109. "http://test:8541", "https://test:8541", // wrong port
  110. "http://bad", "https://bad", "http://bad:8540", "https://bad:8540"},
  111. },
  112. // scheme and port
  113. {
  114. spec: "https://test:8540",
  115. expOk: []string{"https://test:8540"},
  116. expFail: []string{
  117. "https://test", // missing port
  118. "http://test", // missing port, + wrong scheme
  119. "http://test:8540", // wrong scheme
  120. "http://test:8541", "https://test:8541", // wrong port
  121. "http://bad", "https://bad", "http://bad:8540", "https://bad:8540"},
  122. },
  123. // several allowed origins
  124. {
  125. spec: "localhost,http://127.0.0.1",
  126. expOk: []string{"localhost", "http://localhost", "https://localhost:8443",
  127. "http://127.0.0.1", "http://127.0.0.1:8080"},
  128. expFail: []string{
  129. "https://127.0.0.1", // wrong scheme
  130. "http://bad", "https://bad", "http://bad:8540", "https://bad:8540"},
  131. },
  132. }
  133. for _, tc := range tests {
  134. srv := createAndStartServer(t, &httpConfig{}, true, &wsConfig{Origins: splitAndTrim(tc.spec)})
  135. url := fmt.Sprintf("ws://%v", srv.listenAddr())
  136. for _, origin := range tc.expOk {
  137. if err := wsRequest(t, url, origin); err != nil {
  138. t.Errorf("spec '%v', origin '%v': expected ok, got %v", tc.spec, origin, err)
  139. }
  140. }
  141. for _, origin := range tc.expFail {
  142. if err := wsRequest(t, url, origin); err == nil {
  143. t.Errorf("spec '%v', origin '%v': expected not to allow, got ok", tc.spec, origin)
  144. }
  145. }
  146. srv.stop()
  147. }
  148. }
  149. // TestIsWebsocket tests if an incoming websocket upgrade request is handled properly.
  150. func TestIsWebsocket(t *testing.T) {
  151. r, _ := http.NewRequest("GET", "/", nil)
  152. assert.False(t, isWebsocket(r))
  153. r.Header.Set("upgrade", "websocket")
  154. assert.False(t, isWebsocket(r))
  155. r.Header.Set("connection", "upgrade")
  156. assert.True(t, isWebsocket(r))
  157. r.Header.Set("connection", "upgrade,keep-alive")
  158. assert.True(t, isWebsocket(r))
  159. r.Header.Set("connection", " UPGRADE,keep-alive")
  160. assert.True(t, isWebsocket(r))
  161. }
  162. func Test_checkPath(t *testing.T) {
  163. tests := []struct {
  164. req *http.Request
  165. prefix string
  166. expected bool
  167. }{
  168. {
  169. req: &http.Request{URL: &url.URL{Path: "/test"}},
  170. prefix: "/test",
  171. expected: true,
  172. },
  173. {
  174. req: &http.Request{URL: &url.URL{Path: "/testing"}},
  175. prefix: "/test",
  176. expected: true,
  177. },
  178. {
  179. req: &http.Request{URL: &url.URL{Path: "/"}},
  180. prefix: "/test",
  181. expected: false,
  182. },
  183. {
  184. req: &http.Request{URL: &url.URL{Path: "/fail"}},
  185. prefix: "/test",
  186. expected: false,
  187. },
  188. {
  189. req: &http.Request{URL: &url.URL{Path: "/"}},
  190. prefix: "",
  191. expected: true,
  192. },
  193. {
  194. req: &http.Request{URL: &url.URL{Path: "/fail"}},
  195. prefix: "",
  196. expected: false,
  197. },
  198. {
  199. req: &http.Request{URL: &url.URL{Path: "/"}},
  200. prefix: "/",
  201. expected: true,
  202. },
  203. {
  204. req: &http.Request{URL: &url.URL{Path: "/testing"}},
  205. prefix: "/",
  206. expected: true,
  207. },
  208. }
  209. for i, tt := range tests {
  210. t.Run(strconv.Itoa(i), func(t *testing.T) {
  211. assert.Equal(t, tt.expected, checkPath(tt.req, tt.prefix))
  212. })
  213. }
  214. }
  215. func createAndStartServer(t *testing.T, conf *httpConfig, ws bool, wsConf *wsConfig) *httpServer {
  216. t.Helper()
  217. srv := newHTTPServer(testlog.Logger(t, log.LvlDebug), rpc.DefaultHTTPTimeouts)
  218. assert.NoError(t, srv.enableRPC(nil, *conf, nil))
  219. if ws {
  220. assert.NoError(t, srv.enableWS(nil, *wsConf, nil))
  221. }
  222. assert.NoError(t, srv.setListenAddr("localhost", 0))
  223. assert.NoError(t, srv.start(nil))
  224. return srv
  225. }
  226. // wsRequest attempts to open a WebSocket connection to the given URL.
  227. func wsRequest(t *testing.T, url, browserOrigin string) error {
  228. t.Helper()
  229. t.Logf("checking WebSocket on %s (origin %q)", url, browserOrigin)
  230. headers := make(http.Header)
  231. if browserOrigin != "" {
  232. headers.Set("Origin", browserOrigin)
  233. }
  234. conn, _, err := websocket.DefaultDialer.Dial(url, headers)
  235. if conn != nil {
  236. conn.Close()
  237. }
  238. return err
  239. }
  240. // rpcRequest performs a JSON-RPC request to the given URL.
  241. func rpcRequest(t *testing.T, url string, extraHeaders ...string) *http.Response {
  242. t.Helper()
  243. // Create the request.
  244. body := bytes.NewReader([]byte(`{"jsonrpc":"2.0","id":1,"method":"rpc_modules","params":[]}`))
  245. req, err := http.NewRequest("POST", url, body)
  246. if err != nil {
  247. t.Fatal("could not create http request:", err)
  248. }
  249. req.Header.Set("content-type", "application/json")
  250. // Apply extra headers.
  251. if len(extraHeaders)%2 != 0 {
  252. panic("odd extraHeaders length")
  253. }
  254. for i := 0; i < len(extraHeaders); i += 2 {
  255. key, value := extraHeaders[i], extraHeaders[i+1]
  256. if strings.ToLower(key) == "host" {
  257. req.Host = value
  258. } else {
  259. req.Header.Set(key, value)
  260. }
  261. }
  262. // Perform the request.
  263. t.Logf("checking RPC/HTTP on %s %v", url, extraHeaders)
  264. resp, err := http.DefaultClient.Do(req)
  265. if err != nil {
  266. t.Fatal(err)
  267. }
  268. return resp
  269. }