controller_test.go 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  1. /*
  2. * Copyright (c) 2015, 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 psiphon
  20. import (
  21. "context"
  22. "encoding/json"
  23. "flag"
  24. "fmt"
  25. "io"
  26. "io/ioutil"
  27. "log"
  28. "net"
  29. "net/http"
  30. "net/url"
  31. "os"
  32. "strings"
  33. "sync"
  34. "sync/atomic"
  35. "testing"
  36. "time"
  37. socks "github.com/Psiphon-Labs/goptlib"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/inproxy"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic"
  42. "github.com/elazarl/goproxy"
  43. "github.com/elazarl/goproxy/ext/auth"
  44. )
  45. const testClientPlatform = "test_github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  46. func TestMain(m *testing.M) {
  47. flag.Parse()
  48. SetEmitDiagnosticNotices(true, true)
  49. initDisruptor()
  50. initUpstreamProxy()
  51. os.Exit(m.Run())
  52. }
  53. // Test case notes/limitations/dependencies:
  54. //
  55. // * Untunneled upgrade tests must execute before
  56. // the other tests to ensure no tunnel is established.
  57. // We need a way to reset the datastore after it's been
  58. // initialized in order to to clear out its data entries
  59. // and be able to arbitrarily order the tests.
  60. //
  61. // * The resumable download tests using disruptNetwork
  62. // depend on the download object being larger than the
  63. // disruptorMax limits so that the disruptor will actually
  64. // interrupt the first download attempt. Specifically, the
  65. // upgrade and remote server list at the URLs specified in
  66. // controller_test.config.enc.
  67. //
  68. // * The protocol tests assume there is at least one server
  69. // supporting each protocol in the server list at the URL
  70. // specified in controller_test.config.enc, and that these
  71. // servers are not overloaded.
  72. //
  73. // * fetchAndVerifyWebsite depends on the target URL being
  74. // available and responding.
  75. //
  76. func TestUntunneledUpgradeDownload(t *testing.T) {
  77. controllerRun(t,
  78. &controllerRunConfig{
  79. expectNoServerEntries: true,
  80. protocol: "",
  81. disableEstablishing: true,
  82. })
  83. }
  84. func TestUntunneledResumableUpgradeDownload(t *testing.T) {
  85. controllerRun(t,
  86. &controllerRunConfig{
  87. expectNoServerEntries: true,
  88. protocol: "",
  89. disableEstablishing: true,
  90. disruptNetwork: true,
  91. })
  92. }
  93. func TestUntunneledUpgradeClientIsLatestVersion(t *testing.T) {
  94. controllerRun(t,
  95. &controllerRunConfig{
  96. expectNoServerEntries: true,
  97. protocol: "",
  98. clientIsLatestVersion: true,
  99. disableEstablishing: true,
  100. })
  101. }
  102. func TestUntunneledResumableFetchRemoteServerList(t *testing.T) {
  103. controllerRun(t,
  104. &controllerRunConfig{
  105. expectNoServerEntries: true,
  106. protocol: "",
  107. clientIsLatestVersion: true,
  108. disruptNetwork: true,
  109. })
  110. }
  111. func TestTunneledUpgradeClientIsLatestVersion(t *testing.T) {
  112. controllerRun(t,
  113. &controllerRunConfig{
  114. protocol: "",
  115. clientIsLatestVersion: true,
  116. disableUntunneledUpgrade: true,
  117. })
  118. }
  119. func TestSSH(t *testing.T) {
  120. controllerRun(t,
  121. &controllerRunConfig{
  122. protocol: protocol.TUNNEL_PROTOCOL_SSH,
  123. disableUntunneledUpgrade: true,
  124. })
  125. }
  126. func TestObfuscatedSSH(t *testing.T) {
  127. controllerRun(t,
  128. &controllerRunConfig{
  129. protocol: protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  130. disableUntunneledUpgrade: true,
  131. })
  132. }
  133. func TestTLSOSSH(t *testing.T) {
  134. controllerRun(t,
  135. &controllerRunConfig{
  136. protocol: protocol.TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH,
  137. disableUntunneledUpgrade: true,
  138. })
  139. }
  140. func TestUnfrontedMeek(t *testing.T) {
  141. controllerRun(t,
  142. &controllerRunConfig{
  143. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK,
  144. disableUntunneledUpgrade: true,
  145. })
  146. }
  147. func TestUnfrontedMeekWithTransformer(t *testing.T) {
  148. controllerRun(t,
  149. &controllerRunConfig{
  150. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK,
  151. disableUntunneledUpgrade: true,
  152. transformHostNames: true,
  153. })
  154. }
  155. func TestFrontedMeek(t *testing.T) {
  156. controllerRun(t,
  157. &controllerRunConfig{
  158. protocol: protocol.TUNNEL_PROTOCOL_FRONTED_MEEK,
  159. disableUntunneledUpgrade: true,
  160. })
  161. }
  162. func TestFrontedMeekWithTransformer(t *testing.T) {
  163. controllerRun(t,
  164. &controllerRunConfig{
  165. protocol: protocol.TUNNEL_PROTOCOL_FRONTED_MEEK,
  166. disableUntunneledUpgrade: true,
  167. transformHostNames: true,
  168. })
  169. }
  170. func TestFrontedMeekHTTP(t *testing.T) {
  171. controllerRun(t,
  172. &controllerRunConfig{
  173. protocol: protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP,
  174. disableUntunneledUpgrade: true,
  175. })
  176. }
  177. func TestUnfrontedMeekHTTPS(t *testing.T) {
  178. controllerRun(t,
  179. &controllerRunConfig{
  180. expectNoServerEntries: false,
  181. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  182. disableUntunneledUpgrade: true,
  183. })
  184. }
  185. func TestUnfrontedMeekHTTPSWithTransformer(t *testing.T) {
  186. controllerRun(t,
  187. &controllerRunConfig{
  188. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  189. clientIsLatestVersion: true,
  190. transformHostNames: true,
  191. })
  192. }
  193. func TestDisabledApi(t *testing.T) {
  194. controllerRun(t,
  195. &controllerRunConfig{
  196. protocol: "",
  197. clientIsLatestVersion: true,
  198. disableUntunneledUpgrade: true,
  199. disableApi: true,
  200. tunnelPoolSize: 1,
  201. })
  202. }
  203. func TestObfuscatedSSHWithUpstreamProxy(t *testing.T) {
  204. controllerRun(t,
  205. &controllerRunConfig{
  206. protocol: protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  207. disableUntunneledUpgrade: true,
  208. useUpstreamProxy: true,
  209. })
  210. }
  211. func TestUnfrontedMeekWithUpstreamProxy(t *testing.T) {
  212. controllerRun(t,
  213. &controllerRunConfig{
  214. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK,
  215. disableUntunneledUpgrade: true,
  216. useUpstreamProxy: true,
  217. })
  218. }
  219. func TestUnfrontedMeekHTTPSWithUpstreamProxy(t *testing.T) {
  220. controllerRun(t,
  221. &controllerRunConfig{
  222. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  223. disableUntunneledUpgrade: true,
  224. useUpstreamProxy: true,
  225. })
  226. }
  227. func TestObfuscatedSSHFragmentor(t *testing.T) {
  228. controllerRun(t,
  229. &controllerRunConfig{
  230. protocol: protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  231. disableUntunneledUpgrade: true,
  232. useFragmentor: true,
  233. })
  234. }
  235. func TestFrontedMeekFragmentor(t *testing.T) {
  236. controllerRun(t,
  237. &controllerRunConfig{
  238. protocol: protocol.TUNNEL_PROTOCOL_FRONTED_MEEK,
  239. disableUntunneledUpgrade: true,
  240. useFragmentor: true,
  241. })
  242. }
  243. func TestQUIC(t *testing.T) {
  244. if !quic.Enabled() {
  245. t.Skip("QUIC is not enabled")
  246. }
  247. controllerRun(t,
  248. &controllerRunConfig{
  249. protocol: protocol.TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH,
  250. disableUntunneledUpgrade: true,
  251. })
  252. }
  253. func TestFrontedQUIC(t *testing.T) {
  254. if !quic.Enabled() {
  255. t.Skip("QUIC is not enabled")
  256. }
  257. controllerRun(t,
  258. &controllerRunConfig{
  259. protocol: protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH,
  260. disableUntunneledUpgrade: true,
  261. })
  262. }
  263. func TestInproxyOSSH(t *testing.T) {
  264. if !inproxy.Enabled() {
  265. t.Skip("In-proxy is not enabled")
  266. }
  267. controllerRun(t,
  268. &controllerRunConfig{
  269. protocol: "INPROXY-WEBRTC-OSSH",
  270. disableUntunneledUpgrade: true,
  271. useInproxyDialRateLimit: true,
  272. })
  273. }
  274. func TestInproxyQUICOSSH(t *testing.T) {
  275. if !inproxy.Enabled() {
  276. t.Skip("In-proxy is not enabled")
  277. }
  278. controllerRun(t,
  279. &controllerRunConfig{
  280. protocol: "INPROXY-WEBRTC-QUIC-OSSH",
  281. disableUntunneledUpgrade: true,
  282. useInproxyDialRateLimit: true,
  283. })
  284. }
  285. func TestInproxyUnfrontedMeekHTTPS(t *testing.T) {
  286. if !inproxy.Enabled() {
  287. t.Skip("In-proxy is not enabled")
  288. }
  289. controllerRun(t,
  290. &controllerRunConfig{
  291. protocol: "INPROXY-WEBRTC-UNFRONTED-MEEK-HTTPS-OSSH",
  292. disableUntunneledUpgrade: true,
  293. })
  294. }
  295. func TestInproxyTLSOSSH(t *testing.T) {
  296. if !inproxy.Enabled() {
  297. t.Skip("In-proxy is not enabled")
  298. }
  299. controllerRun(t,
  300. &controllerRunConfig{
  301. protocol: "INPROXY-WEBRTC-TLS-OSSH",
  302. disableUntunneledUpgrade: true,
  303. })
  304. }
  305. func TestTunnelPool(t *testing.T) {
  306. controllerRun(t,
  307. &controllerRunConfig{
  308. protocol: protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  309. disableUntunneledUpgrade: true,
  310. tunnelPoolSize: 2,
  311. })
  312. }
  313. func TestLegacyAPIEncoding(t *testing.T) {
  314. controllerRun(t,
  315. &controllerRunConfig{
  316. protocol: protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  317. useLegacyAPIEncoding: true,
  318. })
  319. }
  320. type controllerRunConfig struct {
  321. expectNoServerEntries bool
  322. protocol string
  323. clientIsLatestVersion bool
  324. disableUntunneledUpgrade bool
  325. disableEstablishing bool
  326. disableApi bool
  327. tunnelPoolSize int
  328. useUpstreamProxy bool
  329. disruptNetwork bool
  330. transformHostNames bool
  331. useFragmentor bool
  332. useLegacyAPIEncoding bool
  333. useInproxyDialRateLimit bool
  334. }
  335. func controllerRun(t *testing.T, runConfig *controllerRunConfig) {
  336. testDataDirName, err := ioutil.TempDir("", "psiphon-controller-test")
  337. if err != nil {
  338. t.Fatalf("TempDir failed: %s\n", err)
  339. }
  340. defer os.RemoveAll(testDataDirName)
  341. configJSON, err := ioutil.ReadFile("controller_test.config")
  342. if err != nil {
  343. // Skip, don't fail, if config file is not present
  344. t.Skipf("error loading configuration file: %s", err)
  345. }
  346. // Note: a successful tactics request may modify config parameters.
  347. var modifyConfig map[string]interface{}
  348. err = json.Unmarshal(configJSON, &modifyConfig)
  349. if err != nil {
  350. t.Fatalf("json.Unmarshal failed: %v", err)
  351. }
  352. modifyConfig["DataRootDirectory"] = testDataDirName
  353. if runConfig.protocol != "" {
  354. modifyConfig["LimitTunnelProtocols"] = protocol.TunnelProtocols{runConfig.protocol}
  355. }
  356. modifyConfig["EnableUpgradeDownload"] = true
  357. modifyConfig["EnableFeedbackUpload"] = false
  358. // Override client retry throttle values to speed up automated
  359. // tests and ensure tests complete within fixed deadlines.
  360. modifyConfig["FetchRemoteServerListRetryPeriodMilliseconds"] = 250
  361. modifyConfig["FetchUpgradeRetryPeriodMilliseconds"] = 250
  362. modifyConfig["EstablishTunnelPausePeriodSeconds"] = 1
  363. if runConfig.disableUntunneledUpgrade {
  364. // Break untunneled upgrade downloader to ensure tunneled case is tested
  365. modifyConfig["UpgradeDownloadClientVersionHeader"] = "invalid-value"
  366. }
  367. if runConfig.transformHostNames {
  368. modifyConfig["TransformHostNames"] = "always"
  369. } else {
  370. modifyConfig["TransformHostNames"] = "never"
  371. }
  372. if runConfig.useFragmentor {
  373. modifyConfig["UseFragmentor"] = "always"
  374. modifyConfig["FragmentorLimitProtocols"] = protocol.TunnelProtocols{runConfig.protocol}
  375. modifyConfig["FragmentorMinTotalBytes"] = 1000
  376. modifyConfig["FragmentorMaxTotalBytes"] = 2000
  377. modifyConfig["FragmentorMinWriteBytes"] = 1
  378. modifyConfig["FragmentorMaxWriteBytes"] = 100
  379. modifyConfig["FragmentorMinDelayMicroseconds"] = 1000
  380. modifyConfig["FragmentorMaxDelayMicroseconds"] = 10000
  381. modifyConfig["ObfuscatedSSHMinPadding"] = 4096
  382. modifyConfig["ObfuscatedSSHMaxPadding"] = 8192
  383. }
  384. if runConfig.useLegacyAPIEncoding {
  385. modifyConfig["TargetAPIEncoding"] = protocol.PSIPHON_API_ENCODING_JSON
  386. }
  387. if runConfig.useInproxyDialRateLimit {
  388. modifyConfig["InproxyClientDialRateLimitQuantity"] = 2
  389. modifyConfig["InproxyClientDialRateLimitIntervalMilliseconds"] = 1000
  390. }
  391. configJSON, _ = json.Marshal(modifyConfig)
  392. config, err := LoadConfig(configJSON)
  393. if err != nil {
  394. t.Fatalf("error processing configuration file: %s", err)
  395. }
  396. if config.ClientPlatform == "" {
  397. config.ClientPlatform = testClientPlatform
  398. }
  399. if runConfig.clientIsLatestVersion {
  400. config.ClientVersion = "999999999"
  401. }
  402. if runConfig.disableEstablishing {
  403. // Clear remote server list so tunnel cannot be established.
  404. // TODO: also delete all server entries in the datastore.
  405. config.DisableRemoteServerListFetcher = true
  406. }
  407. if runConfig.disableApi {
  408. config.DisableApi = true
  409. }
  410. config.TunnelPoolSize = runConfig.tunnelPoolSize
  411. if runConfig.useUpstreamProxy && runConfig.disruptNetwork {
  412. t.Fatalf("cannot use multiple upstream proxies")
  413. }
  414. if runConfig.disruptNetwork {
  415. config.UpstreamProxyURL = disruptorProxyURL
  416. } else if runConfig.useUpstreamProxy {
  417. config.UpstreamProxyURL = upstreamProxyURL
  418. config.CustomHeaders = upstreamProxyCustomHeaders
  419. }
  420. // All config fields should be set before calling Commit.
  421. err = config.Commit(false)
  422. if err != nil {
  423. t.Fatalf("error committing configuration file: %s", err)
  424. }
  425. err = OpenDataStore(config)
  426. if err != nil {
  427. t.Fatalf("error initializing datastore: %s", err)
  428. }
  429. defer CloseDataStore()
  430. serverEntryCount := CountServerEntries()
  431. if runConfig.expectNoServerEntries && serverEntryCount > 0 {
  432. // TODO: replace expectNoServerEntries with resetServerEntries
  433. // so tests can run in arbitrary order
  434. t.Fatalf("unexpected server entries")
  435. }
  436. controller, err := NewController(config)
  437. if err != nil {
  438. t.Fatalf("error creating controller: %s", err)
  439. }
  440. // Monitor notices for "Tunnels" with count > 1, the
  441. // indication of tunnel establishment success.
  442. // Also record the selected HTTP proxy port to use
  443. // when fetching websites through the tunnel.
  444. httpProxyPort := 0
  445. tunnelEstablished := make(chan struct{}, 1)
  446. upgradeDownloaded := make(chan struct{}, 1)
  447. remoteServerListDownloaded := make(chan struct{}, 1)
  448. confirmedLatestVersion := make(chan struct{}, 1)
  449. candidateServers := make(chan struct{}, 1)
  450. availableEgressRegions := make(chan struct{}, 1)
  451. var clientUpgradeDownloadedBytesCount int32
  452. var remoteServerListDownloadedBytesCount int32
  453. SetNoticeWriter(NewNoticeReceiver(
  454. func(notice []byte) {
  455. // TODO: log notices without logging server IPs:
  456. //fmt.Fprintf(os.Stderr, "%s\n", string(notice))
  457. noticeType, payload, err := GetNotice(notice)
  458. if err != nil {
  459. return
  460. }
  461. switch noticeType {
  462. case "ListeningHttpProxyPort":
  463. httpProxyPort = int(payload["port"].(float64))
  464. case "ConnectingServer":
  465. serverProtocol := payload["protocol"].(string)
  466. if runConfig.protocol != "" && serverProtocol != runConfig.protocol {
  467. // TODO: wrong goroutine for t.FatalNow()
  468. t.Fatalf("wrong protocol selected: %s", serverProtocol)
  469. }
  470. case "Tunnels":
  471. count := int(payload["count"].(float64))
  472. if count > 0 {
  473. if runConfig.disableEstablishing {
  474. // TODO: wrong goroutine for t.FatalNow()
  475. t.Fatalf("tunnel established unexpectedly")
  476. } else {
  477. select {
  478. case tunnelEstablished <- struct{}{}:
  479. default:
  480. }
  481. }
  482. }
  483. case "ClientUpgradeDownloadedBytes":
  484. atomic.AddInt32(&clientUpgradeDownloadedBytesCount, 1)
  485. t.Logf("ClientUpgradeDownloadedBytes: %d", int(payload["bytes"].(float64)))
  486. case "ClientUpgradeDownloaded":
  487. select {
  488. case upgradeDownloaded <- struct{}{}:
  489. default:
  490. }
  491. case "ClientIsLatestVersion":
  492. select {
  493. case confirmedLatestVersion <- struct{}{}:
  494. default:
  495. }
  496. case "RemoteServerListResourceDownloadedBytes":
  497. url := payload["url"].(string)
  498. if url == config.RemoteServerListUrl {
  499. t.Logf("RemoteServerListResourceDownloadedBytes: %d", int(payload["bytes"].(float64)))
  500. atomic.AddInt32(&remoteServerListDownloadedBytesCount, 1)
  501. }
  502. case "RemoteServerListResourceDownloaded":
  503. url := payload["url"].(string)
  504. if url == config.RemoteServerListUrl {
  505. t.Logf("RemoteServerListResourceDownloaded")
  506. select {
  507. case remoteServerListDownloaded <- struct{}{}:
  508. default:
  509. }
  510. }
  511. case "CandidateServers":
  512. select {
  513. case candidateServers <- struct{}{}:
  514. default:
  515. }
  516. case "AvailableEgressRegions":
  517. select {
  518. case availableEgressRegions <- struct{}{}:
  519. default:
  520. }
  521. }
  522. }))
  523. // Run controller, which establishes tunnels
  524. ctx, cancelFunc := context.WithCancel(context.Background())
  525. controllerWaitGroup := new(sync.WaitGroup)
  526. controllerWaitGroup.Add(1)
  527. go func() {
  528. defer controllerWaitGroup.Done()
  529. controller.Run(ctx)
  530. }()
  531. defer func() {
  532. // Test: shutdown must complete within 20 seconds
  533. cancelFunc()
  534. shutdownTimeout := time.NewTimer(20 * time.Second)
  535. shutdownOk := make(chan struct{}, 1)
  536. go func() {
  537. controllerWaitGroup.Wait()
  538. shutdownOk <- struct{}{}
  539. }()
  540. select {
  541. case <-shutdownOk:
  542. case <-shutdownTimeout.C:
  543. t.Fatalf("controller shutdown timeout exceeded")
  544. }
  545. }()
  546. if !runConfig.disableEstablishing {
  547. // Test: tunnel must be established within 120 seconds
  548. establishTimeout := time.NewTimer(120 * time.Second)
  549. select {
  550. case <-tunnelEstablished:
  551. case <-establishTimeout.C:
  552. t.Fatalf("tunnel establish timeout exceeded")
  553. }
  554. // Test: asynchronous server entry scans must complete
  555. select {
  556. case <-candidateServers:
  557. case <-establishTimeout.C:
  558. t.Fatalf("missing candidate servers notice")
  559. }
  560. select {
  561. case <-availableEgressRegions:
  562. case <-establishTimeout.C:
  563. t.Fatalf("missing available egress regions notice")
  564. }
  565. // Test: if starting with no server entries, a fetch remote
  566. // server list must have succeeded. With disruptNetwork, the
  567. // fetch must have been resumed at least once.
  568. if serverEntryCount == 0 {
  569. select {
  570. case <-remoteServerListDownloaded:
  571. default:
  572. t.Fatalf("expected remote server list downloaded")
  573. }
  574. if runConfig.disruptNetwork {
  575. count := atomic.LoadInt32(&remoteServerListDownloadedBytesCount)
  576. if count <= 1 {
  577. t.Fatalf("unexpected remote server list download progress: %d", count)
  578. }
  579. }
  580. }
  581. // Cannot establish port forwards in DisableApi mode
  582. if !runConfig.disableApi {
  583. // Test: fetch website through tunnel
  584. // Allow for known race condition described in NewHttpProxy():
  585. time.Sleep(1 * time.Second)
  586. if !runConfig.disruptNetwork {
  587. fetchAndVerifyWebsite(t, httpProxyPort)
  588. }
  589. }
  590. }
  591. // Test: upgrade check/download must be downloaded within 240 seconds
  592. expectUpgrade := !runConfig.disableApi && !runConfig.disableUntunneledUpgrade
  593. if expectUpgrade {
  594. upgradeTimeout := time.NewTimer(240 * time.Second)
  595. select {
  596. case <-upgradeDownloaded:
  597. // TODO: verify downloaded file
  598. if runConfig.clientIsLatestVersion {
  599. t.Fatalf("upgrade downloaded unexpectedly")
  600. }
  601. // Test: with disruptNetwork, must be multiple download progress notices
  602. if runConfig.disruptNetwork {
  603. count := atomic.LoadInt32(&clientUpgradeDownloadedBytesCount)
  604. if count <= 1 {
  605. t.Fatalf("unexpected upgrade download progress: %d", count)
  606. }
  607. }
  608. case <-confirmedLatestVersion:
  609. if !runConfig.clientIsLatestVersion {
  610. t.Fatalf("confirmed latest version unexpectedly")
  611. }
  612. case <-upgradeTimeout.C:
  613. t.Fatalf("upgrade download timeout exceeded")
  614. }
  615. }
  616. }
  617. func fetchAndVerifyWebsite(t *testing.T, httpProxyPort int) error {
  618. testUrl := "https://psiphon.ca"
  619. roundTripTimeout := 30 * time.Second
  620. expectedResponseContains := "Psiphon"
  621. checkResponse := func(responseBody string) bool {
  622. return strings.Contains(responseBody, expectedResponseContains)
  623. }
  624. // Retries are made to compensate for intermittent failures due
  625. // to external network conditions.
  626. fetchWithRetries := func(fetchName string, fetchFunc func() error) error {
  627. retryCount := 6
  628. retryDelay := 5 * time.Second
  629. var err error
  630. for i := 0; i < retryCount; i++ {
  631. err = fetchFunc()
  632. if err == nil || i == retryCount-1 {
  633. break
  634. }
  635. time.Sleep(retryDelay)
  636. t.Logf("retrying %s...", fetchName)
  637. }
  638. return err
  639. }
  640. // Test: use HTTP proxy
  641. fetchUsingHTTPProxy := func() error {
  642. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", httpProxyPort))
  643. if err != nil {
  644. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  645. }
  646. httpTransport := &http.Transport{
  647. Proxy: http.ProxyURL(proxyUrl),
  648. DisableKeepAlives: true,
  649. }
  650. httpClient := &http.Client{
  651. Transport: httpTransport,
  652. Timeout: roundTripTimeout,
  653. }
  654. request, err := http.NewRequest("GET", testUrl, nil)
  655. if err != nil {
  656. return fmt.Errorf("error preparing proxied HTTP request: %s", err)
  657. }
  658. response, err := httpClient.Do(request)
  659. if err != nil {
  660. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  661. }
  662. defer response.Body.Close()
  663. body, err := ioutil.ReadAll(response.Body)
  664. if err != nil {
  665. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  666. }
  667. if !checkResponse(string(body)) {
  668. return fmt.Errorf("unexpected proxied HTTP response")
  669. }
  670. return nil
  671. }
  672. err := fetchWithRetries("proxied HTTP request", fetchUsingHTTPProxy)
  673. if err != nil {
  674. return err
  675. }
  676. // Delay before requesting from external service again
  677. time.Sleep(1 * time.Second)
  678. // Test: use direct URL proxy
  679. fetchUsingURLProxyDirect := func() error {
  680. httpTransport := &http.Transport{
  681. DisableKeepAlives: true,
  682. }
  683. httpClient := &http.Client{
  684. Transport: httpTransport,
  685. Timeout: roundTripTimeout,
  686. }
  687. request, err := http.NewRequest(
  688. "GET",
  689. fmt.Sprintf("http://127.0.0.1:%d/direct/%s",
  690. httpProxyPort, url.QueryEscape(testUrl)),
  691. nil)
  692. if err != nil {
  693. return fmt.Errorf("error preparing direct URL request: %s", err)
  694. }
  695. response, err := httpClient.Do(request)
  696. if err != nil {
  697. return fmt.Errorf("error sending direct URL request: %s", err)
  698. }
  699. defer response.Body.Close()
  700. body, err := ioutil.ReadAll(response.Body)
  701. if err != nil {
  702. return fmt.Errorf("error reading direct URL response: %s", err)
  703. }
  704. if !checkResponse(string(body)) {
  705. return fmt.Errorf("unexpected direct URL response")
  706. }
  707. return nil
  708. }
  709. err = fetchWithRetries("direct URL request", fetchUsingURLProxyDirect)
  710. if err != nil {
  711. return err
  712. }
  713. // Delay before requesting from external service again
  714. time.Sleep(1 * time.Second)
  715. // Test: use tunneled URL proxy
  716. fetchUsingURLProxyTunneled := func() error {
  717. httpTransport := &http.Transport{
  718. DisableKeepAlives: true,
  719. }
  720. httpClient := &http.Client{
  721. Transport: httpTransport,
  722. Timeout: roundTripTimeout,
  723. }
  724. request, err := http.NewRequest(
  725. "GET",
  726. fmt.Sprintf("http://127.0.0.1:%d/tunneled/%s",
  727. httpProxyPort, url.QueryEscape(testUrl)),
  728. nil)
  729. if err != nil {
  730. return fmt.Errorf("error preparing tunneled URL request: %s", err)
  731. }
  732. response, err := httpClient.Do(request)
  733. if err != nil {
  734. return fmt.Errorf("error sending tunneled URL request: %s", err)
  735. }
  736. defer response.Body.Close()
  737. body, err := ioutil.ReadAll(response.Body)
  738. if err != nil {
  739. return fmt.Errorf("error reading tunneled URL response: %s", err)
  740. }
  741. if !checkResponse(string(body)) {
  742. return fmt.Errorf("unexpected tunneled URL response")
  743. }
  744. return nil
  745. }
  746. err = fetchWithRetries("tunneled URL request", fetchUsingURLProxyTunneled)
  747. if err != nil {
  748. return err
  749. }
  750. return nil
  751. }
  752. // Note: Valid values for disruptorMaxConnectionBytes depend on the production
  753. // network; for example, the size of the remote server list resource must exceed
  754. // disruptorMaxConnectionBytes or else TestUntunneledResumableFetchRemoteServerList
  755. // will fail since no retries are required. But if disruptorMaxConnectionBytes is
  756. // too small, the test will take longer to run since more retries are necessary.
  757. //
  758. // Tests such as TestUntunneledResumableFetchRemoteServerList could be rewritten to
  759. // use mock components (for example, see TestObfuscatedRemoteServerLists); however
  760. // these test in controller_test serve the dual purpose of ensuring that tunnel
  761. // core works with the production network.
  762. //
  763. // TODO: set disruptorMaxConnectionBytes (and disruptorMaxConnectionTime) dynamically,
  764. // based on current production network configuration?
  765. const disruptorProxyAddress = "127.0.0.1:2160"
  766. const disruptorProxyURL = "socks4a://" + disruptorProxyAddress
  767. const disruptorMaxConnectionBytes = 150000
  768. const disruptorMaxConnectionTime = 10 * time.Second
  769. func initDisruptor() {
  770. go func() {
  771. listener, err := socks.ListenSocks("tcp", disruptorProxyAddress)
  772. if err != nil {
  773. fmt.Printf("disruptor proxy listen error: %s\n", err)
  774. return
  775. }
  776. for {
  777. localConn, err := listener.AcceptSocks()
  778. if err != nil {
  779. if e, ok := err.(net.Error); ok && e.Temporary() {
  780. fmt.Printf("disruptor proxy temporary accept error: %s\n", err)
  781. continue
  782. }
  783. fmt.Printf("disruptor proxy accept error: %s\n", err)
  784. return
  785. }
  786. go func() {
  787. defer localConn.Close()
  788. remoteConn, err := net.Dial("tcp", localConn.Req.Target)
  789. if err != nil {
  790. // TODO: log "err" without logging server IPs
  791. fmt.Printf("disruptor proxy dial error\n")
  792. return
  793. }
  794. defer remoteConn.Close()
  795. err = localConn.Grant(&net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 0})
  796. if err != nil {
  797. fmt.Printf("disruptor proxy grant error: %s\n", err)
  798. return
  799. }
  800. // Cut connection after disruptorMaxConnectionTime
  801. time.AfterFunc(disruptorMaxConnectionTime, func() {
  802. localConn.Close()
  803. remoteConn.Close()
  804. })
  805. // Relay connection, but only up to disruptorMaxConnectionBytes
  806. waitGroup := new(sync.WaitGroup)
  807. waitGroup.Add(1)
  808. go func() {
  809. defer waitGroup.Done()
  810. io.CopyN(localConn, remoteConn, disruptorMaxConnectionBytes)
  811. localConn.Close()
  812. remoteConn.Close()
  813. }()
  814. io.CopyN(remoteConn, localConn, disruptorMaxConnectionBytes)
  815. localConn.Close()
  816. remoteConn.Close()
  817. waitGroup.Wait()
  818. }()
  819. }
  820. }()
  821. }
  822. const upstreamProxyURL = "http://testUser:testPassword@127.0.0.1:2161"
  823. var upstreamProxyCustomHeaders = map[string][]string{"X-Test-Header-Name": {"test-header-value1", "test-header-value2"}}
  824. func hasExpectedCustomHeaders(h http.Header) bool {
  825. for name, values := range upstreamProxyCustomHeaders {
  826. if h[name] == nil {
  827. return false
  828. }
  829. // Order may not be the same
  830. for _, value := range values {
  831. if !common.Contains(h[name], value) {
  832. return false
  833. }
  834. }
  835. }
  836. return true
  837. }
  838. func initUpstreamProxy() {
  839. go func() {
  840. proxy := goproxy.NewProxyHttpServer()
  841. proxy.Logger = log.New(ioutil.Discard, "", 0)
  842. auth.ProxyBasic(
  843. proxy,
  844. "testRealm",
  845. func(user, passwd string) bool { return user == "testUser" && passwd == "testPassword" })
  846. proxy.OnRequest().DoFunc(
  847. func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
  848. if !hasExpectedCustomHeaders(r.Header) {
  849. fmt.Printf("missing expected headers: %+v\n", ctx.Req.Header)
  850. return nil, goproxy.NewResponse(r, goproxy.ContentTypeText, http.StatusUnauthorized, "")
  851. }
  852. return r, nil
  853. })
  854. proxy.OnRequest().HandleConnectFunc(
  855. func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
  856. if !hasExpectedCustomHeaders(ctx.Req.Header) {
  857. fmt.Printf("missing expected headers: %+v\n", ctx.Req.Header)
  858. return goproxy.RejectConnect, host
  859. }
  860. return goproxy.OkConnect, host
  861. })
  862. err := http.ListenAndServe("127.0.0.1:2161", proxy)
  863. if err != nil {
  864. fmt.Printf("upstream proxy failed: %s\n", err)
  865. }
  866. }()
  867. // TODO: wait until listener is active?
  868. }