api_test.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. // Copyright (C) 2016 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package api
  7. import (
  8. "bytes"
  9. "compress/gzip"
  10. "encoding/json"
  11. "fmt"
  12. "io"
  13. "io/ioutil"
  14. "net"
  15. "net/http"
  16. "net/http/httptest"
  17. "os"
  18. "path/filepath"
  19. "strconv"
  20. "strings"
  21. "testing"
  22. "time"
  23. "github.com/d4l3k/messagediff"
  24. "github.com/syncthing/syncthing/lib/config"
  25. "github.com/syncthing/syncthing/lib/events"
  26. "github.com/syncthing/syncthing/lib/fs"
  27. "github.com/syncthing/syncthing/lib/locations"
  28. "github.com/syncthing/syncthing/lib/model"
  29. "github.com/syncthing/syncthing/lib/protocol"
  30. "github.com/syncthing/syncthing/lib/sync"
  31. "github.com/syncthing/syncthing/lib/ur"
  32. "github.com/thejerf/suture"
  33. )
  34. func TestMain(m *testing.M) {
  35. orig := locations.GetBaseDir(locations.ConfigBaseDir)
  36. locations.SetBaseDir(locations.ConfigBaseDir, "testdata/config")
  37. exitCode := m.Run()
  38. locations.SetBaseDir(locations.ConfigBaseDir, orig)
  39. os.Exit(exitCode)
  40. }
  41. func TestCSRFToken(t *testing.T) {
  42. t1 := newCsrfToken()
  43. t2 := newCsrfToken()
  44. t3 := newCsrfToken()
  45. if !validCsrfToken(t3) {
  46. t.Fatal("t3 should be valid")
  47. }
  48. for i := 0; i < 250; i++ {
  49. if i%5 == 0 {
  50. // t1 and t2 should remain valid by virtue of us checking them now
  51. // and then.
  52. if !validCsrfToken(t1) {
  53. t.Fatal("t1 should be valid at iteration", i)
  54. }
  55. if !validCsrfToken(t2) {
  56. t.Fatal("t2 should be valid at iteration", i)
  57. }
  58. }
  59. // The newly generated token is always valid
  60. t4 := newCsrfToken()
  61. if !validCsrfToken(t4) {
  62. t.Fatal("t4 should be valid at iteration", i)
  63. }
  64. }
  65. if validCsrfToken(t3) {
  66. t.Fatal("t3 should have expired by now")
  67. }
  68. }
  69. func TestStopAfterBrokenConfig(t *testing.T) {
  70. cfg := config.Configuration{
  71. GUI: config.GUIConfiguration{
  72. RawAddress: "127.0.0.1:0",
  73. RawUseTLS: false,
  74. },
  75. }
  76. w := config.Wrap("/dev/null", cfg)
  77. srv := New(protocol.LocalDeviceID, w, "", "syncthing", nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, false).(*service)
  78. srv.started = make(chan string)
  79. sup := suture.New("test", suture.Spec{
  80. PassThroughPanics: true,
  81. })
  82. sup.Add(srv)
  83. sup.ServeBackground()
  84. <-srv.started
  85. // Service is now running, listening on a random port on localhost. Now we
  86. // request a config change to a completely invalid listen address. The
  87. // commit will fail and the service will be in a broken state.
  88. newCfg := config.Configuration{
  89. GUI: config.GUIConfiguration{
  90. RawAddress: "totally not a valid address",
  91. RawUseTLS: false,
  92. },
  93. }
  94. if err := srv.VerifyConfiguration(cfg, newCfg); err == nil {
  95. t.Fatal("Verify config should have failed")
  96. }
  97. // Nonetheless, it should be fine to Stop() it without panic.
  98. sup.Stop()
  99. }
  100. func TestAssetsDir(t *testing.T) {
  101. // For any given request to $FILE, we should return the first found of
  102. // - assetsdir/$THEME/$FILE
  103. // - compiled in asset $THEME/$FILE
  104. // - assetsdir/default/$FILE
  105. // - compiled in asset default/$FILE
  106. // The asset map contains compressed assets, so create a couple of gzip compressed assets here.
  107. buf := new(bytes.Buffer)
  108. gw := gzip.NewWriter(buf)
  109. gw.Write([]byte("default"))
  110. gw.Close()
  111. def := buf.Bytes()
  112. buf = new(bytes.Buffer)
  113. gw = gzip.NewWriter(buf)
  114. gw.Write([]byte("foo"))
  115. gw.Close()
  116. foo := buf.Bytes()
  117. e := &staticsServer{
  118. theme: "foo",
  119. mut: sync.NewRWMutex(),
  120. assetDir: "testdata",
  121. assets: map[string][]byte{
  122. "foo/a": foo, // overridden in foo/a
  123. "foo/b": foo,
  124. "default/a": def, // overridden in default/a (but foo/a takes precedence)
  125. "default/b": def, // overridden in default/b (but foo/b takes precedence)
  126. "default/c": def,
  127. },
  128. }
  129. s := httptest.NewServer(e)
  130. defer s.Close()
  131. // assetsdir/foo/a exists, overrides compiled in
  132. expectURLToContain(t, s.URL+"/a", "overridden-foo")
  133. // foo/b is compiled in, default/b is overridden, return compiled in
  134. expectURLToContain(t, s.URL+"/b", "foo")
  135. // only exists as compiled in default/c so use that
  136. expectURLToContain(t, s.URL+"/c", "default")
  137. // only exists as overridden default/d so use that
  138. expectURLToContain(t, s.URL+"/d", "overridden-default")
  139. }
  140. func expectURLToContain(t *testing.T, url, exp string) {
  141. res, err := http.Get(url)
  142. if err != nil {
  143. t.Error(err)
  144. return
  145. }
  146. if res.StatusCode != 200 {
  147. t.Errorf("Got %s instead of 200 OK", res.Status)
  148. return
  149. }
  150. data, err := ioutil.ReadAll(res.Body)
  151. res.Body.Close()
  152. if err != nil {
  153. t.Error(err)
  154. return
  155. }
  156. if string(data) != exp {
  157. t.Errorf("Got %q instead of %q on %q", data, exp, url)
  158. return
  159. }
  160. }
  161. func TestDirNames(t *testing.T) {
  162. names := dirNames("testdata")
  163. expected := []string{"config", "default", "foo", "testfolder"}
  164. if diff, equal := messagediff.PrettyDiff(expected, names); !equal {
  165. t.Errorf("Unexpected dirNames return: %#v\n%s", names, diff)
  166. }
  167. }
  168. type httpTestCase struct {
  169. URL string // URL to check
  170. Code int // Expected result code
  171. Type string // Expected content type
  172. Prefix string // Expected result prefix
  173. Timeout time.Duration // Defaults to a second
  174. }
  175. func TestAPIServiceRequests(t *testing.T) {
  176. const testAPIKey = "foobarbaz"
  177. cfg := new(mockedConfig)
  178. cfg.gui.APIKey = testAPIKey
  179. baseURL, err := startHTTP(cfg)
  180. if err != nil {
  181. t.Fatal(err)
  182. }
  183. cases := []httpTestCase{
  184. // /rest/db
  185. {
  186. URL: "/rest/db/completion?device=" + protocol.LocalDeviceID.String() + "&folder=default",
  187. Code: 200,
  188. Type: "application/json",
  189. Prefix: "{",
  190. },
  191. {
  192. URL: "/rest/db/file?folder=default&file=something",
  193. Code: 404,
  194. },
  195. {
  196. URL: "/rest/db/ignores?folder=default",
  197. Code: 200,
  198. Type: "application/json",
  199. Prefix: "{",
  200. },
  201. {
  202. URL: "/rest/db/need?folder=default",
  203. Code: 200,
  204. Type: "application/json",
  205. Prefix: "{",
  206. },
  207. {
  208. URL: "/rest/db/status?folder=default",
  209. Code: 200,
  210. Type: "application/json",
  211. Prefix: "{",
  212. },
  213. {
  214. URL: "/rest/db/browse?folder=default",
  215. Code: 200,
  216. Type: "application/json",
  217. Prefix: "null",
  218. },
  219. // /rest/stats
  220. {
  221. URL: "/rest/stats/device",
  222. Code: 200,
  223. Type: "application/json",
  224. Prefix: "null",
  225. },
  226. {
  227. URL: "/rest/stats/folder",
  228. Code: 200,
  229. Type: "application/json",
  230. Prefix: "null",
  231. },
  232. // /rest/svc
  233. {
  234. URL: "/rest/svc/deviceid?id=" + protocol.LocalDeviceID.String(),
  235. Code: 200,
  236. Type: "application/json",
  237. Prefix: "{",
  238. },
  239. {
  240. URL: "/rest/svc/lang",
  241. Code: 200,
  242. Type: "application/json",
  243. Prefix: "[",
  244. },
  245. {
  246. URL: "/rest/svc/report",
  247. Code: 200,
  248. Type: "application/json",
  249. Prefix: "{",
  250. Timeout: 5 * time.Second,
  251. },
  252. // /rest/system
  253. {
  254. URL: "/rest/system/browse?current=~",
  255. Code: 200,
  256. Type: "application/json",
  257. Prefix: "[",
  258. },
  259. {
  260. URL: "/rest/system/config",
  261. Code: 200,
  262. Type: "application/json",
  263. Prefix: "{",
  264. },
  265. {
  266. URL: "/rest/system/config/insync",
  267. Code: 200,
  268. Type: "application/json",
  269. Prefix: "{",
  270. },
  271. {
  272. URL: "/rest/system/connections",
  273. Code: 200,
  274. Type: "application/json",
  275. Prefix: "null",
  276. },
  277. {
  278. URL: "/rest/system/discovery",
  279. Code: 200,
  280. Type: "application/json",
  281. Prefix: "{",
  282. },
  283. {
  284. URL: "/rest/system/error?since=0",
  285. Code: 200,
  286. Type: "application/json",
  287. Prefix: "{",
  288. },
  289. {
  290. URL: "/rest/system/ping",
  291. Code: 200,
  292. Type: "application/json",
  293. Prefix: "{",
  294. },
  295. {
  296. URL: "/rest/system/status",
  297. Code: 200,
  298. Type: "application/json",
  299. Prefix: "{",
  300. },
  301. {
  302. URL: "/rest/system/version",
  303. Code: 200,
  304. Type: "application/json",
  305. Prefix: "{",
  306. },
  307. {
  308. URL: "/rest/system/debug",
  309. Code: 200,
  310. Type: "application/json",
  311. Prefix: "{",
  312. },
  313. {
  314. URL: "/rest/system/log?since=0",
  315. Code: 200,
  316. Type: "application/json",
  317. Prefix: "{",
  318. },
  319. {
  320. URL: "/rest/system/log.txt?since=0",
  321. Code: 200,
  322. Type: "text/plain",
  323. Prefix: "",
  324. },
  325. }
  326. for _, tc := range cases {
  327. t.Log("Testing", tc.URL, "...")
  328. testHTTPRequest(t, baseURL, tc, testAPIKey)
  329. }
  330. }
  331. // testHTTPRequest tries the given test case, comparing the result code,
  332. // content type, and result prefix.
  333. func testHTTPRequest(t *testing.T, baseURL string, tc httpTestCase, apikey string) {
  334. timeout := time.Second
  335. if tc.Timeout > 0 {
  336. timeout = tc.Timeout
  337. }
  338. cli := &http.Client{
  339. Timeout: timeout,
  340. }
  341. req, err := http.NewRequest("GET", baseURL+tc.URL, nil)
  342. if err != nil {
  343. t.Errorf("Unexpected error requesting %s: %v", tc.URL, err)
  344. return
  345. }
  346. req.Header.Set("X-API-Key", apikey)
  347. resp, err := cli.Do(req)
  348. if err != nil {
  349. t.Errorf("Unexpected error requesting %s: %v", tc.URL, err)
  350. return
  351. }
  352. defer resp.Body.Close()
  353. if resp.StatusCode != tc.Code {
  354. t.Errorf("Get on %s should have returned status code %d, not %s", tc.URL, tc.Code, resp.Status)
  355. return
  356. }
  357. ct := resp.Header.Get("Content-Type")
  358. if !strings.HasPrefix(ct, tc.Type) {
  359. t.Errorf("The content type on %s should be %q, not %q", tc.URL, tc.Type, ct)
  360. return
  361. }
  362. data, err := ioutil.ReadAll(resp.Body)
  363. if err != nil {
  364. t.Errorf("Unexpected error reading %s: %v", tc.URL, err)
  365. return
  366. }
  367. if !bytes.HasPrefix(data, []byte(tc.Prefix)) {
  368. t.Errorf("Returned data from %s does not have prefix %q: %s", tc.URL, tc.Prefix, data)
  369. return
  370. }
  371. }
  372. func TestHTTPLogin(t *testing.T) {
  373. cfg := new(mockedConfig)
  374. cfg.gui.User = "üser"
  375. cfg.gui.Password = "$2a$10$IdIZTxTg/dCNuNEGlmLynOjqg4B1FvDKuIV5e0BB3pnWVHNb8.GSq" // bcrypt of "räksmörgås" in UTF-8
  376. baseURL, err := startHTTP(cfg)
  377. if err != nil {
  378. t.Fatal(err)
  379. }
  380. // Verify rejection when not using authorization
  381. req, _ := http.NewRequest("GET", baseURL, nil)
  382. resp, err := http.DefaultClient.Do(req)
  383. if err != nil {
  384. t.Fatal(err)
  385. }
  386. if resp.StatusCode != http.StatusUnauthorized {
  387. t.Errorf("Unexpected non-401 return code %d for unauthed request", resp.StatusCode)
  388. }
  389. // Verify that incorrect password is rejected
  390. req.SetBasicAuth("üser", "rksmrgs")
  391. resp, err = http.DefaultClient.Do(req)
  392. if err != nil {
  393. t.Fatal(err)
  394. }
  395. if resp.StatusCode != http.StatusUnauthorized {
  396. t.Errorf("Unexpected non-401 return code %d for incorrect password", resp.StatusCode)
  397. }
  398. // Verify that incorrect username is rejected
  399. req.SetBasicAuth("user", "räksmörgås") // string literals in Go source code are in UTF-8
  400. resp, err = http.DefaultClient.Do(req)
  401. if err != nil {
  402. t.Fatal(err)
  403. }
  404. if resp.StatusCode != http.StatusUnauthorized {
  405. t.Errorf("Unexpected non-401 return code %d for incorrect username", resp.StatusCode)
  406. }
  407. // Verify that UTF-8 auth works
  408. req.SetBasicAuth("üser", "räksmörgås") // string literals in Go source code are in UTF-8
  409. resp, err = http.DefaultClient.Do(req)
  410. if err != nil {
  411. t.Fatal(err)
  412. }
  413. if resp.StatusCode != http.StatusOK {
  414. t.Errorf("Unexpected non-200 return code %d for authed request (UTF-8)", resp.StatusCode)
  415. }
  416. // Verify that ISO-8859-1 auth
  417. req.SetBasicAuth("\xfcser", "r\xe4ksm\xf6rg\xe5s") // escaped ISO-8859-1
  418. resp, err = http.DefaultClient.Do(req)
  419. if err != nil {
  420. t.Fatal(err)
  421. }
  422. if resp.StatusCode != http.StatusOK {
  423. t.Errorf("Unexpected non-200 return code %d for authed request (ISO-8859-1)", resp.StatusCode)
  424. }
  425. }
  426. func startHTTP(cfg *mockedConfig) (string, error) {
  427. m := new(mockedModel)
  428. assetDir := "../../gui"
  429. eventSub := new(mockedEventSub)
  430. diskEventSub := new(mockedEventSub)
  431. discoverer := new(mockedCachingMux)
  432. connections := new(mockedConnections)
  433. errorLog := new(mockedLoggerRecorder)
  434. systemLog := new(mockedLoggerRecorder)
  435. cpu := new(mockedCPUService)
  436. addrChan := make(chan string)
  437. // Instantiate the API service
  438. urService := ur.New(cfg, m, connections, false)
  439. summaryService := model.NewFolderSummaryService(cfg, m, protocol.LocalDeviceID)
  440. svc := New(protocol.LocalDeviceID, cfg, assetDir, "syncthing", m, eventSub, diskEventSub, discoverer, connections, urService, summaryService, errorLog, systemLog, cpu, nil, false).(*service)
  441. svc.started = addrChan
  442. // Actually start the API service
  443. supervisor := suture.New("API test", suture.Spec{
  444. PassThroughPanics: true,
  445. })
  446. supervisor.Add(svc)
  447. supervisor.ServeBackground()
  448. // Make sure the API service is listening, and get the URL to use.
  449. addr := <-addrChan
  450. tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
  451. if err != nil {
  452. return "", fmt.Errorf("Weird address from API service: %v", err)
  453. }
  454. host, _, _ := net.SplitHostPort(cfg.gui.RawAddress)
  455. if host == "" || host == "0.0.0.0" {
  456. host = "127.0.0.1"
  457. }
  458. baseURL := fmt.Sprintf("http://%s", net.JoinHostPort(host, strconv.Itoa(tcpAddr.Port)))
  459. return baseURL, nil
  460. }
  461. func TestCSRFRequired(t *testing.T) {
  462. const testAPIKey = "foobarbaz"
  463. cfg := new(mockedConfig)
  464. cfg.gui.APIKey = testAPIKey
  465. baseURL, err := startHTTP(cfg)
  466. if err != nil {
  467. t.Fatal("Unexpected error from getting base URL:", err)
  468. }
  469. cli := &http.Client{
  470. Timeout: time.Second,
  471. }
  472. // Getting the base URL (i.e. "/") should succeed.
  473. resp, err := cli.Get(baseURL)
  474. if err != nil {
  475. t.Fatal("Unexpected error from getting base URL:", err)
  476. }
  477. resp.Body.Close()
  478. if resp.StatusCode != http.StatusOK {
  479. t.Fatal("Getting base URL should succeed, not", resp.Status)
  480. }
  481. // Find the returned CSRF token for future use
  482. var csrfTokenName, csrfTokenValue string
  483. for _, cookie := range resp.Cookies() {
  484. if strings.HasPrefix(cookie.Name, "CSRF-Token") {
  485. csrfTokenName = cookie.Name
  486. csrfTokenValue = cookie.Value
  487. break
  488. }
  489. }
  490. // Calling on /rest without a token should fail
  491. resp, err = cli.Get(baseURL + "/rest/system/config")
  492. if err != nil {
  493. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  494. }
  495. resp.Body.Close()
  496. if resp.StatusCode != http.StatusForbidden {
  497. t.Fatal("Getting /rest/system/config without CSRF token should fail, not", resp.Status)
  498. }
  499. // Calling on /rest with a token should succeed
  500. req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
  501. req.Header.Set("X-"+csrfTokenName, csrfTokenValue)
  502. resp, err = cli.Do(req)
  503. if err != nil {
  504. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  505. }
  506. resp.Body.Close()
  507. if resp.StatusCode != http.StatusOK {
  508. t.Fatal("Getting /rest/system/config with CSRF token should succeed, not", resp.Status)
  509. }
  510. // Calling on /rest with the API key should succeed
  511. req, _ = http.NewRequest("GET", baseURL+"/rest/system/config", nil)
  512. req.Header.Set("X-API-Key", testAPIKey)
  513. resp, err = cli.Do(req)
  514. if err != nil {
  515. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  516. }
  517. resp.Body.Close()
  518. if resp.StatusCode != http.StatusOK {
  519. t.Fatal("Getting /rest/system/config with API key should succeed, not", resp.Status)
  520. }
  521. }
  522. func TestRandomString(t *testing.T) {
  523. const testAPIKey = "foobarbaz"
  524. cfg := new(mockedConfig)
  525. cfg.gui.APIKey = testAPIKey
  526. baseURL, err := startHTTP(cfg)
  527. if err != nil {
  528. t.Fatal(err)
  529. }
  530. cli := &http.Client{
  531. Timeout: time.Second,
  532. }
  533. // The default should be to return a 32 character random string
  534. for _, url := range []string{"/rest/svc/random/string", "/rest/svc/random/string?length=-1", "/rest/svc/random/string?length=yo"} {
  535. req, _ := http.NewRequest("GET", baseURL+url, nil)
  536. req.Header.Set("X-API-Key", testAPIKey)
  537. resp, err := cli.Do(req)
  538. if err != nil {
  539. t.Fatal(err)
  540. }
  541. var res map[string]string
  542. if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
  543. t.Fatal(err)
  544. }
  545. if len(res["random"]) != 32 {
  546. t.Errorf("Expected 32 random characters, got %q of length %d", res["random"], len(res["random"]))
  547. }
  548. }
  549. // We can ask for a different length if we like
  550. req, _ := http.NewRequest("GET", baseURL+"/rest/svc/random/string?length=27", nil)
  551. req.Header.Set("X-API-Key", testAPIKey)
  552. resp, err := cli.Do(req)
  553. if err != nil {
  554. t.Fatal(err)
  555. }
  556. var res map[string]string
  557. if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
  558. t.Fatal(err)
  559. }
  560. if len(res["random"]) != 27 {
  561. t.Errorf("Expected 27 random characters, got %q of length %d", res["random"], len(res["random"]))
  562. }
  563. }
  564. func TestConfigPostOK(t *testing.T) {
  565. cfg := bytes.NewBuffer([]byte(`{
  566. "version": 15,
  567. "folders": [
  568. {"id": "foo"}
  569. ]
  570. }`))
  571. resp, err := testConfigPost(cfg)
  572. if err != nil {
  573. t.Fatal(err)
  574. }
  575. if resp.StatusCode != http.StatusOK {
  576. t.Error("Expected 200 OK, not", resp.Status)
  577. }
  578. }
  579. func TestConfigPostDupFolder(t *testing.T) {
  580. cfg := bytes.NewBuffer([]byte(`{
  581. "version": 15,
  582. "folders": [
  583. {"id": "foo"},
  584. {"id": "foo"}
  585. ]
  586. }`))
  587. resp, err := testConfigPost(cfg)
  588. if err != nil {
  589. t.Fatal(err)
  590. }
  591. if resp.StatusCode != http.StatusBadRequest {
  592. t.Error("Expected 400 Bad Request, not", resp.Status)
  593. }
  594. }
  595. func testConfigPost(data io.Reader) (*http.Response, error) {
  596. const testAPIKey = "foobarbaz"
  597. cfg := new(mockedConfig)
  598. cfg.gui.APIKey = testAPIKey
  599. baseURL, err := startHTTP(cfg)
  600. if err != nil {
  601. return nil, err
  602. }
  603. cli := &http.Client{
  604. Timeout: time.Second,
  605. }
  606. req, _ := http.NewRequest("POST", baseURL+"/rest/system/config", data)
  607. req.Header.Set("X-API-Key", testAPIKey)
  608. return cli.Do(req)
  609. }
  610. func TestHostCheck(t *testing.T) {
  611. // An API service bound to localhost should reject non-localhost host Headers
  612. cfg := new(mockedConfig)
  613. cfg.gui.RawAddress = "127.0.0.1:0"
  614. baseURL, err := startHTTP(cfg)
  615. if err != nil {
  616. t.Fatal(err)
  617. }
  618. // A normal HTTP get to the localhost-bound service should succeed
  619. resp, err := http.Get(baseURL)
  620. if err != nil {
  621. t.Fatal(err)
  622. }
  623. resp.Body.Close()
  624. if resp.StatusCode != http.StatusOK {
  625. t.Error("Regular HTTP get: expected 200 OK, not", resp.Status)
  626. }
  627. // A request with a suspicious Host header should fail
  628. req, _ := http.NewRequest("GET", baseURL, nil)
  629. req.Host = "example.com"
  630. resp, err = http.DefaultClient.Do(req)
  631. if err != nil {
  632. t.Fatal(err)
  633. }
  634. resp.Body.Close()
  635. if resp.StatusCode != http.StatusForbidden {
  636. t.Error("Suspicious Host header: expected 403 Forbidden, not", resp.Status)
  637. }
  638. // A request with an explicit "localhost:8384" Host header should pass
  639. req, _ = http.NewRequest("GET", baseURL, nil)
  640. req.Host = "localhost:8384"
  641. resp, err = http.DefaultClient.Do(req)
  642. if err != nil {
  643. t.Fatal(err)
  644. }
  645. resp.Body.Close()
  646. if resp.StatusCode != http.StatusOK {
  647. t.Error("Explicit localhost:8384: expected 200 OK, not", resp.Status)
  648. }
  649. // A request with an explicit "localhost" Host header (no port) should pass
  650. req, _ = http.NewRequest("GET", baseURL, nil)
  651. req.Host = "localhost"
  652. resp, err = http.DefaultClient.Do(req)
  653. if err != nil {
  654. t.Fatal(err)
  655. }
  656. resp.Body.Close()
  657. if resp.StatusCode != http.StatusOK {
  658. t.Error("Explicit localhost: expected 200 OK, not", resp.Status)
  659. }
  660. // A server with InsecureSkipHostCheck set behaves differently
  661. cfg = new(mockedConfig)
  662. cfg.gui.RawAddress = "127.0.0.1:0"
  663. cfg.gui.InsecureSkipHostCheck = true
  664. baseURL, err = startHTTP(cfg)
  665. if err != nil {
  666. t.Fatal(err)
  667. }
  668. // A request with a suspicious Host header should be allowed
  669. req, _ = http.NewRequest("GET", baseURL, nil)
  670. req.Host = "example.com"
  671. resp, err = http.DefaultClient.Do(req)
  672. if err != nil {
  673. t.Fatal(err)
  674. }
  675. resp.Body.Close()
  676. if resp.StatusCode != http.StatusOK {
  677. t.Error("Incorrect host header, check disabled: expected 200 OK, not", resp.Status)
  678. }
  679. // A server bound to a wildcard address also doesn't do the check
  680. cfg = new(mockedConfig)
  681. cfg.gui.RawAddress = "0.0.0.0:0"
  682. cfg.gui.InsecureSkipHostCheck = true
  683. baseURL, err = startHTTP(cfg)
  684. if err != nil {
  685. t.Fatal(err)
  686. }
  687. // A request with a suspicious Host header should be allowed
  688. req, _ = http.NewRequest("GET", baseURL, nil)
  689. req.Host = "example.com"
  690. resp, err = http.DefaultClient.Do(req)
  691. if err != nil {
  692. t.Fatal(err)
  693. }
  694. resp.Body.Close()
  695. if resp.StatusCode != http.StatusOK {
  696. t.Error("Incorrect host header, wildcard bound: expected 200 OK, not", resp.Status)
  697. }
  698. // This should all work over IPv6 as well
  699. cfg = new(mockedConfig)
  700. cfg.gui.RawAddress = "[::1]:0"
  701. baseURL, err = startHTTP(cfg)
  702. if err != nil {
  703. t.Fatal(err)
  704. }
  705. // A normal HTTP get to the localhost-bound service should succeed
  706. resp, err = http.Get(baseURL)
  707. if err != nil {
  708. t.Fatal(err)
  709. }
  710. resp.Body.Close()
  711. if resp.StatusCode != http.StatusOK {
  712. t.Error("Regular HTTP get (IPv6): expected 200 OK, not", resp.Status)
  713. }
  714. // A request with a suspicious Host header should fail
  715. req, _ = http.NewRequest("GET", baseURL, nil)
  716. req.Host = "example.com"
  717. resp, err = http.DefaultClient.Do(req)
  718. if err != nil {
  719. t.Fatal(err)
  720. }
  721. resp.Body.Close()
  722. if resp.StatusCode != http.StatusForbidden {
  723. t.Error("Suspicious Host header (IPv6): expected 403 Forbidden, not", resp.Status)
  724. }
  725. // A request with an explicit "localhost:8384" Host header should pass
  726. req, _ = http.NewRequest("GET", baseURL, nil)
  727. req.Host = "localhost:8384"
  728. resp, err = http.DefaultClient.Do(req)
  729. if err != nil {
  730. t.Fatal(err)
  731. }
  732. resp.Body.Close()
  733. if resp.StatusCode != http.StatusOK {
  734. t.Error("Explicit localhost:8384 (IPv6): expected 200 OK, not", resp.Status)
  735. }
  736. }
  737. func TestAddressIsLocalhost(t *testing.T) {
  738. testcases := []struct {
  739. address string
  740. result bool
  741. }{
  742. // These are all valid localhost addresses
  743. {"localhost", true},
  744. {"LOCALHOST", true},
  745. {"localhost.", true},
  746. {"::1", true},
  747. {"127.0.0.1", true},
  748. {"127.23.45.56", true},
  749. {"localhost:8080", true},
  750. {"LOCALHOST:8000", true},
  751. {"localhost.:8080", true},
  752. {"[::1]:8080", true},
  753. {"127.0.0.1:8080", true},
  754. {"127.23.45.56:8080", true},
  755. // These are all non-localhost addresses
  756. {"example.com", false},
  757. {"example.com:8080", false},
  758. {"localhost.com", false},
  759. {"localhost.com:8080", false},
  760. {"www.localhost", false},
  761. {"www.localhost:8080", false},
  762. {"192.0.2.10", false},
  763. {"192.0.2.10:8080", false},
  764. {"0.0.0.0", false},
  765. {"0.0.0.0:8080", false},
  766. {"::", false},
  767. {"[::]:8080", false},
  768. {":8080", false},
  769. }
  770. for _, tc := range testcases {
  771. result := addressIsLocalhost(tc.address)
  772. if result != tc.result {
  773. t.Errorf("addressIsLocalhost(%q)=%v, expected %v", tc.address, result, tc.result)
  774. }
  775. }
  776. }
  777. func TestAccessControlAllowOriginHeader(t *testing.T) {
  778. const testAPIKey = "foobarbaz"
  779. cfg := new(mockedConfig)
  780. cfg.gui.APIKey = testAPIKey
  781. baseURL, err := startHTTP(cfg)
  782. if err != nil {
  783. t.Fatal(err)
  784. }
  785. cli := &http.Client{
  786. Timeout: time.Second,
  787. }
  788. req, _ := http.NewRequest("GET", baseURL+"/rest/system/status", nil)
  789. req.Header.Set("X-API-Key", testAPIKey)
  790. resp, err := cli.Do(req)
  791. if err != nil {
  792. t.Fatal(err)
  793. }
  794. resp.Body.Close()
  795. if resp.StatusCode != http.StatusOK {
  796. t.Fatal("GET on /rest/system/status should succeed, not", resp.Status)
  797. }
  798. if resp.Header.Get("Access-Control-Allow-Origin") != "*" {
  799. t.Fatal("GET on /rest/system/status should return a 'Access-Control-Allow-Origin: *' header")
  800. }
  801. }
  802. func TestOptionsRequest(t *testing.T) {
  803. const testAPIKey = "foobarbaz"
  804. cfg := new(mockedConfig)
  805. cfg.gui.APIKey = testAPIKey
  806. baseURL, err := startHTTP(cfg)
  807. if err != nil {
  808. t.Fatal(err)
  809. }
  810. cli := &http.Client{
  811. Timeout: time.Second,
  812. }
  813. req, _ := http.NewRequest("OPTIONS", baseURL+"/rest/system/status", nil)
  814. resp, err := cli.Do(req)
  815. if err != nil {
  816. t.Fatal(err)
  817. }
  818. resp.Body.Close()
  819. if resp.StatusCode != http.StatusNoContent {
  820. t.Fatal("OPTIONS on /rest/system/status should succeed, not", resp.Status)
  821. }
  822. if resp.Header.Get("Access-Control-Allow-Origin") != "*" {
  823. t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Origin: *' header")
  824. }
  825. if resp.Header.Get("Access-Control-Allow-Methods") != "GET, POST" {
  826. t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Methods: GET, POST' header")
  827. }
  828. if resp.Header.Get("Access-Control-Allow-Headers") != "Content-Type, X-API-Key" {
  829. t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Headers: Content-Type, X-API-KEY' header")
  830. }
  831. }
  832. func TestEventMasks(t *testing.T) {
  833. cfg := new(mockedConfig)
  834. defSub := new(mockedEventSub)
  835. diskSub := new(mockedEventSub)
  836. svc := New(protocol.LocalDeviceID, cfg, "", "syncthing", nil, defSub, diskSub, nil, nil, nil, nil, nil, nil, nil, nil, false).(*service)
  837. if mask := svc.getEventMask(""); mask != DefaultEventMask {
  838. t.Errorf("incorrect default mask %x != %x", int64(mask), int64(DefaultEventMask))
  839. }
  840. expected := events.FolderSummary | events.LocalChangeDetected
  841. if mask := svc.getEventMask("FolderSummary,LocalChangeDetected"); mask != expected {
  842. t.Errorf("incorrect parsed mask %x != %x", int64(mask), int64(expected))
  843. }
  844. expected = 0
  845. if mask := svc.getEventMask("WeirdEvent,something else that doesn't exist"); mask != expected {
  846. t.Errorf("incorrect parsed mask %x != %x", int64(mask), int64(expected))
  847. }
  848. if res := svc.getEventSub(DefaultEventMask); res != defSub {
  849. t.Errorf("should have returned the given default event sub")
  850. }
  851. if res := svc.getEventSub(DiskEventMask); res != diskSub {
  852. t.Errorf("should have returned the given disk event sub")
  853. }
  854. if res := svc.getEventSub(events.LocalIndexUpdated); res == nil || res == defSub || res == diskSub {
  855. t.Errorf("should have returned a valid, non-default event sub")
  856. }
  857. }
  858. func TestBrowse(t *testing.T) {
  859. pathSep := string(os.PathSeparator)
  860. tmpDir, err := ioutil.TempDir("", "syncthing")
  861. if err != nil {
  862. t.Fatal(err)
  863. }
  864. defer os.RemoveAll(tmpDir)
  865. if err := os.Mkdir(filepath.Join(tmpDir, "dir"), 0755); err != nil {
  866. t.Fatal(err)
  867. }
  868. if err := ioutil.WriteFile(filepath.Join(tmpDir, "file"), []byte("hello"), 0644); err != nil {
  869. t.Fatal(err)
  870. }
  871. if err := os.Mkdir(filepath.Join(tmpDir, "MiXEDCase"), 0755); err != nil {
  872. t.Fatal(err)
  873. }
  874. // We expect completion to return the full path to the completed
  875. // directory, with an ending slash.
  876. dirPath := filepath.Join(tmpDir, "dir") + pathSep
  877. mixedCaseDirPath := filepath.Join(tmpDir, "MiXEDCase") + pathSep
  878. cases := []struct {
  879. current string
  880. returns []string
  881. }{
  882. // The direcotory without slash is completed to one with slash.
  883. {tmpDir, []string{tmpDir + pathSep}},
  884. // With slash it's completed to its contents.
  885. // Dirs are given pathSeps.
  886. // Files are not returned.
  887. {tmpDir + pathSep, []string{mixedCaseDirPath, dirPath}},
  888. // Globbing is automatic based on prefix.
  889. {tmpDir + pathSep + "d", []string{dirPath}},
  890. {tmpDir + pathSep + "di", []string{dirPath}},
  891. {tmpDir + pathSep + "dir", []string{dirPath}},
  892. {tmpDir + pathSep + "f", nil},
  893. {tmpDir + pathSep + "q", nil},
  894. // Globbing is case-insensitve
  895. {tmpDir + pathSep + "mixed", []string{mixedCaseDirPath}},
  896. }
  897. for _, tc := range cases {
  898. ret := browseFiles(tc.current, fs.FilesystemTypeBasic)
  899. if !equalStrings(ret, tc.returns) {
  900. t.Errorf("browseFiles(%q) => %q, expected %q", tc.current, ret, tc.returns)
  901. }
  902. }
  903. }
  904. func TestPrefixMatch(t *testing.T) {
  905. cases := []struct {
  906. s string
  907. prefix string
  908. expected int
  909. }{
  910. {"aaaA", "aaa", matchExact},
  911. {"AAAX", "BBB", noMatch},
  912. {"AAAX", "aAa", matchCaseIns},
  913. {"äÜX", "äü", matchCaseIns},
  914. }
  915. for _, tc := range cases {
  916. ret := checkPrefixMatch(tc.s, tc.prefix)
  917. if ret != tc.expected {
  918. t.Errorf("checkPrefixMatch(%q, %q) => %v, expected %v", tc.s, tc.prefix, ret, tc.expected)
  919. }
  920. }
  921. }
  922. func equalStrings(a, b []string) bool {
  923. if len(a) != len(b) {
  924. return false
  925. }
  926. for i := range a {
  927. if a[i] != b[i] {
  928. return false
  929. }
  930. }
  931. return true
  932. }