stats_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /*
  2. * Copyright (c) 2014, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package psiphon
  20. import (
  21. "encoding/json"
  22. "errors"
  23. "fmt"
  24. "net"
  25. "net/http"
  26. "testing"
  27. "time"
  28. mapset "github.com/deckarep/golang-set"
  29. "github.com/stretchr/testify/suite"
  30. )
  31. const (
  32. _SERVER_ID = "myserverid"
  33. )
  34. type StatsTestSuite struct {
  35. suite.Suite
  36. httpClient *http.Client
  37. }
  38. func TestStatsTestSuite(t *testing.T) {
  39. suite.Run(t, new(StatsTestSuite))
  40. }
  41. func (suite *StatsTestSuite) SetupTest() {
  42. re := make(Regexps, 0)
  43. suite.httpClient = &http.Client{
  44. Transport: &http.Transport{
  45. Dial: makeStatsDialer(_SERVER_ID, &re),
  46. },
  47. }
  48. }
  49. func (suite *StatsTestSuite) TearDownTest() {
  50. suite.httpClient = nil
  51. }
  52. func makeStatsDialer(serverID string, regexps *Regexps) func(network, addr string) (conn net.Conn, err error) {
  53. return func(network, addr string) (conn net.Conn, err error) {
  54. var subConn net.Conn
  55. switch network {
  56. case "tcp", "tcp4", "tcp6":
  57. tcpAddr, err := net.ResolveTCPAddr(network, addr)
  58. if err != nil {
  59. return nil, err
  60. }
  61. subConn, err = net.DialTCP(network, nil, tcpAddr)
  62. if err != nil {
  63. return nil, err
  64. }
  65. default:
  66. err = errors.New("using an unsupported testing network type")
  67. return
  68. }
  69. conn = NewStatsConn(subConn, serverID, regexps)
  70. err = nil
  71. return
  72. }
  73. }
  74. // TODO: move out of stats test suite
  75. func (suite *StatsTestSuite) Test_NextStatusRequestPeriod() {
  76. res1 := NextStatusRequestPeriod()
  77. suite.True(res1 > time.Duration(0), "duration should not be zero")
  78. res2 := NextStatusRequestPeriod()
  79. suite.NotEqual(res1, res2, "duration should have randomness difference between calls")
  80. }
  81. func (suite *StatsTestSuite) Test_StatsConn() {
  82. resp, err := suite.httpClient.Get("http://example.com/index.html")
  83. suite.Nil(err, "basic HTTP requests should succeed")
  84. resp.Body.Close()
  85. resp, err = suite.httpClient.Get("https://example.org/index.html")
  86. suite.Nil(err, "basic HTTPS requests should succeed")
  87. resp.Body.Close()
  88. }
  89. func (suite *StatsTestSuite) Test_GetForServer() {
  90. payload := GetForServer(_SERVER_ID)
  91. suite.Nil(payload, "should get nil stats before any traffic (but not crash)")
  92. resp, err := suite.httpClient.Get("http://example.com/index.html")
  93. suite.Nil(err, "need successful http to proceed with tests")
  94. resp.Body.Close()
  95. // Make sure there aren't stats returned for a bad server ID
  96. payload = GetForServer("INVALID")
  97. suite.Nil(payload, "should get nil stats for invalid server ID")
  98. payload = GetForServer(_SERVER_ID)
  99. suite.NotNil(payload, "should receive valid payload for valid server ID")
  100. payloadJSON, err := json.Marshal(payload)
  101. var parsedJSON interface{}
  102. err = json.Unmarshal(payloadJSON, &parsedJSON)
  103. suite.Nil(err, "payload JSON should parse successfully")
  104. // After we retrieve the stats for a server, they should be cleared out of the tracked stats
  105. payload = GetForServer(_SERVER_ID)
  106. suite.Nil(payload, "after retrieving stats for a server, there should be no more stats (until more data goes through)")
  107. }
  108. func (suite *StatsTestSuite) Test_PutBack() {
  109. resp, err := suite.httpClient.Get("http://example.com/index.html")
  110. suite.Nil(err, "need successful http to proceed with tests")
  111. resp.Body.Close()
  112. payloadToPutBack := GetForServer(_SERVER_ID)
  113. suite.NotNil(payloadToPutBack, "should receive valid payload for valid server ID")
  114. payload := GetForServer(_SERVER_ID)
  115. suite.Nil(payload, "should not be any remaining stats after getting them")
  116. PutBack(_SERVER_ID, payloadToPutBack)
  117. // PutBack is asynchronous, so we'll need to wait a moment for it to do its thing
  118. <-time.After(100 * time.Millisecond)
  119. payload = GetForServer(_SERVER_ID)
  120. suite.NotNil(payload, "stats should be re-added after putting back")
  121. suite.Equal(payload, payloadToPutBack, "stats should be the same as after the first retrieval")
  122. }
  123. func (suite *StatsTestSuite) Test_MakeRegexps() {
  124. pageViewRegexes := []map[string]string{make(map[string]string)}
  125. pageViewRegexes[0]["regex"] = `(^http://[a-z0-9\.]*\.example\.[a-z\.]*)/.*`
  126. pageViewRegexes[0]["replace"] = "$1"
  127. httpsRequestRegexes := []map[string]string{make(map[string]string), make(map[string]string)}
  128. httpsRequestRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com)$`
  129. httpsRequestRegexes[0]["replace"] = "$1"
  130. httpsRequestRegexes[1]["regex"] = `^.*example\.org$`
  131. httpsRequestRegexes[1]["replace"] = "replacement"
  132. regexps := MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  133. suite.NotNil(regexps, "should return a valid object")
  134. suite.Len(*regexps, 2, "should only have processed httpsRequestRegexes")
  135. //
  136. // Test some bad regexps
  137. //
  138. httpsRequestRegexes[0]["regex"] = ""
  139. httpsRequestRegexes[0]["replace"] = "$1"
  140. regexps = MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  141. suite.NotNil(regexps, "should return a valid object")
  142. suite.Len(*regexps, 1, "should have discarded one regexp")
  143. httpsRequestRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com)$`
  144. httpsRequestRegexes[0]["replace"] = ""
  145. regexps = MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  146. suite.NotNil(regexps, "should return a valid object")
  147. suite.Len(*regexps, 1, "should have discarded one regexp")
  148. httpsRequestRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com$` // missing closing paren
  149. httpsRequestRegexes[0]["replace"] = "$1"
  150. regexps = MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  151. suite.NotNil(regexps, "should return a valid object")
  152. suite.Len(*regexps, 1, "should have discarded one regexp")
  153. }
  154. func (suite *StatsTestSuite) Test_Regex() {
  155. // We'll make a new client with actual regexps.
  156. pageViewRegexes := make([]map[string]string, 0)
  157. httpsRequestRegexes := []map[string]string{make(map[string]string), make(map[string]string)}
  158. httpsRequestRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com)$`
  159. httpsRequestRegexes[0]["replace"] = "$1"
  160. httpsRequestRegexes[1]["regex"] = `^.*example\.org$`
  161. httpsRequestRegexes[1]["replace"] = "replacement"
  162. regexps := MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  163. suite.httpClient = &http.Client{
  164. Transport: &http.Transport{
  165. Dial: makeStatsDialer(_SERVER_ID, regexps),
  166. },
  167. }
  168. // Using both HTTP and HTTPS will help us to exercise both methods of hostname parsing
  169. for _, scheme := range []string{"http", "https"} {
  170. // No subdomain, so won't match regex
  171. url := fmt.Sprintf("%s://example.com/index.html", scheme)
  172. resp, err := suite.httpClient.Get(url)
  173. suite.Nil(err)
  174. resp.Body.Close()
  175. // Will match the first regex
  176. url = fmt.Sprintf("%s://www.example.com/index.html", scheme)
  177. resp, err = suite.httpClient.Get(url)
  178. suite.Nil(err)
  179. resp.Body.Close()
  180. // Will match the second regex
  181. url = fmt.Sprintf("%s://example.org/index.html", scheme)
  182. resp, err = suite.httpClient.Get(url)
  183. suite.Nil(err)
  184. resp.Body.Close()
  185. payload := GetForServer(_SERVER_ID)
  186. suite.NotNil(payload, "should get stats because we made HTTP reqs; %s", scheme)
  187. expectedHostnames := mapset.NewSet()
  188. expectedHostnames.Add("(OTHER)")
  189. expectedHostnames.Add("example.com")
  190. expectedHostnames.Add("replacement")
  191. hostnames := make([]interface{}, 0)
  192. for hostname := range payload.hostnameToStats {
  193. hostnames = append(hostnames, hostname)
  194. }
  195. actualHostnames := mapset.NewSetFromSlice(hostnames)
  196. suite.Equal(expectedHostnames, actualHostnames, "post-regex hostnames should be processed as expecteds; %s", scheme)
  197. }
  198. }
  199. func (suite *StatsTestSuite) Test_getTLSHostname() {
  200. // TODO: Create a more robust/antagonistic set of negative tests.
  201. // We can write raw TCP to simulate any arbitrary degree of "almost looks
  202. // like a TLS handshake".
  203. // These tests are basically just checking for crashes.
  204. //
  205. // An easier way to construct valid client-hello messages (but not malicious ones)
  206. // would be to use the clientHelloMsg struct and marshal function from:
  207. // https://github.com/golang/go/blob/master/src/crypto/tls/handshake_messages.go
  208. // TODO: Talk to a local TCP server instead of spamming example.com
  209. dialer := makeStatsDialer(_SERVER_ID, nil)
  210. // Data too short
  211. conn, err := dialer("tcp", "example.com:80")
  212. suite.Nil(err)
  213. b := []byte(`my bytes`)
  214. n, err := conn.Write(b)
  215. suite.Nil(err)
  216. suite.Equal(len(b), n)
  217. err = conn.Close()
  218. suite.Nil(err)
  219. // Data long enough, but wrong first byte
  220. conn, err = dialer("tcp", "example.com:80")
  221. suite.Nil(err)
  222. b = []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  223. n, err = conn.Write(b)
  224. suite.Nil(err)
  225. suite.Equal(len(b), n)
  226. err = conn.Close()
  227. suite.Nil(err)
  228. // Data long enough, correct first byte
  229. conn, err = dialer("tcp", "example.com:80")
  230. suite.Nil(err)
  231. b = []byte{22, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  232. n, err = conn.Write(b)
  233. suite.Nil(err)
  234. suite.Equal(len(b), n)
  235. err = conn.Close()
  236. suite.Nil(err)
  237. // Correct until after SSL version
  238. conn, err = dialer("tcp", "example.com:80")
  239. suite.Nil(err)
  240. b = []byte{22, 3, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  241. n, err = conn.Write(b)
  242. suite.Nil(err)
  243. suite.Equal(len(b), n)
  244. err = conn.Close()
  245. suite.Nil(err)
  246. plaintextLen := byte(70)
  247. // Correct until after plaintext length
  248. conn, err = dialer("tcp", "example.com:80")
  249. suite.Nil(err)
  250. b = []byte{22, 3, 1, 0, plaintextLen, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  251. n, err = conn.Write(b)
  252. suite.Nil(err)
  253. suite.Equal(len(b), n)
  254. err = conn.Close()
  255. suite.Nil(err)
  256. // Correct until after handshake type
  257. conn, err = dialer("tcp", "example.com:80")
  258. suite.Nil(err)
  259. b = []byte{22, 3, 1, 0, plaintextLen, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  260. n, err = conn.Write(b)
  261. suite.Nil(err)
  262. suite.Equal(len(b), n)
  263. err = conn.Close()
  264. suite.Nil(err)
  265. // Correct until after handshake length
  266. conn, err = dialer("tcp", "example.com:80")
  267. suite.Nil(err)
  268. b = []byte{22, 3, 1, 0, plaintextLen, 1, 0, 0, plaintextLen - 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  269. n, err = conn.Write(b)
  270. suite.Nil(err)
  271. suite.Equal(len(b), n)
  272. err = conn.Close()
  273. suite.Nil(err)
  274. // Correct until after protocol version
  275. conn, err = dialer("tcp", "example.com:80")
  276. suite.Nil(err)
  277. b = []byte{22, 3, 1, 0, plaintextLen, 1, 0, 0, plaintextLen - 4, 3, 3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  278. n, err = conn.Write(b)
  279. suite.Nil(err)
  280. suite.Equal(len(b), n)
  281. err = conn.Close()
  282. suite.Nil(err)
  283. }