controller_test.go 26 KB

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