transferstats_test.go 12 KB

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