clientlib_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. /*
  2. * Copyright (c) 2018, 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 clientlib
  20. import (
  21. "context"
  22. "encoding/json"
  23. "os"
  24. "testing"
  25. "time"
  26. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  28. )
  29. func TestStartTunnel(t *testing.T) {
  30. // TODO: More comprehensive tests. This is only a smoke test.
  31. clientPlatform := "clientlib_test.go"
  32. networkID := "UNKNOWN"
  33. timeout := 60
  34. quickTimeout := 1
  35. trueVal := true
  36. configJSON, err := os.ReadFile("../../psiphon/controller_test.config")
  37. if err != nil {
  38. // Skip, don't fail, if config file is not present
  39. t.Skipf("error loading configuration file: %s", err)
  40. }
  41. // Initialize a fresh datastore and create a modified config which cannot
  42. // connect without known servers, to be used in timeout cases.
  43. testDataDirName, err := os.MkdirTemp("", "psiphon-clientlib-test")
  44. if err != nil {
  45. t.Fatalf("ioutil.TempDir failed: %v", err)
  46. }
  47. defer os.RemoveAll(testDataDirName)
  48. var config map[string]interface{}
  49. err = json.Unmarshal(configJSON, &config)
  50. if err != nil {
  51. t.Fatalf("json.Unmarshal failed: %v", err)
  52. }
  53. // Use the legacy encoding to both exercise that case, and facilitate a
  54. // gradual network upgrade to new encoding support.
  55. config["TargetAPIEncoding"] = protocol.PSIPHON_API_ENCODING_JSON
  56. configJSON, err = json.Marshal(config)
  57. if err != nil {
  58. t.Fatalf("json.Marshal failed: %v", err)
  59. }
  60. config["DisableRemoteServerListFetcher"] = true
  61. configJSONNoFetcher, err := json.Marshal(config)
  62. if err != nil {
  63. t.Fatalf("json.Marshal failed: %v", err)
  64. }
  65. type args struct {
  66. ctxTimeout time.Duration
  67. configJSON []byte
  68. embeddedServerEntryList string
  69. params Parameters
  70. paramsDelta ParametersDelta
  71. noticeReceiver func(NoticeEvent)
  72. }
  73. tests := []struct {
  74. name string
  75. args args
  76. wantTunnel bool
  77. expectedErr error
  78. }{
  79. {
  80. name: "Failure: context timeout",
  81. args: args{
  82. ctxTimeout: 10 * time.Millisecond,
  83. configJSON: configJSONNoFetcher,
  84. embeddedServerEntryList: "",
  85. params: Parameters{
  86. DataRootDirectory: &testDataDirName,
  87. ClientPlatform: &clientPlatform,
  88. NetworkID: &networkID,
  89. EstablishTunnelTimeoutSeconds: &timeout,
  90. },
  91. paramsDelta: nil,
  92. noticeReceiver: nil,
  93. },
  94. wantTunnel: false,
  95. expectedErr: ErrTimeout,
  96. },
  97. {
  98. name: "Failure: config timeout",
  99. args: args{
  100. ctxTimeout: 0,
  101. configJSON: configJSONNoFetcher,
  102. embeddedServerEntryList: "",
  103. params: Parameters{
  104. DataRootDirectory: &testDataDirName,
  105. ClientPlatform: &clientPlatform,
  106. NetworkID: &networkID,
  107. EstablishTunnelTimeoutSeconds: &quickTimeout,
  108. },
  109. paramsDelta: nil,
  110. noticeReceiver: nil,
  111. },
  112. wantTunnel: false,
  113. expectedErr: ErrTimeout,
  114. },
  115. {
  116. name: "Success: simple",
  117. args: args{
  118. ctxTimeout: 0,
  119. configJSON: configJSON,
  120. embeddedServerEntryList: "",
  121. params: Parameters{
  122. DataRootDirectory: &testDataDirName,
  123. ClientPlatform: &clientPlatform,
  124. NetworkID: &networkID,
  125. EstablishTunnelTimeoutSeconds: &timeout,
  126. },
  127. paramsDelta: nil,
  128. noticeReceiver: nil,
  129. },
  130. wantTunnel: true,
  131. expectedErr: nil,
  132. },
  133. {
  134. name: "Success: disable SOCKS proxy",
  135. args: args{
  136. ctxTimeout: 0,
  137. configJSON: configJSON,
  138. embeddedServerEntryList: "",
  139. params: Parameters{
  140. DataRootDirectory: &testDataDirName,
  141. ClientPlatform: &clientPlatform,
  142. NetworkID: &networkID,
  143. EstablishTunnelTimeoutSeconds: &timeout,
  144. DisableLocalSocksProxy: &trueVal,
  145. },
  146. paramsDelta: nil,
  147. noticeReceiver: nil,
  148. },
  149. wantTunnel: true,
  150. expectedErr: nil,
  151. },
  152. {
  153. name: "Success: disable HTTP proxy",
  154. args: args{
  155. ctxTimeout: 0,
  156. configJSON: configJSON,
  157. embeddedServerEntryList: "",
  158. params: Parameters{
  159. DataRootDirectory: &testDataDirName,
  160. ClientPlatform: &clientPlatform,
  161. NetworkID: &networkID,
  162. EstablishTunnelTimeoutSeconds: &timeout,
  163. DisableLocalHTTPProxy: &trueVal,
  164. },
  165. paramsDelta: nil,
  166. noticeReceiver: nil,
  167. },
  168. wantTunnel: true,
  169. expectedErr: nil,
  170. },
  171. {
  172. name: "Success: disable SOCKS and HTTP proxies",
  173. args: args{
  174. ctxTimeout: 0,
  175. configJSON: configJSON,
  176. embeddedServerEntryList: "",
  177. params: Parameters{
  178. DataRootDirectory: &testDataDirName,
  179. ClientPlatform: &clientPlatform,
  180. NetworkID: &networkID,
  181. EstablishTunnelTimeoutSeconds: &timeout,
  182. DisableLocalSocksProxy: &trueVal,
  183. DisableLocalHTTPProxy: &trueVal,
  184. },
  185. paramsDelta: nil,
  186. noticeReceiver: nil,
  187. },
  188. wantTunnel: true,
  189. expectedErr: nil,
  190. },
  191. }
  192. for _, tt := range tests {
  193. t.Run(tt.name, func(t *testing.T) {
  194. ctx := context.Background()
  195. var cancelFunc context.CancelFunc
  196. if tt.args.ctxTimeout > 0 {
  197. ctx, cancelFunc = context.WithTimeout(ctx, tt.args.ctxTimeout)
  198. }
  199. tunnel, err := StartTunnel(
  200. ctx,
  201. tt.args.configJSON,
  202. tt.args.embeddedServerEntryList,
  203. tt.args.params,
  204. tt.args.paramsDelta,
  205. tt.args.noticeReceiver)
  206. gotTunnel := (tunnel != nil)
  207. if cancelFunc != nil {
  208. cancelFunc()
  209. }
  210. if tunnel != nil {
  211. tunnel.Stop()
  212. }
  213. if gotTunnel != tt.wantTunnel {
  214. t.Errorf("StartTunnel() gotTunnel = %v, wantTunnel %v", err, tt.wantTunnel)
  215. }
  216. if err != tt.expectedErr {
  217. t.Fatalf("StartTunnel() error = %v, expectedErr %v", err, tt.expectedErr)
  218. return
  219. }
  220. if tunnel == nil {
  221. return
  222. }
  223. if tt.args.params.DisableLocalSocksProxy != nil && *tt.args.params.DisableLocalSocksProxy {
  224. if tunnel.SOCKSProxyPort != 0 {
  225. t.Fatalf("should not have started SOCKS proxy")
  226. }
  227. } else {
  228. if tunnel.SOCKSProxyPort == 0 {
  229. t.Fatalf("failed to start SOCKS proxy")
  230. }
  231. }
  232. if tt.args.params.DisableLocalHTTPProxy != nil && *tt.args.params.DisableLocalHTTPProxy {
  233. if tunnel.HTTPProxyPort != 0 {
  234. t.Fatalf("should not have started HTTP proxy")
  235. }
  236. } else {
  237. if tunnel.HTTPProxyPort == 0 {
  238. t.Fatalf("failed to start HTTP proxy")
  239. }
  240. }
  241. })
  242. }
  243. }
  244. func TestMultipleStartTunnel(t *testing.T) {
  245. configJSON, err := os.ReadFile("../../psiphon/controller_test.config")
  246. if err != nil {
  247. // What to do if config file is not present?
  248. t.Skipf("error loading configuration file: %s", err)
  249. }
  250. var config map[string]interface{}
  251. err = json.Unmarshal(configJSON, &config)
  252. if err != nil {
  253. t.Fatalf("json.Unmarshal failed: %v", err)
  254. }
  255. // Use the legacy encoding to both exercise that case, and facilitate a
  256. // gradual network upgrade to new encoding support.
  257. config["TargetAPIEncoding"] = protocol.PSIPHON_API_ENCODING_JSON
  258. configJSON, err = json.Marshal(config)
  259. if err != nil {
  260. t.Fatalf("json.Marshal failed: %v", err)
  261. }
  262. testDataDirName, err := os.MkdirTemp("", "psiphon-clientlib-test")
  263. if err != nil {
  264. t.Fatalf("ioutil.TempDir failed: %v", err)
  265. }
  266. defer os.RemoveAll(testDataDirName)
  267. ctx := context.Background()
  268. tunnel1, err := StartTunnel(
  269. ctx,
  270. configJSON,
  271. "",
  272. Parameters{DataRootDirectory: &testDataDirName},
  273. nil,
  274. nil)
  275. if err != nil {
  276. t.Fatalf("first StartTunnel() error = %v", err)
  277. }
  278. // We have not stopped the tunnel, so a second StartTunnel() should fail
  279. _, err = StartTunnel(
  280. ctx,
  281. configJSON,
  282. "",
  283. Parameters{DataRootDirectory: &testDataDirName},
  284. nil,
  285. nil)
  286. if err != errMultipleStart {
  287. t.Fatalf("second StartTunnel() should have failed with errMultipleStart; got %v", err)
  288. }
  289. // Stop the tunnel and try again
  290. tunnel1.Stop()
  291. tunnel3, err := StartTunnel(
  292. ctx,
  293. configJSON,
  294. "",
  295. Parameters{DataRootDirectory: &testDataDirName},
  296. nil,
  297. nil)
  298. if err != nil {
  299. t.Fatalf("third StartTunnel() error = %v", err)
  300. }
  301. // Stop the tunnel so it doesn't interfere with other tests
  302. tunnel3.Stop()
  303. }
  304. func TestPsiphonTunnel_Dial(t *testing.T) {
  305. trueVal := true
  306. configJSON, err := os.ReadFile("../../psiphon/controller_test.config")
  307. if err != nil {
  308. // Skip, don't fail, if config file is not present
  309. t.Skipf("error loading configuration file: %s", err)
  310. }
  311. var config map[string]interface{}
  312. err = json.Unmarshal(configJSON, &config)
  313. if err != nil {
  314. t.Fatalf("json.Unmarshal failed: %v", err)
  315. }
  316. // Use the legacy encoding to both exercise that case, and facilitate a
  317. // gradual network upgrade to new encoding support.
  318. config["TargetAPIEncoding"] = protocol.PSIPHON_API_ENCODING_JSON
  319. configJSON, err = json.Marshal(config)
  320. if err != nil {
  321. t.Fatalf("json.Marshal failed: %v", err)
  322. }
  323. testDataDirName, err := os.MkdirTemp("", "psiphon-clientlib-test")
  324. if err != nil {
  325. t.Fatalf("ioutil.TempDir failed: %v", err)
  326. }
  327. defer os.RemoveAll(testDataDirName)
  328. type args struct {
  329. remoteAddr string
  330. }
  331. tests := []struct {
  332. name string
  333. args args
  334. wantErr bool
  335. }{
  336. {
  337. name: "Success: example.com",
  338. args: args{remoteAddr: "example.com:443"},
  339. wantErr: false,
  340. },
  341. {
  342. name: "Failure: invalid address",
  343. args: args{remoteAddr: "example.com:99999"},
  344. wantErr: true,
  345. },
  346. }
  347. for _, tt := range tests {
  348. t.Run(tt.name, func(t *testing.T) {
  349. tunnel, err := StartTunnel(
  350. context.Background(),
  351. configJSON,
  352. "",
  353. Parameters{
  354. DataRootDirectory: &testDataDirName,
  355. // Don't need local proxies for dial tests
  356. // (and this is likely the configuration that will be used by consumers of the library who utilitize Dial).
  357. DisableLocalSocksProxy: &trueVal,
  358. DisableLocalHTTPProxy: &trueVal,
  359. },
  360. nil,
  361. nil)
  362. if err != nil {
  363. t.Fatalf("StartTunnel() error = %v", err)
  364. }
  365. defer tunnel.Stop()
  366. conn, err := tunnel.Dial(tt.args.remoteAddr)
  367. if (err != nil) != tt.wantErr {
  368. t.Fatalf("PsiphonTunnel.Dial() error = %v, wantErr %v", err, tt.wantErr)
  369. return
  370. }
  371. if tt.wantErr != (conn == nil) {
  372. t.Fatalf("PsiphonTunnel.Dial() conn = %v, wantConn %v", conn, !tt.wantErr)
  373. }
  374. })
  375. }
  376. }
  377. // We had a problem where config-related notices were being printed to stderr before we
  378. // set the NoticeWriter. We want to make sure that no longer happens.
  379. func TestStartTunnelNoOutput(t *testing.T) {
  380. configJSON, err := os.ReadFile("../../psiphon/controller_test.config")
  381. if err != nil {
  382. // What to do if config file is not present?
  383. t.Skipf("error loading configuration file: %s", err)
  384. }
  385. var config map[string]interface{}
  386. err = json.Unmarshal(configJSON, &config)
  387. if err != nil {
  388. t.Fatalf("json.Unmarshal failed: %v", err)
  389. }
  390. // Before starting the tunnel, set up a notice receiver. If it receives anything at
  391. // all, that means that it would have been printed to stderr.
  392. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  393. func(notice []byte) {
  394. t.Fatalf("Received notice: %v", string(notice))
  395. }))
  396. // Use the legacy encoding to both exercise that case, and facilitate a
  397. // gradual network upgrade to new encoding support.
  398. config["TargetAPIEncoding"] = protocol.PSIPHON_API_ENCODING_JSON
  399. configJSON, err = json.Marshal(config)
  400. if err != nil {
  401. t.Fatalf("json.Marshal failed: %v", err)
  402. }
  403. testDataDirName, err := os.MkdirTemp("", "psiphon-clientlib-test")
  404. if err != nil {
  405. t.Fatalf("ioutil.TempDir failed: %v", err)
  406. }
  407. defer os.RemoveAll(testDataDirName)
  408. ctx := context.Background()
  409. tunnel, err := StartTunnel(
  410. ctx,
  411. configJSON,
  412. "",
  413. Parameters{DataRootDirectory: &testDataDirName},
  414. nil,
  415. nil)
  416. if err != nil {
  417. t.Fatalf("StartTunnel() error = %v", err)
  418. }
  419. tunnel.Stop()
  420. }
  421. // We had a problem where a very early error could result in `started` being set to true
  422. // and not be set back to false, preventing StartTunnel from being re-callable.
  423. func TestStartTunnelReentry(t *testing.T) {
  424. testDataDirName, err := os.MkdirTemp("", "psiphon-clientlib-test")
  425. if err != nil {
  426. t.Fatalf("ioutil.TempDir failed: %v", err)
  427. }
  428. defer os.RemoveAll(testDataDirName)
  429. configJSON := []byte("BAD CONFIG JSON")
  430. ctx := context.Background()
  431. _, err = StartTunnel(
  432. ctx,
  433. configJSON,
  434. "",
  435. Parameters{DataRootDirectory: &testDataDirName},
  436. nil,
  437. nil)
  438. if err == nil {
  439. t.Fatalf("expected config error")
  440. }
  441. // Call again with a good config. Should work.
  442. configJSON, err = os.ReadFile("../../psiphon/controller_test.config")
  443. if err != nil {
  444. // What to do if config file is not present?
  445. t.Skipf("error loading configuration file: %s", err)
  446. }
  447. var config map[string]interface{}
  448. err = json.Unmarshal(configJSON, &config)
  449. if err != nil {
  450. t.Fatalf("json.Unmarshal failed: %v", err)
  451. }
  452. // Use the legacy encoding to both exercise that case, and facilitate a
  453. // gradual network upgrade to new encoding support.
  454. config["TargetAPIEncoding"] = protocol.PSIPHON_API_ENCODING_JSON
  455. configJSON, err = json.Marshal(config)
  456. if err != nil {
  457. t.Fatalf("json.Marshal failed: %v", err)
  458. }
  459. tunnel, err := StartTunnel(
  460. ctx,
  461. configJSON,
  462. "",
  463. Parameters{DataRootDirectory: &testDataDirName},
  464. nil,
  465. nil)
  466. if err != nil {
  467. t.Fatalf("StartTunnel() error = %v", err)
  468. }
  469. tunnel.Stop()
  470. }