stats_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. func (suite *StatsTestSuite) Test_NextSendPeriod() {
  75. res1 := NextSendPeriod()
  76. suite.True(res1 > time.Duration(0), "duration should not be zero")
  77. res2 := NextSendPeriod()
  78. suite.NotEqual(res1, res2, "duration should have randomness difference between calls")
  79. }
  80. func (suite *StatsTestSuite) Test_StatsConn() {
  81. resp, err := suite.httpClient.Get("http://example.com/index.html")
  82. suite.Nil(err, "basic HTTP requests should succeed")
  83. resp.Body.Close()
  84. resp, err = suite.httpClient.Get("https://example.org/index.html")
  85. suite.Nil(err, "basic HTTPS requests should succeed")
  86. resp.Body.Close()
  87. }
  88. func (suite *StatsTestSuite) Test_GetForServer() {
  89. payload := GetForServer(_SERVER_ID)
  90. suite.Nil(payload, "should get nil stats before any traffic (but not crash)")
  91. resp, err := suite.httpClient.Get("http://example.com/index.html")
  92. suite.Nil(err, "need successful http to proceed with tests")
  93. resp.Body.Close()
  94. // Make sure there aren't stats returned for a bad server ID
  95. payload = GetForServer("INVALID")
  96. suite.Nil(payload, "should get nil stats for invalid server ID")
  97. payload = GetForServer(_SERVER_ID)
  98. suite.NotNil(payload, "should receive valid payload for valid server ID")
  99. payloadJSON, err := json.Marshal(payload)
  100. var parsedJSON interface{}
  101. err = json.Unmarshal(payloadJSON, &parsedJSON)
  102. suite.Nil(err, "payload JSON should parse successfully")
  103. // After we retrieve the stats for a server, they should be cleared out of the tracked stats
  104. payload = GetForServer(_SERVER_ID)
  105. suite.Nil(payload, "after retrieving stats for a server, there should be no more stats (until more data goes through)")
  106. }
  107. func (suite *StatsTestSuite) Test_PutBack() {
  108. resp, err := suite.httpClient.Get("http://example.com/index.html")
  109. suite.Nil(err, "need successful http to proceed with tests")
  110. resp.Body.Close()
  111. payloadToPutBack := GetForServer(_SERVER_ID)
  112. suite.NotNil(payloadToPutBack, "should receive valid payload for valid server ID")
  113. payload := GetForServer(_SERVER_ID)
  114. suite.Nil(payload, "should not be any remaining stats after getting them")
  115. PutBack(_SERVER_ID, payloadToPutBack)
  116. // PutBack is asynchronous, so we'll need to wait a moment for it to do its thing
  117. <-time.After(100 * time.Millisecond)
  118. payload = GetForServer(_SERVER_ID)
  119. suite.NotNil(payload, "stats should be re-added after putting back")
  120. suite.Equal(payload, payloadToPutBack, "stats should be the same as after the first retrieval")
  121. }
  122. func (suite *StatsTestSuite) Test_MakeRegexps() {
  123. pageViewRegexes := []map[string]string{make(map[string]string)}
  124. pageViewRegexes[0]["regex"] = `(^http://[a-z0-9\.]*\.example\.[a-z\.]*)/.*`
  125. pageViewRegexes[0]["replace"] = "$1"
  126. httpsRequestRegexes := []map[string]string{make(map[string]string), make(map[string]string)}
  127. httpsRequestRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com)$`
  128. httpsRequestRegexes[0]["replace"] = "$1"
  129. httpsRequestRegexes[1]["regex"] = `^.*example\.org$`
  130. httpsRequestRegexes[1]["replace"] = "replacement"
  131. regexps := MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  132. suite.NotNil(regexps, "should return a valid object")
  133. suite.Len(*regexps, 2, "should only have processed httpsRequestRegexes")
  134. //
  135. // Test some bad regexps
  136. //
  137. httpsRequestRegexes[0]["regex"] = ""
  138. httpsRequestRegexes[0]["replace"] = "$1"
  139. regexps = MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  140. suite.NotNil(regexps, "should return a valid object")
  141. suite.Len(*regexps, 1, "should have discarded one regexp")
  142. httpsRequestRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com)$`
  143. httpsRequestRegexes[0]["replace"] = ""
  144. regexps = MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  145. suite.NotNil(regexps, "should return a valid object")
  146. suite.Len(*regexps, 1, "should have discarded one regexp")
  147. httpsRequestRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com$` // missing closing paren
  148. httpsRequestRegexes[0]["replace"] = "$1"
  149. regexps = MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  150. suite.NotNil(regexps, "should return a valid object")
  151. suite.Len(*regexps, 1, "should have discarded one regexp")
  152. }
  153. func (suite *StatsTestSuite) Test_Regex() {
  154. // We'll make a new client with actual regexps.
  155. pageViewRegexes := make([]map[string]string, 0)
  156. httpsRequestRegexes := []map[string]string{make(map[string]string), make(map[string]string)}
  157. httpsRequestRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com)$`
  158. httpsRequestRegexes[0]["replace"] = "$1"
  159. httpsRequestRegexes[1]["regex"] = `^.*example\.org$`
  160. httpsRequestRegexes[1]["replace"] = "replacement"
  161. regexps := MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  162. suite.httpClient = &http.Client{
  163. Transport: &http.Transport{
  164. Dial: makeStatsDialer(_SERVER_ID, regexps),
  165. },
  166. }
  167. // Using both HTTP and HTTPS will help us to exercise both methods of hostname parsing
  168. for _, scheme := range []string{"http", "https"} {
  169. // No subdomain, so won't match regex
  170. url := fmt.Sprintf("%s://example.com/index.html", scheme)
  171. resp, err := suite.httpClient.Get(url)
  172. suite.Nil(err)
  173. resp.Body.Close()
  174. // Will match the first regex
  175. url = fmt.Sprintf("%s://www.example.com/index.html", scheme)
  176. resp, err = suite.httpClient.Get(url)
  177. suite.Nil(err)
  178. resp.Body.Close()
  179. // Will match the second regex
  180. url = fmt.Sprintf("%s://example.org/index.html", scheme)
  181. resp, err = suite.httpClient.Get(url)
  182. suite.Nil(err)
  183. resp.Body.Close()
  184. payload := GetForServer(_SERVER_ID)
  185. suite.NotNil(payload, "should get stats because we made HTTP reqs; %s", scheme)
  186. expectedHostnames := mapset.NewSet()
  187. expectedHostnames.Add("(OTHER)")
  188. expectedHostnames.Add("example.com")
  189. expectedHostnames.Add("replacement")
  190. hostnames := make([]interface{}, 0)
  191. for hostname := range payload.hostnameToStats {
  192. hostnames = append(hostnames, hostname)
  193. }
  194. actualHostnames := mapset.NewSetFromSlice(hostnames)
  195. suite.Equal(expectedHostnames, actualHostnames, "post-regex hostnames should be processed as expecteds; %s", scheme)
  196. }
  197. }
  198. func (suite *StatsTestSuite) Test_getTLSHostname() {
  199. // TODO: Create a more robust/antagonistic set of negative tests.
  200. // We can write raw TCP to simulate any arbitrary degree of "almost looks
  201. // like a TLS handshake".
  202. // These tests are basically just checking for crashes.
  203. //
  204. // An easier way to construct valid client-hello messages (but not malicious ones)
  205. // would be to use the clientHelloMsg struct and marshal function from:
  206. // https://github.com/golang/go/blob/master/src/crypto/tls/handshake_messages.go
  207. // TODO: Talk to a local TCP server instead of spamming example.com
  208. dialer := makeStatsDialer(_SERVER_ID, nil)
  209. // Data too short
  210. conn, err := dialer("tcp", "example.com:80")
  211. suite.Nil(err)
  212. b := []byte(`my bytes`)
  213. n, err := conn.Write(b)
  214. suite.Nil(err)
  215. suite.Equal(len(b), n)
  216. err = conn.Close()
  217. suite.Nil(err)
  218. // Data long enough, but wrong first byte
  219. conn, err = dialer("tcp", "example.com:80")
  220. suite.Nil(err)
  221. 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}
  222. n, err = conn.Write(b)
  223. suite.Nil(err)
  224. suite.Equal(len(b), n)
  225. err = conn.Close()
  226. suite.Nil(err)
  227. // Data long enough, correct first byte
  228. conn, err = dialer("tcp", "example.com:80")
  229. suite.Nil(err)
  230. 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}
  231. n, err = conn.Write(b)
  232. suite.Nil(err)
  233. suite.Equal(len(b), n)
  234. err = conn.Close()
  235. suite.Nil(err)
  236. // Correct until after SSL version
  237. conn, err = dialer("tcp", "example.com:80")
  238. suite.Nil(err)
  239. 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}
  240. n, err = conn.Write(b)
  241. suite.Nil(err)
  242. suite.Equal(len(b), n)
  243. err = conn.Close()
  244. suite.Nil(err)
  245. plaintextLen := byte(70)
  246. // Correct until after plaintext length
  247. conn, err = dialer("tcp", "example.com:80")
  248. suite.Nil(err)
  249. 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}
  250. n, err = conn.Write(b)
  251. suite.Nil(err)
  252. suite.Equal(len(b), n)
  253. err = conn.Close()
  254. suite.Nil(err)
  255. // Correct until after handshake type
  256. conn, err = dialer("tcp", "example.com:80")
  257. suite.Nil(err)
  258. 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}
  259. n, err = conn.Write(b)
  260. suite.Nil(err)
  261. suite.Equal(len(b), n)
  262. err = conn.Close()
  263. suite.Nil(err)
  264. // Correct until after handshake length
  265. conn, err = dialer("tcp", "example.com:80")
  266. suite.Nil(err)
  267. 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}
  268. n, err = conn.Write(b)
  269. suite.Nil(err)
  270. suite.Equal(len(b), n)
  271. err = conn.Close()
  272. suite.Nil(err)
  273. // Correct until after protocol version
  274. conn, err = dialer("tcp", "example.com:80")
  275. suite.Nil(err)
  276. 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}
  277. n, err = conn.Write(b)
  278. suite.Nil(err)
  279. suite.Equal(len(b), n)
  280. err = conn.Close()
  281. suite.Nil(err)
  282. }