psinet_test.go 12 KB

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