api_test.go 27 KB

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