psinet_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /*
  2. * Copyright (c) 2017, 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 psinet
  20. import (
  21. "bytes"
  22. "fmt"
  23. "io/ioutil"
  24. "os"
  25. "path/filepath"
  26. "strconv"
  27. "testing"
  28. "time"
  29. )
  30. func TestDatabase(t *testing.T) {
  31. testDataDirName, err := ioutil.TempDir("", "psinet-test")
  32. if err != nil {
  33. t.Fatalf("TempDir failed: %s\n", err)
  34. }
  35. defer os.RemoveAll(testDataDirName)
  36. databaseJSON := `
  37. {
  38. "sponsors" : {
  39. "SPONSOR-ID" : {
  40. "id" : "SPONSOR-ID",
  41. "home_pages" : {
  42. "CLIENT-REGION" : [{
  43. "region" : "CLIENT-REGION",
  44. "url" : "HOME-PAGE-URL?client_region=XX"
  45. }],
  46. "None" : [{
  47. "region" : "None",
  48. "url" : "DEFAULT-HOME-PAGE-URL?client_region=XX"
  49. }]
  50. },
  51. "mobile_home_pages": {
  52. "CLIENT-REGION" : [{
  53. "region" : "CLIENT-REGION",
  54. "url" : "MOBILE-HOME-PAGE-URL?client_region=XX&client_asn=XX"
  55. }],
  56. "None" : [{
  57. "region" : "None",
  58. "url" : "DEFAULT-MOBILE-HOME-PAGE-URL?client_region=XX&client_asn=XX"
  59. }]
  60. },
  61. "alert_action_urls" : {
  62. "ALERT-REASON-1" : ["SPONSOR-ALERT-1-ACTION-URL?client_region=XX"]
  63. },
  64. "https_request_regexes" : [{
  65. "regex" : "REGEX-VALUE",
  66. "replace" : "REPLACE-VALUE"
  67. }]
  68. }
  69. },
  70. "client_versions" : {
  71. "CLIENT-PLATFORM" : [
  72. {"version" : "1"},
  73. {"version" : "2"}
  74. ]
  75. },
  76. "default_sponsor_id" : "SPONSOR-ID",
  77. "default_alert_action_urls" : {
  78. "ALERT-REASON-1" : ["DEFAULT-ALERT-1-ACTION-URL?client_region=XX"],
  79. "ALERT-REASON-2" : ["DEFAULT-ALERT-2-ACTION-URL?client_region=XX"]
  80. },
  81. "valid_server_entry_tags" : {
  82. "SERVER-ENTRY-TAG" : true
  83. },
  84. "discovery_servers" : [
  85. {"discovery_date_range" : ["1900-01-01T00:00:00Z", "2000-01-01T00:00:00Z"], "encoded_server_entry" : "0"},
  86. {"discovery_date_range" : ["1900-01-01T00:00:00Z", "2000-01-01T00:00:00Z"], "encoded_server_entry" : "0"},
  87. {"discovery_date_range" : ["1900-01-01T00:00:00Z", "2000-01-01T00:00:00Z"], "encoded_server_entry" : "0"},
  88. {"discovery_date_range" : ["1900-01-01T00:00:00Z", "2000-01-01T00:00:00Z"], "encoded_server_entry" : "0"},
  89. {"discovery_date_range" : ["2000-01-01T00:00:00Z", "2100-01-01T00:00:00Z"], "encoded_server_entry" : "1"},
  90. {"discovery_date_range" : ["2000-01-01T00:00:00Z", "2100-01-01T00:00:00Z"], "encoded_server_entry" : "1"},
  91. {"discovery_date_range" : ["2000-01-01T00:00:00Z", "2100-01-01T00:00:00Z"], "encoded_server_entry" : "1"},
  92. {"discovery_date_range" : ["2000-01-01T00:00:00Z", "2100-01-01T00:00:00Z"], "encoded_server_entry" : "1"}
  93. ]
  94. }`
  95. filename := filepath.Join(testDataDirName, "psinet.json")
  96. err = ioutil.WriteFile(filename, []byte(databaseJSON), 0600)
  97. if err != nil {
  98. t.Fatalf("WriteFile failed: %s", err)
  99. }
  100. db, err := NewDatabase(filename)
  101. if err != nil {
  102. t.Fatalf("NewDatabase failed: %s", err)
  103. }
  104. homePageTestCases := []struct {
  105. sponsorID string
  106. clientRegion string
  107. clientASN string
  108. isMobile bool
  109. expectedURL string
  110. }{
  111. {"SPONSOR-ID", "CLIENT-REGION", "65535", false, "HOME-PAGE-URL?client_region=CLIENT-REGION"},
  112. {"SPONSOR-ID", "UNCONFIGURED-CLIENT-REGION", "65535", false, "DEFAULT-HOME-PAGE-URL?client_region=UNCONFIGURED-CLIENT-REGION"},
  113. {"SPONSOR-ID", "CLIENT-REGION", "65535", true, "MOBILE-HOME-PAGE-URL?client_region=CLIENT-REGION&client_asn=65535"},
  114. {"SPONSOR-ID", "UNCONFIGURED-CLIENT-REGION", "65535", true, "DEFAULT-MOBILE-HOME-PAGE-URL?client_region=UNCONFIGURED-CLIENT-REGION&client_asn=65535"},
  115. {"UNCONFIGURED-SPONSOR-ID", "CLIENT-REGION", "65535", false, "HOME-PAGE-URL?client_region=CLIENT-REGION"},
  116. {"UNCONFIGURED-SPONSOR-ID", "UNCONFIGURED-CLIENT-REGION", "65535", false, "DEFAULT-HOME-PAGE-URL?client_region=UNCONFIGURED-CLIENT-REGION"},
  117. {"UNCONFIGURED-SPONSOR-ID", "CLIENT-REGION", "65535", true, "MOBILE-HOME-PAGE-URL?client_region=CLIENT-REGION&client_asn=65535"},
  118. {"UNCONFIGURED-SPONSOR-ID", "UNCONFIGURED-CLIENT-REGION", "65535", true, "DEFAULT-MOBILE-HOME-PAGE-URL?client_region=UNCONFIGURED-CLIENT-REGION&client_asn=65535"},
  119. }
  120. for _, testCase := range homePageTestCases {
  121. t.Run(fmt.Sprintf("%+v", testCase), func(t *testing.T) {
  122. homepages := db.GetHomepages(testCase.sponsorID, testCase.clientRegion, testCase.clientASN, testCase.isMobile)
  123. if len(homepages) != 1 || homepages[0] != testCase.expectedURL {
  124. t.Fatalf("unexpected home page: %+v", homepages)
  125. }
  126. })
  127. }
  128. alertActionURLTestCases := []struct {
  129. alertReason string
  130. sponsorID string
  131. expectedURLCount int
  132. expectedURL string
  133. }{
  134. {"ALERT-REASON-1", "SPONSOR-ID", 1, "SPONSOR-ALERT-1-ACTION-URL?client_region=CLIENT-REGION"},
  135. {"ALERT-REASON-1", "UNCONFIGURED-SPONSOR-ID", 1, "DEFAULT-ALERT-1-ACTION-URL?client_region=CLIENT-REGION"},
  136. {"ALERT-REASON-2", "SPONSOR-ID", 1, "DEFAULT-ALERT-2-ACTION-URL?client_region=CLIENT-REGION"},
  137. {"ALERT-REASON-2", "UNCONFIGURED-SPONSOR-ID", 1, "DEFAULT-ALERT-2-ACTION-URL?client_region=CLIENT-REGION"},
  138. {"UNCONFIGURED-ALERT-REASON", "SPONSOR-ID", 0, ""},
  139. }
  140. for _, testCase := range alertActionURLTestCases {
  141. t.Run(fmt.Sprintf("%+v", testCase), func(t *testing.T) {
  142. URLs := db.GetAlertActionURLs(testCase.alertReason, testCase.sponsorID, "CLIENT-REGION", "")
  143. if len(URLs) != testCase.expectedURLCount || (len(URLs) > 0 && URLs[0] != testCase.expectedURL) {
  144. t.Fatalf("unexpected URLs: %d %+v, %+v", testCase.expectedURLCount, testCase.expectedURL, URLs)
  145. }
  146. })
  147. }
  148. versionTestCases := []struct {
  149. currentClientVersion string
  150. clientPlatform string
  151. expectedUpgradeClientVersion string
  152. }{
  153. {"0", "CLIENT-PLATFORM", "2"},
  154. {"1", "CLIENT-PLATFORM", "2"},
  155. {"2", "CLIENT-PLATFORM", ""},
  156. {"3", "CLIENT-PLATFORM", ""},
  157. {"2", "UNCONFIGURED-CLIENT-PLATFORM", ""},
  158. }
  159. for _, testCase := range versionTestCases {
  160. t.Run(fmt.Sprintf("%+v", testCase), func(t *testing.T) {
  161. upgradeVersion := db.GetUpgradeClientVersion(testCase.currentClientVersion, testCase.clientPlatform)
  162. if upgradeVersion != testCase.expectedUpgradeClientVersion {
  163. t.Fatalf("unexpected upgrade version: %s", upgradeVersion)
  164. }
  165. })
  166. }
  167. httpsRegexTestCases := []struct {
  168. sponsorID string
  169. expectedRegexValue string
  170. expectedReplaceValue string
  171. }{
  172. {"SPONSOR-ID", "REGEX-VALUE", "REPLACE-VALUE"},
  173. {"UNCONFIGURED-SPONSOR-ID", "REGEX-VALUE", "REPLACE-VALUE"},
  174. }
  175. for _, testCase := range httpsRegexTestCases {
  176. t.Run(fmt.Sprintf("%+v", testCase), func(t *testing.T) {
  177. regexes, checksum := db.GetHttpsRequestRegexes(testCase.sponsorID)
  178. if !bytes.Equal(checksum, db.GetDomainBytesChecksum(testCase.sponsorID)) {
  179. t.Fatalf("unexpected checksum: %+v", checksum)
  180. }
  181. var regexValue, replaceValue string
  182. ok := false
  183. if len(regexes) == 1 && len(regexes[0]) == 2 {
  184. regexValue, ok = regexes[0]["regex"]
  185. if ok {
  186. replaceValue, ok = regexes[0]["replace"]
  187. }
  188. }
  189. if !ok || regexValue != testCase.expectedRegexValue || replaceValue != testCase.expectedReplaceValue {
  190. t.Fatalf("unexpected regexes: %+v", regexes)
  191. }
  192. })
  193. }
  194. for i := 0; i < 1000; i++ {
  195. encodedServerEntries := db.DiscoverServers(i)
  196. if len(encodedServerEntries) != 1 || encodedServerEntries[0] != "1" {
  197. t.Fatalf("unexpected discovery server list: %+v", encodedServerEntries)
  198. }
  199. }
  200. if !db.IsValidServerEntryTag("SERVER-ENTRY-TAG") {
  201. t.Fatalf("unexpected invalid server entry tag")
  202. }
  203. if db.IsValidServerEntryTag("INVALID-SERVER-ENTRY-TAG") {
  204. t.Fatalf("unexpected valid server entry tag")
  205. }
  206. }
  207. func TestDiscoveryBuckets(t *testing.T) {
  208. checkBuckets := func(buckets [][]*DiscoveryServer, expectedServerEntries [][]int) {
  209. if len(buckets) != len(expectedServerEntries) {
  210. t.Errorf(
  211. "unexpected bucket count: got %d expected %d",
  212. len(buckets), len(expectedServerEntries))
  213. return
  214. }
  215. for i := 0; i < len(buckets); i++ {
  216. if len(buckets[i]) != len(expectedServerEntries[i]) {
  217. t.Errorf(
  218. "unexpected bucket %d size: got %d expected %d",
  219. i, len(buckets[i]), len(expectedServerEntries[i]))
  220. return
  221. }
  222. for j := 0; j < len(buckets[i]); j++ {
  223. expectedServerEntry := strconv.Itoa(expectedServerEntries[i][j])
  224. if buckets[i][j].EncodedServerEntry != expectedServerEntry {
  225. t.Errorf(
  226. "unexpected bucket %d item %d: got %s expected %s",
  227. i, j, buckets[i][j].EncodedServerEntry, expectedServerEntry)
  228. return
  229. }
  230. }
  231. }
  232. }
  233. // Partition test cases from:
  234. // http://stackoverflow.com/questions/2659900/python-slicing-a-list-into-n-nearly-equal-length-partitions
  235. servers := make([]*DiscoveryServer, 0)
  236. for i := 0; i < 105; i++ {
  237. servers = append(servers, &DiscoveryServer{EncodedServerEntry: strconv.Itoa(i)})
  238. }
  239. t.Run("5 servers, 5 buckets", func(t *testing.T) {
  240. checkBuckets(
  241. bucketizeServerList(servers[0:5], 5),
  242. [][]int{{0}, {1}, {2}, {3}, {4}})
  243. })
  244. t.Run("5 servers, 2 buckets", func(t *testing.T) {
  245. checkBuckets(
  246. bucketizeServerList(servers[0:5], 2),
  247. [][]int{{0, 1, 2}, {3, 4}})
  248. })
  249. t.Run("5 servers, 3 buckets", func(t *testing.T) {
  250. checkBuckets(
  251. bucketizeServerList(servers[0:5], 3),
  252. [][]int{{0, 1}, {2}, {3, 4}})
  253. })
  254. t.Run("105 servers, 10 buckets", func(t *testing.T) {
  255. checkBuckets(
  256. bucketizeServerList(servers, 10),
  257. [][]int{
  258. {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
  259. {11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
  260. {21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31},
  261. {32, 33, 34, 35, 36, 37, 38, 39, 40, 41},
  262. {42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52},
  263. {53, 54, 55, 56, 57, 58, 59, 60, 61, 62},
  264. {63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73},
  265. {74, 75, 76, 77, 78, 79, 80, 81, 82, 83},
  266. {84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94},
  267. {95, 96, 97, 98, 99, 100, 101, 102, 103, 104},
  268. })
  269. })
  270. t.Run("repeatedly discover with fixed IP address", func(t *testing.T) {
  271. // For a IP address values, only one bucket should be used; with enough
  272. // iterations, all and only the items in a single bucket should be discovered.
  273. discoveredServers := make(map[string]bool)
  274. // discoveryValue is derived from the client's IP address and indexes the bucket;
  275. // a value of 0 always maps to the first bucket.
  276. discoveryValue := 0
  277. for i := 0; i < 1000; i++ {
  278. for _, server := range selectServers(servers, i*int(time.Hour/time.Second), discoveryValue) {
  279. discoveredServers[server.EncodedServerEntry] = true
  280. }
  281. }
  282. bucketCount := calculateBucketCount(len(servers))
  283. buckets := bucketizeServerList(servers, bucketCount)
  284. if len(buckets[0]) != len(discoveredServers) {
  285. t.Errorf(
  286. "unexpected discovered server count: got %d expected %d",
  287. len(discoveredServers), len(buckets[0]))
  288. return
  289. }
  290. for _, bucketServer := range buckets[0] {
  291. if _, ok := discoveredServers[bucketServer.EncodedServerEntry]; !ok {
  292. t.Errorf("unexpected missing discovery server: %s", bucketServer.EncodedServerEntry)
  293. return
  294. }
  295. }
  296. })
  297. }