api_test.go 34 KB

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