psinet_test.go 12 KB

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