server_test.go 8.0 KB

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