server_test.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. /*
  2. * Copyright (c) 2016, 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 server
  20. import (
  21. "encoding/json"
  22. "flag"
  23. "fmt"
  24. "io/ioutil"
  25. "net/http"
  26. "net/url"
  27. "os"
  28. "sync"
  29. "syscall"
  30. "testing"
  31. "time"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  33. )
  34. func TestMain(m *testing.M) {
  35. flag.Parse()
  36. os.Remove(psiphon.DATA_STORE_FILENAME)
  37. psiphon.SetEmitDiagnosticNotices(true)
  38. os.Exit(m.Run())
  39. }
  40. // Note: not testing fronting meek protocols, which client is
  41. // hard-wired to except running on privileged ports 80 and 443.
  42. func TestSSH(t *testing.T) {
  43. runServer(t,
  44. &runServerConfig{
  45. tunnelProtocol: "SSH",
  46. enableSSHAPIRequests: true,
  47. doHotReload: false,
  48. })
  49. }
  50. func TestOSSH(t *testing.T) {
  51. runServer(t,
  52. &runServerConfig{
  53. tunnelProtocol: "OSSH",
  54. enableSSHAPIRequests: true,
  55. doHotReload: false,
  56. })
  57. }
  58. func TestUnfrontedMeek(t *testing.T) {
  59. runServer(t,
  60. &runServerConfig{
  61. tunnelProtocol: "UNFRONTED-MEEK-OSSH",
  62. enableSSHAPIRequests: true,
  63. doHotReload: false,
  64. })
  65. }
  66. func TestUnfrontedMeekHTTPS(t *testing.T) {
  67. runServer(t,
  68. &runServerConfig{
  69. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  70. enableSSHAPIRequests: true,
  71. doHotReload: false,
  72. })
  73. }
  74. func TestWebTransportAPIRequests(t *testing.T) {
  75. runServer(t,
  76. &runServerConfig{
  77. tunnelProtocol: "OSSH",
  78. enableSSHAPIRequests: false,
  79. doHotReload: false,
  80. })
  81. }
  82. func TestHotReload(t *testing.T) {
  83. runServer(t,
  84. &runServerConfig{
  85. tunnelProtocol: "OSSH",
  86. enableSSHAPIRequests: true,
  87. doHotReload: true,
  88. })
  89. }
  90. type runServerConfig struct {
  91. tunnelProtocol string
  92. enableSSHAPIRequests bool
  93. doHotReload bool
  94. }
  95. func runServer(t *testing.T, runConfig *runServerConfig) {
  96. // create a server
  97. serverConfigJSON, _, encodedServerEntry, err := GenerateConfig(
  98. &GenerateConfigParams{
  99. ServerIPAddress: "127.0.0.1",
  100. EnableSSHAPIRequests: runConfig.enableSSHAPIRequests,
  101. WebServerPort: 8000,
  102. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: 4000},
  103. })
  104. if err != nil {
  105. t.Fatalf("error generating server config: %s", err)
  106. }
  107. // customize server config
  108. // Pave psinet with random values to test handshake homepages.
  109. psinetFilename := "psinet.json"
  110. sponsorID, expectedHomepageURL := pavePsinetDatabaseFile(t, psinetFilename)
  111. var serverConfig interface{}
  112. json.Unmarshal(serverConfigJSON, &serverConfig)
  113. serverConfig.(map[string]interface{})["GeoIPDatabaseFilename"] = ""
  114. serverConfig.(map[string]interface{})["PsinetDatabaseFilename"] = psinetFilename
  115. serverConfig.(map[string]interface{})["TrafficRulesFilename"] = ""
  116. serverConfigJSON, _ = json.Marshal(serverConfig)
  117. // run server
  118. serverWaitGroup := new(sync.WaitGroup)
  119. serverWaitGroup.Add(1)
  120. go func() {
  121. defer serverWaitGroup.Done()
  122. err := RunServices(serverConfigJSON)
  123. if err != nil {
  124. // TODO: wrong goroutine for t.FatalNow()
  125. t.Fatalf("error running server: %s", err)
  126. }
  127. }()
  128. defer func() {
  129. // Test: orderly server shutdown
  130. p, _ := os.FindProcess(os.Getpid())
  131. p.Signal(os.Interrupt)
  132. shutdownTimeout := time.NewTimer(5 * time.Second)
  133. shutdownOk := make(chan struct{}, 1)
  134. go func() {
  135. serverWaitGroup.Wait()
  136. shutdownOk <- *new(struct{})
  137. }()
  138. select {
  139. case <-shutdownOk:
  140. case <-shutdownTimeout.C:
  141. t.Fatalf("server shutdown timeout exceeded")
  142. }
  143. }()
  144. // Test: hot reload (of psinet)
  145. if runConfig.doHotReload {
  146. // TODO: monitor logs for more robust wait-until-loaded
  147. time.Sleep(1 * time.Second)
  148. // Pave a new psinet with different random values.
  149. sponsorID, expectedHomepageURL = pavePsinetDatabaseFile(t, psinetFilename)
  150. p, _ := os.FindProcess(os.Getpid())
  151. p.Signal(syscall.SIGUSR1)
  152. // TODO: monitor logs for more robust wait-until-reloaded
  153. time.Sleep(1 * time.Second)
  154. // After reloading psinet, the new sponsorID/expectedHomepageURL
  155. // should be active, as tested in the client "Homepage" notice
  156. // handler below.
  157. }
  158. // connect to server with client
  159. // TODO: currently, TargetServerEntry only works with one tunnel
  160. numTunnels := 1
  161. localHTTPProxyPort := 8081
  162. establishTunnelPausePeriodSeconds := 1
  163. // Note: calling LoadConfig ensures all *int config fields are initialized
  164. clientConfigJSON := `
  165. {
  166. "ClientVersion" : "0",
  167. "SponsorId" : "0",
  168. "PropagationChannelId" : "0"
  169. }`
  170. clientConfig, _ := psiphon.LoadConfig([]byte(clientConfigJSON))
  171. clientConfig.SponsorId = sponsorID
  172. clientConfig.ConnectionWorkerPoolSize = numTunnels
  173. clientConfig.TunnelPoolSize = numTunnels
  174. clientConfig.DisableRemoteServerListFetcher = true
  175. clientConfig.EstablishTunnelPausePeriodSeconds = &establishTunnelPausePeriodSeconds
  176. clientConfig.TargetServerEntry = string(encodedServerEntry)
  177. clientConfig.TunnelProtocol = runConfig.tunnelProtocol
  178. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  179. err = psiphon.InitDataStore(clientConfig)
  180. if err != nil {
  181. t.Fatalf("error initializing client datastore: %s", err)
  182. }
  183. controller, err := psiphon.NewController(clientConfig)
  184. if err != nil {
  185. t.Fatalf("error creating client controller: %s", err)
  186. }
  187. tunnelsEstablished := make(chan struct{}, 1)
  188. homepageReceived := make(chan struct{}, 1)
  189. psiphon.SetNoticeOutput(psiphon.NewNoticeReceiver(
  190. func(notice []byte) {
  191. //fmt.Printf("%s\n", string(notice))
  192. noticeType, payload, err := psiphon.GetNotice(notice)
  193. if err != nil {
  194. return
  195. }
  196. switch noticeType {
  197. case "Tunnels":
  198. count := int(payload["count"].(float64))
  199. if count >= numTunnels {
  200. select {
  201. case tunnelsEstablished <- *new(struct{}):
  202. default:
  203. }
  204. }
  205. case "Homepage":
  206. homepageURL := payload["url"].(string)
  207. if homepageURL != expectedHomepageURL {
  208. // TODO: wrong goroutine for t.FatalNow()
  209. t.Fatalf("unexpected homepage: %s", homepageURL)
  210. }
  211. select {
  212. case homepageReceived <- *new(struct{}):
  213. default:
  214. }
  215. }
  216. }))
  217. controllerShutdownBroadcast := make(chan struct{})
  218. controllerWaitGroup := new(sync.WaitGroup)
  219. controllerWaitGroup.Add(1)
  220. go func() {
  221. defer controllerWaitGroup.Done()
  222. controller.Run(controllerShutdownBroadcast)
  223. }()
  224. defer func() {
  225. close(controllerShutdownBroadcast)
  226. shutdownTimeout := time.NewTimer(20 * time.Second)
  227. shutdownOk := make(chan struct{}, 1)
  228. go func() {
  229. controllerWaitGroup.Wait()
  230. shutdownOk <- *new(struct{})
  231. }()
  232. select {
  233. case <-shutdownOk:
  234. case <-shutdownTimeout.C:
  235. t.Fatalf("controller shutdown timeout exceeded")
  236. }
  237. }()
  238. // Test: tunnels must be established, and correct homepage
  239. // must be received, within 30 seconds
  240. establishTimeout := time.NewTimer(30 * time.Second)
  241. select {
  242. case <-tunnelsEstablished:
  243. case <-establishTimeout.C:
  244. t.Fatalf("tunnel establish timeout exceeded")
  245. }
  246. select {
  247. case <-homepageReceived:
  248. case <-establishTimeout.C:
  249. t.Fatalf("homepage received timeout exceeded")
  250. }
  251. // Test: tunneled web site fetch
  252. testUrl := "https://psiphon.ca"
  253. roundTripTimeout := 30 * time.Second
  254. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  255. if err != nil {
  256. t.Fatalf("error initializing proxied HTTP request: %s", err)
  257. }
  258. httpClient := &http.Client{
  259. Transport: &http.Transport{
  260. Proxy: http.ProxyURL(proxyUrl),
  261. },
  262. Timeout: roundTripTimeout,
  263. }
  264. response, err := httpClient.Get(testUrl)
  265. if err != nil {
  266. t.Fatalf("error sending proxied HTTP request: %s", err)
  267. }
  268. _, err = ioutil.ReadAll(response.Body)
  269. if err != nil {
  270. t.Fatalf("error reading proxied HTTP response: %s", err)
  271. }
  272. response.Body.Close()
  273. }
  274. func pavePsinetDatabaseFile(t *testing.T, psinetFilename string) (string, string) {
  275. sponsorID, _ := psiphon.MakeRandomStringHex(8)
  276. fakeDomain, _ := psiphon.MakeRandomStringHex(4)
  277. fakePath, _ := psiphon.MakeRandomStringHex(4)
  278. expectedHomepageURL := fmt.Sprintf("https://%s.com/%s", fakeDomain, fakePath)
  279. psinetJSONFormat := `
  280. {
  281. "sponsors": {
  282. "%s": {
  283. "home_pages": {
  284. "None": [
  285. {
  286. "region": null,
  287. "url": "%s"
  288. }
  289. ]
  290. }
  291. }
  292. }
  293. }
  294. `
  295. psinetJSON := fmt.Sprintf(psinetJSONFormat, sponsorID, expectedHomepageURL)
  296. err := ioutil.WriteFile(psinetFilename, []byte(psinetJSON), 0600)
  297. if err != nil {
  298. t.Fatalf("error paving psinet database: %s", err)
  299. }
  300. return sponsorID, expectedHomepageURL
  301. }