controller_test.go 27 KB

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