transferstats_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /*
  2. * Copyright (c) 2015, 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 transferstats
  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. var nextServerID = 0
  35. type StatsTestSuite struct {
  36. suite.Suite
  37. serverID string
  38. httpClient *http.Client
  39. }
  40. func TestStatsTestSuite(t *testing.T) {
  41. suite.Run(t, new(StatsTestSuite))
  42. }
  43. func (suite *StatsTestSuite) SetupTest() {
  44. re := make(Regexps, 0)
  45. suite.serverID = fmt.Sprintf("%s-%d", _SERVER_ID, nextServerID)
  46. nextServerID++
  47. suite.httpClient = &http.Client{
  48. Transport: &http.Transport{
  49. Dial: makeStatsDialer(suite.serverID, &re),
  50. },
  51. }
  52. }
  53. func (suite *StatsTestSuite) TearDownTest() {
  54. suite.httpClient = nil
  55. }
  56. func makeStatsDialer(serverID string, regexps *Regexps) func(network, addr string) (conn net.Conn, err error) {
  57. return func(network, addr string) (conn net.Conn, err error) {
  58. var subConn net.Conn
  59. switch network {
  60. case "tcp", "tcp4", "tcp6":
  61. tcpAddr, err := net.ResolveTCPAddr(network, addr)
  62. if err != nil {
  63. return nil, err
  64. }
  65. subConn, err = net.DialTCP(network, nil, tcpAddr)
  66. if err != nil {
  67. return nil, err
  68. }
  69. default:
  70. err = errors.New("using an unsupported testing network type")
  71. return
  72. }
  73. conn = NewConn(subConn, serverID, regexps)
  74. err = nil
  75. return
  76. }
  77. }
  78. func (suite *StatsTestSuite) Test_StatsConn() {
  79. resp, err := suite.httpClient.Get("http://example.com/index.html")
  80. suite.Nil(err, "basic HTTP requests should succeed")
  81. resp.Body.Close()
  82. resp, err = suite.httpClient.Get("https://example.org/index.html")
  83. suite.Nil(err, "basic HTTPS requests should succeed")
  84. resp.Body.Close()
  85. }
  86. func (suite *StatsTestSuite) Test_TakeOutStatsForServer() {
  87. zeroPayload := &AccumulatedStats{hostnameToStats: make(map[string]*hostStats)}
  88. payload := TakeOutStatsForServer(suite.serverID)
  89. suite.Equal(payload, zeroPayload, "should get zero stats before any traffic")
  90. resp, err := suite.httpClient.Get("http://example.com/index.html")
  91. suite.Nil(err, "need successful http to proceed with tests")
  92. resp.Body.Close()
  93. payload = TakeOutStatsForServer(suite.serverID)
  94. suite.NotNil(payload, "should receive valid payload for valid server ID")
  95. payloadJSON, err := json.Marshal(payload)
  96. var parsedJSON interface{}
  97. err = json.Unmarshal(payloadJSON, &parsedJSON)
  98. suite.Nil(err, "payload JSON should parse successfully")
  99. // After we retrieve the stats for a server, they should be cleared out of the tracked stats
  100. payload = TakeOutStatsForServer(suite.serverID)
  101. suite.Equal(payload, zeroPayload, "after retrieving stats for a server, there should be zero stats (until more data goes through)")
  102. }
  103. func (suite *StatsTestSuite) Test_PutBackStatsForServer() {
  104. resp, err := suite.httpClient.Get("http://example.com/index.html")
  105. suite.Nil(err, "need successful http to proceed with tests")
  106. resp.Body.Close()
  107. payloadToPutBack := TakeOutStatsForServer(suite.serverID)
  108. suite.NotNil(payloadToPutBack, "should receive valid payload for valid server ID")
  109. zeroPayload := &AccumulatedStats{hostnameToStats: make(map[string]*hostStats)}
  110. payload := TakeOutStatsForServer(suite.serverID)
  111. suite.Equal(payload, zeroPayload, "should be zero stats after getting them")
  112. PutBackStatsForServer(suite.serverID, payloadToPutBack)
  113. // PutBack is asynchronous, so we'll need to wait a moment for it to do its thing
  114. <-time.After(100 * time.Millisecond)
  115. payload = TakeOutStatsForServer(suite.serverID)
  116. suite.NotEqual(payload, zeroPayload, "stats should be re-added after putting back")
  117. suite.Equal(payload, payloadToPutBack, "stats should be the same as after the first retrieval")
  118. }
  119. func (suite *StatsTestSuite) Test_MakeRegexps() {
  120. pageViewRegexes := []map[string]string{make(map[string]string)}
  121. pageViewRegexes[0]["regex"] = `(^http://[a-z0-9\.]*\.example\.[a-z\.]*)/.*`
  122. pageViewRegexes[0]["replace"] = "$1"
  123. httpsRequestRegexes := []map[string]string{make(map[string]string), make(map[string]string)}
  124. httpsRequestRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com)$`
  125. httpsRequestRegexes[0]["replace"] = "$1"
  126. httpsRequestRegexes[1]["regex"] = `^.*example\.org$`
  127. httpsRequestRegexes[1]["replace"] = "replacement"
  128. regexps, notices := MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  129. suite.NotNil(regexps, "should return a valid object")
  130. suite.Len(*regexps, 2, "should only have processed httpsRequestRegexes")
  131. suite.Len(notices, 0, "should return no notices")
  132. //
  133. // Test some bad regexps
  134. //
  135. httpsRequestRegexes[0]["regex"] = ""
  136. httpsRequestRegexes[0]["replace"] = "$1"
  137. regexps, notices = MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  138. suite.NotNil(regexps, "should return a valid object")
  139. suite.Len(*regexps, 1, "should have discarded one regexp")
  140. suite.Len(notices, 1, "should have returned one notice")
  141. httpsRequestRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com)$`
  142. httpsRequestRegexes[0]["replace"] = ""
  143. regexps, notices = MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  144. suite.NotNil(regexps, "should return a valid object")
  145. suite.Len(*regexps, 1, "should have discarded one regexp")
  146. suite.Len(notices, 1, "should have returned one notice")
  147. httpsRequestRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com$` // missing closing paren
  148. httpsRequestRegexes[0]["replace"] = "$1"
  149. regexps, notices = MakeRegexps(pageViewRegexes, httpsRequestRegexes)
  150. suite.NotNil(regexps, "should return a valid object")
  151. suite.Len(*regexps, 1, "should have discarded one regexp")
  152. suite.Len(notices, 1, "should have returned one notice")
  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(suite.serverID, 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 := TakeOutStatsForServer(suite.serverID)
  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(suite.serverID, 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. }