api_test.go 30 KB

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