api_test.go 29 KB

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