transferstats_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. "errors"
  22. "fmt"
  23. "net"
  24. "net/http"
  25. "regexp"
  26. "testing"
  27. mapset "github.com/deckarep/golang-set"
  28. "github.com/stretchr/testify/suite"
  29. )
  30. const (
  31. _SERVER_ID = "myserverid"
  32. )
  33. var nextServerID = 0
  34. type StatsTestSuite struct {
  35. suite.Suite
  36. serverID string
  37. httpClient *http.Client
  38. }
  39. func TestStatsTestSuite(t *testing.T) {
  40. suite.Run(t, new(StatsTestSuite))
  41. }
  42. func (suite *StatsTestSuite) SetupTest() {
  43. suite.serverID = fmt.Sprintf("%s-%d", _SERVER_ID, nextServerID)
  44. nextServerID++
  45. suite.httpClient = &http.Client{
  46. Transport: &http.Transport{
  47. Dial: makeStatsDialer(suite.serverID, &Regexps{}),
  48. },
  49. }
  50. }
  51. func (suite *StatsTestSuite) TearDownTest() {
  52. suite.httpClient = nil
  53. }
  54. func makeStatsDialer(serverID string, regexps *Regexps) func(network, addr string) (conn net.Conn, err error) {
  55. return func(network, addr string) (conn net.Conn, err error) {
  56. var subConn net.Conn
  57. switch network {
  58. case "tcp", "tcp4", "tcp6":
  59. tcpAddr, err := net.ResolveTCPAddr(network, addr)
  60. if err != nil {
  61. return nil, err
  62. }
  63. subConn, err = net.DialTCP(network, nil, tcpAddr)
  64. if err != nil {
  65. return nil, err
  66. }
  67. default:
  68. err = errors.New("using an unsupported testing network type")
  69. return
  70. }
  71. conn = NewConn(subConn, serverID, regexps)
  72. err = nil
  73. return
  74. }
  75. }
  76. func (suite *StatsTestSuite) Test_StatsConn() {
  77. resp, err := suite.httpClient.Get("http://example.com/index.html")
  78. suite.Nil(err, "basic HTTP requests should succeed")
  79. resp.Body.Close()
  80. resp, err = suite.httpClient.Get("https://example.org/index.html")
  81. suite.Nil(err, "basic HTTPS requests should succeed")
  82. resp.Body.Close()
  83. }
  84. func (suite *StatsTestSuite) Test_TakeOutStatsForServer() {
  85. zeroPayload := &AccumulatedStats{hostnameToStats: make(map[string]*hostStats)}
  86. payload := TakeOutStatsForServer(suite.serverID)
  87. suite.Equal(payload, zeroPayload, "should get zero stats before any traffic")
  88. resp, err := suite.httpClient.Get("http://example.com/index.html")
  89. suite.Nil(err, "need successful http to proceed with tests")
  90. resp.Body.Close()
  91. payload = TakeOutStatsForServer(suite.serverID)
  92. suite.NotNil(payload, "should receive valid payload for valid server ID")
  93. // After we retrieve the stats for a server, they should be cleared out of the tracked stats
  94. payload = TakeOutStatsForServer(suite.serverID)
  95. suite.Equal(payload, zeroPayload, "after retrieving stats for a server, there should be zero stats (until more data goes through)")
  96. }
  97. func (suite *StatsTestSuite) Test_PutBackStatsForServer() {
  98. // Set a regexp for the httpClient to ensure it at least records "(OTHER)" domain bytes;
  99. // The regex is set to "nomatch.com" so that it _will_ exercise the "(OTHER)" case.
  100. regexp, _ := regexp.Compile(`^[a-z0-9\.]*\.(nomatch\.com)$`)
  101. replace := "$1"
  102. regexps := &Regexps{regexpReplace{regexp: regexp, replace: replace}}
  103. suite.httpClient = &http.Client{
  104. Transport: &http.Transport{
  105. Dial: makeStatsDialer(suite.serverID, regexps),
  106. },
  107. }
  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 := TakeOutStatsForServer(suite.serverID)
  112. suite.NotNil(payloadToPutBack, "should receive valid payload for valid server ID")
  113. zeroPayload := &AccumulatedStats{hostnameToStats: make(map[string]*hostStats)}
  114. payload := TakeOutStatsForServer(suite.serverID)
  115. suite.Equal(payload, zeroPayload, "should be zero stats after getting them")
  116. PutBackStatsForServer(suite.serverID, payloadToPutBack)
  117. payload = TakeOutStatsForServer(suite.serverID)
  118. suite.NotEqual(payload, zeroPayload, "stats should be re-added after putting back")
  119. suite.Equal(payload, payloadToPutBack, "stats should be the same as after the first retrieval")
  120. }
  121. func (suite *StatsTestSuite) Test_NoRegexes() {
  122. // Set no regexps for the httpClient
  123. suite.httpClient = &http.Client{
  124. Transport: &http.Transport{
  125. Dial: makeStatsDialer(suite.serverID, &Regexps{}),
  126. },
  127. }
  128. // Ensure there are no stats before making the no-regex request
  129. _ = TakeOutStatsForServer(suite.serverID)
  130. resp, err := suite.httpClient.Get("http://example.com/index.html")
  131. suite.Nil(err, "need successful http to proceed with tests")
  132. resp.Body.Close()
  133. zeroPayload := &AccumulatedStats{hostnameToStats: make(map[string]*hostStats)}
  134. payload := TakeOutStatsForServer(suite.serverID)
  135. suite.Equal(payload, zeroPayload, "should be zero stats after getting them")
  136. }
  137. func (suite *StatsTestSuite) Test_MakeRegexps() {
  138. hostnameRegexes := []map[string]string{make(map[string]string), make(map[string]string)}
  139. hostnameRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com)$`
  140. hostnameRegexes[0]["replace"] = "$1"
  141. hostnameRegexes[1]["regex"] = `^.*example\.org$`
  142. hostnameRegexes[1]["replace"] = "replacement"
  143. regexps, notices := MakeRegexps(hostnameRegexes)
  144. suite.NotNil(regexps, "should return a valid object")
  145. suite.Len(*regexps, 2, "should only have processed hostnameRegexes")
  146. suite.Len(notices, 0, "should return no notices")
  147. //
  148. // Test some bad regexps
  149. //
  150. hostnameRegexes[0]["regex"] = ""
  151. hostnameRegexes[0]["replace"] = "$1"
  152. regexps, notices = MakeRegexps(hostnameRegexes)
  153. suite.NotNil(regexps, "should return a valid object")
  154. suite.Len(*regexps, 1, "should have discarded one regexp")
  155. suite.Len(notices, 1, "should have returned one notice")
  156. hostnameRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com)$`
  157. hostnameRegexes[0]["replace"] = ""
  158. regexps, notices = MakeRegexps(hostnameRegexes)
  159. suite.NotNil(regexps, "should return a valid object")
  160. suite.Len(*regexps, 1, "should have discarded one regexp")
  161. suite.Len(notices, 1, "should have returned one notice")
  162. hostnameRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com$` // missing closing paren
  163. hostnameRegexes[0]["replace"] = "$1"
  164. regexps, notices = MakeRegexps(hostnameRegexes)
  165. suite.NotNil(regexps, "should return a valid object")
  166. suite.Len(*regexps, 1, "should have discarded one regexp")
  167. suite.Len(notices, 1, "should have returned one notice")
  168. }
  169. func (suite *StatsTestSuite) Test_Regex() {
  170. // We'll make a new client with actual regexps.
  171. hostnameRegexes := []map[string]string{make(map[string]string), make(map[string]string)}
  172. hostnameRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com)$`
  173. hostnameRegexes[0]["replace"] = "$1"
  174. hostnameRegexes[1]["regex"] = `^.*example\.org$`
  175. hostnameRegexes[1]["replace"] = "replacement"
  176. regexps, _ := MakeRegexps(hostnameRegexes)
  177. suite.httpClient = &http.Client{
  178. Transport: &http.Transport{
  179. Dial: makeStatsDialer(suite.serverID, regexps),
  180. },
  181. }
  182. // Using both HTTP and HTTPS will help us to exercise both methods of hostname parsing
  183. for _, scheme := range []string{"http", "https"} {
  184. // No subdomain, so won't match regex
  185. url := fmt.Sprintf("%s://example.com/index.html", scheme)
  186. resp, err := suite.httpClient.Get(url)
  187. suite.Nil(err)
  188. resp.Body.Close()
  189. // Will match the first regex
  190. url = fmt.Sprintf("%s://www.example.com/index.html", scheme)
  191. resp, err = suite.httpClient.Get(url)
  192. suite.Nil(err)
  193. resp.Body.Close()
  194. // Will match the second regex
  195. url = fmt.Sprintf("%s://example.org/index.html", scheme)
  196. resp, err = suite.httpClient.Get(url)
  197. suite.Nil(err)
  198. resp.Body.Close()
  199. payload := TakeOutStatsForServer(suite.serverID)
  200. suite.NotNil(payload, "should get stats because we made HTTP reqs; %s", scheme)
  201. expectedHostnames := mapset.NewSet()
  202. expectedHostnames.Add("(OTHER)")
  203. expectedHostnames.Add("example.com")
  204. expectedHostnames.Add("replacement")
  205. hostnames := make([]interface{}, 0)
  206. for hostname := range payload.hostnameToStats {
  207. hostnames = append(hostnames, hostname)
  208. }
  209. actualHostnames := mapset.NewSetFromSlice(hostnames)
  210. suite.Equal(expectedHostnames, actualHostnames, "post-regex hostnames should be processed as expecteds; %s", scheme)
  211. }
  212. }
  213. func (suite *StatsTestSuite) Test_getTLSHostname() {
  214. // TODO: Create a more robust/antagonistic set of negative tests.
  215. // We can write raw TCP to simulate any arbitrary degree of "almost looks
  216. // like a TLS handshake".
  217. // These tests are basically just checking for crashes.
  218. //
  219. // An easier way to construct valid client-hello messages (but not malicious ones)
  220. // would be to use the clientHelloMsg struct and marshal function from:
  221. // https://github.com/golang/go/blob/master/src/crypto/tls/handshake_messages.go
  222. // TODO: Talk to a local TCP server instead of spamming example.com
  223. dialer := makeStatsDialer(suite.serverID, nil)
  224. // Data too short
  225. conn, err := dialer("tcp", "example.com:80")
  226. suite.Nil(err)
  227. b := []byte(`my bytes`)
  228. n, err := conn.Write(b)
  229. suite.Nil(err)
  230. suite.Equal(len(b), n)
  231. err = conn.Close()
  232. suite.Nil(err)
  233. // Data long enough, but wrong first byte
  234. conn, err = dialer("tcp", "example.com:80")
  235. suite.Nil(err)
  236. 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}
  237. n, err = conn.Write(b)
  238. suite.Nil(err)
  239. suite.Equal(len(b), n)
  240. err = conn.Close()
  241. suite.Nil(err)
  242. // Data long enough, correct first byte
  243. conn, err = dialer("tcp", "example.com:80")
  244. suite.Nil(err)
  245. 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}
  246. n, err = conn.Write(b)
  247. suite.Nil(err)
  248. suite.Equal(len(b), n)
  249. err = conn.Close()
  250. suite.Nil(err)
  251. // Correct until after SSL version
  252. conn, err = dialer("tcp", "example.com:80")
  253. suite.Nil(err)
  254. 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}
  255. n, err = conn.Write(b)
  256. suite.Nil(err)
  257. suite.Equal(len(b), n)
  258. err = conn.Close()
  259. suite.Nil(err)
  260. plaintextLen := byte(70)
  261. // Correct until after plaintext length
  262. conn, err = dialer("tcp", "example.com:80")
  263. suite.Nil(err)
  264. 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}
  265. n, err = conn.Write(b)
  266. suite.Nil(err)
  267. suite.Equal(len(b), n)
  268. err = conn.Close()
  269. suite.Nil(err)
  270. // Correct until after handshake type
  271. conn, err = dialer("tcp", "example.com:80")
  272. suite.Nil(err)
  273. 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}
  274. n, err = conn.Write(b)
  275. suite.Nil(err)
  276. suite.Equal(len(b), n)
  277. err = conn.Close()
  278. suite.Nil(err)
  279. // Correct until after handshake length
  280. conn, err = dialer("tcp", "example.com:80")
  281. suite.Nil(err)
  282. 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}
  283. n, err = conn.Write(b)
  284. suite.Nil(err)
  285. suite.Equal(len(b), n)
  286. err = conn.Close()
  287. suite.Nil(err)
  288. // Correct until after protocol version
  289. conn, err = dialer("tcp", "example.com:80")
  290. suite.Nil(err)
  291. 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}
  292. n, err = conn.Write(b)
  293. suite.Nil(err)
  294. suite.Equal(len(b), n)
  295. err = conn.Close()
  296. suite.Nil(err)
  297. }