api_test.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  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/folders",
  358. Code: 200,
  359. Type: "application/json",
  360. Prefix: "",
  361. },
  362. {
  363. URL: "/rest/config/folders/missing",
  364. Code: 404,
  365. Type: "text/plain",
  366. Prefix: "",
  367. },
  368. {
  369. URL: "/rest/config/devices",
  370. Code: 200,
  371. Type: "application/json",
  372. Prefix: "",
  373. },
  374. {
  375. URL: "/rest/config/devices/illegalid",
  376. Code: 400,
  377. Type: "text/plain",
  378. Prefix: "",
  379. },
  380. {
  381. URL: "/rest/config/devices/" + protocol.GlobalDeviceID.String(),
  382. Code: 404,
  383. Type: "text/plain",
  384. Prefix: "",
  385. },
  386. {
  387. URL: "/rest/config/options",
  388. Code: 200,
  389. Type: "application/json",
  390. Prefix: "{",
  391. },
  392. {
  393. URL: "/rest/config/gui",
  394. Code: 200,
  395. Type: "application/json",
  396. Prefix: "{",
  397. },
  398. {
  399. URL: "/rest/config/ldap",
  400. Code: 200,
  401. Type: "application/json",
  402. Prefix: "{",
  403. },
  404. }
  405. for _, tc := range cases {
  406. t.Log("Testing", tc.URL, "...")
  407. testHTTPRequest(t, baseURL, tc, testAPIKey)
  408. }
  409. }
  410. // testHTTPRequest tries the given test case, comparing the result code,
  411. // content type, and result prefix.
  412. func testHTTPRequest(t *testing.T, baseURL string, tc httpTestCase, apikey string) {
  413. timeout := time.Second
  414. if tc.Timeout > 0 {
  415. timeout = tc.Timeout
  416. }
  417. cli := &http.Client{
  418. Timeout: timeout,
  419. }
  420. req, err := http.NewRequest("GET", baseURL+tc.URL, nil)
  421. if err != nil {
  422. t.Errorf("Unexpected error requesting %s: %v", tc.URL, err)
  423. return
  424. }
  425. req.Header.Set("X-API-Key", apikey)
  426. resp, err := cli.Do(req)
  427. if err != nil {
  428. t.Errorf("Unexpected error requesting %s: %v", tc.URL, err)
  429. return
  430. }
  431. defer resp.Body.Close()
  432. if resp.StatusCode != tc.Code {
  433. t.Errorf("Get on %s should have returned status code %d, not %s", tc.URL, tc.Code, resp.Status)
  434. return
  435. }
  436. ct := resp.Header.Get("Content-Type")
  437. if !strings.HasPrefix(ct, tc.Type) {
  438. t.Errorf("The content type on %s should be %q, not %q", tc.URL, tc.Type, ct)
  439. return
  440. }
  441. data, err := ioutil.ReadAll(resp.Body)
  442. if err != nil {
  443. t.Errorf("Unexpected error reading %s: %v", tc.URL, err)
  444. return
  445. }
  446. if !bytes.HasPrefix(data, []byte(tc.Prefix)) {
  447. t.Errorf("Returned data from %s does not have prefix %q: %s", tc.URL, tc.Prefix, data)
  448. return
  449. }
  450. }
  451. func TestHTTPLogin(t *testing.T) {
  452. t.Parallel()
  453. cfg := new(mockedConfig)
  454. cfg.gui.User = "üser"
  455. cfg.gui.Password = "$2a$10$IdIZTxTg/dCNuNEGlmLynOjqg4B1FvDKuIV5e0BB3pnWVHNb8.GSq" // bcrypt of "räksmörgås" in UTF-8
  456. baseURL, sup, err := startHTTP(cfg)
  457. if err != nil {
  458. t.Fatal(err)
  459. }
  460. defer sup.Stop()
  461. // Verify rejection when not using authorization
  462. req, _ := http.NewRequest("GET", baseURL, nil)
  463. resp, err := http.DefaultClient.Do(req)
  464. if err != nil {
  465. t.Fatal(err)
  466. }
  467. if resp.StatusCode != http.StatusUnauthorized {
  468. t.Errorf("Unexpected non-401 return code %d for unauthed request", resp.StatusCode)
  469. }
  470. // Verify that incorrect password is rejected
  471. req.SetBasicAuth("üser", "rksmrgs")
  472. resp, err = http.DefaultClient.Do(req)
  473. if err != nil {
  474. t.Fatal(err)
  475. }
  476. if resp.StatusCode != http.StatusUnauthorized {
  477. t.Errorf("Unexpected non-401 return code %d for incorrect password", resp.StatusCode)
  478. }
  479. // Verify that incorrect username is rejected
  480. req.SetBasicAuth("user", "räksmörgås") // string literals in Go source code are in UTF-8
  481. resp, err = http.DefaultClient.Do(req)
  482. if err != nil {
  483. t.Fatal(err)
  484. }
  485. if resp.StatusCode != http.StatusUnauthorized {
  486. t.Errorf("Unexpected non-401 return code %d for incorrect username", resp.StatusCode)
  487. }
  488. // Verify that UTF-8 auth works
  489. req.SetBasicAuth("üser", "räksmörgås") // string literals in Go source code are in UTF-8
  490. resp, err = http.DefaultClient.Do(req)
  491. if err != nil {
  492. t.Fatal(err)
  493. }
  494. if resp.StatusCode != http.StatusOK {
  495. t.Errorf("Unexpected non-200 return code %d for authed request (UTF-8)", resp.StatusCode)
  496. }
  497. // Verify that ISO-8859-1 auth
  498. req.SetBasicAuth("\xfcser", "r\xe4ksm\xf6rg\xe5s") // escaped ISO-8859-1
  499. resp, err = http.DefaultClient.Do(req)
  500. if err != nil {
  501. t.Fatal(err)
  502. }
  503. if resp.StatusCode != http.StatusOK {
  504. t.Errorf("Unexpected non-200 return code %d for authed request (ISO-8859-1)", resp.StatusCode)
  505. }
  506. }
  507. func startHTTP(cfg config.Wrapper) (string, *suture.Supervisor, error) {
  508. m := new(mockedModel)
  509. assetDir := "../../gui"
  510. eventSub := new(mockedEventSub)
  511. diskEventSub := new(mockedEventSub)
  512. discoverer := new(mockedCachingMux)
  513. connections := new(mockedConnections)
  514. errorLog := new(mockedLoggerRecorder)
  515. systemLog := new(mockedLoggerRecorder)
  516. addrChan := make(chan string)
  517. // Instantiate the API service
  518. urService := ur.New(cfg, m, connections, false)
  519. svc := New(protocol.LocalDeviceID, cfg, assetDir, "syncthing", m, eventSub, diskEventSub, events.NoopLogger, discoverer, connections, urService, &mockedFolderSummaryService{}, errorLog, systemLog, nil, false).(*service)
  520. defer os.Remove(token)
  521. svc.started = addrChan
  522. // Actually start the API service
  523. supervisor := suture.New("API test", suture.Spec{
  524. PassThroughPanics: true,
  525. })
  526. supervisor.Add(svc)
  527. supervisor.ServeBackground()
  528. // Make sure the API service is listening, and get the URL to use.
  529. addr := <-addrChan
  530. tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
  531. if err != nil {
  532. supervisor.Stop()
  533. return "", nil, fmt.Errorf("weird address from API service: %w", err)
  534. }
  535. host, _, _ := net.SplitHostPort(cfg.GUI().RawAddress)
  536. if host == "" || host == "0.0.0.0" {
  537. host = "127.0.0.1"
  538. }
  539. baseURL := fmt.Sprintf("http://%s", net.JoinHostPort(host, strconv.Itoa(tcpAddr.Port)))
  540. return baseURL, supervisor, nil
  541. }
  542. func TestCSRFRequired(t *testing.T) {
  543. t.Parallel()
  544. const testAPIKey = "foobarbaz"
  545. cfg := new(mockedConfig)
  546. cfg.gui.APIKey = testAPIKey
  547. baseURL, sup, err := startHTTP(cfg)
  548. if err != nil {
  549. t.Fatal("Unexpected error from getting base URL:", err)
  550. }
  551. defer sup.Stop()
  552. cli := &http.Client{
  553. Timeout: time.Minute,
  554. }
  555. // Getting the base URL (i.e. "/") should succeed.
  556. resp, err := cli.Get(baseURL)
  557. if err != nil {
  558. t.Fatal("Unexpected error from getting base URL:", err)
  559. }
  560. resp.Body.Close()
  561. if resp.StatusCode != http.StatusOK {
  562. t.Fatal("Getting base URL should succeed, not", resp.Status)
  563. }
  564. // Find the returned CSRF token for future use
  565. var csrfTokenName, csrfTokenValue string
  566. for _, cookie := range resp.Cookies() {
  567. if strings.HasPrefix(cookie.Name, "CSRF-Token") {
  568. csrfTokenName = cookie.Name
  569. csrfTokenValue = cookie.Value
  570. break
  571. }
  572. }
  573. // Calling on /rest without a token should fail
  574. resp, err = cli.Get(baseURL + "/rest/system/config")
  575. if err != nil {
  576. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  577. }
  578. resp.Body.Close()
  579. if resp.StatusCode != http.StatusForbidden {
  580. t.Fatal("Getting /rest/system/config without CSRF token should fail, not", resp.Status)
  581. }
  582. // Calling on /rest with a token should succeed
  583. req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
  584. req.Header.Set("X-"+csrfTokenName, csrfTokenValue)
  585. resp, err = cli.Do(req)
  586. if err != nil {
  587. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  588. }
  589. resp.Body.Close()
  590. if resp.StatusCode != http.StatusOK {
  591. t.Fatal("Getting /rest/system/config with CSRF token should succeed, not", resp.Status)
  592. }
  593. // Calling on /rest with the API key should succeed
  594. req, _ = http.NewRequest("GET", baseURL+"/rest/system/config", nil)
  595. req.Header.Set("X-API-Key", testAPIKey)
  596. resp, err = cli.Do(req)
  597. if err != nil {
  598. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  599. }
  600. resp.Body.Close()
  601. if resp.StatusCode != http.StatusOK {
  602. t.Fatal("Getting /rest/system/config with API key should succeed, not", resp.Status)
  603. }
  604. }
  605. func TestRandomString(t *testing.T) {
  606. t.Parallel()
  607. const testAPIKey = "foobarbaz"
  608. cfg := new(mockedConfig)
  609. cfg.gui.APIKey = testAPIKey
  610. baseURL, sup, err := startHTTP(cfg)
  611. if err != nil {
  612. t.Fatal(err)
  613. }
  614. defer sup.Stop()
  615. cli := &http.Client{
  616. Timeout: time.Second,
  617. }
  618. // The default should be to return a 32 character random string
  619. for _, url := range []string{"/rest/svc/random/string", "/rest/svc/random/string?length=-1", "/rest/svc/random/string?length=yo"} {
  620. req, _ := http.NewRequest("GET", baseURL+url, nil)
  621. req.Header.Set("X-API-Key", testAPIKey)
  622. resp, err := cli.Do(req)
  623. if err != nil {
  624. t.Fatal(err)
  625. }
  626. var res map[string]string
  627. if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
  628. t.Fatal(err)
  629. }
  630. if len(res["random"]) != 32 {
  631. t.Errorf("Expected 32 random characters, got %q of length %d", res["random"], len(res["random"]))
  632. }
  633. }
  634. // We can ask for a different length if we like
  635. req, _ := http.NewRequest("GET", baseURL+"/rest/svc/random/string?length=27", nil)
  636. req.Header.Set("X-API-Key", testAPIKey)
  637. resp, err := cli.Do(req)
  638. if err != nil {
  639. t.Fatal(err)
  640. }
  641. var res map[string]string
  642. if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
  643. t.Fatal(err)
  644. }
  645. if len(res["random"]) != 27 {
  646. t.Errorf("Expected 27 random characters, got %q of length %d", res["random"], len(res["random"]))
  647. }
  648. }
  649. func TestConfigPostOK(t *testing.T) {
  650. t.Parallel()
  651. cfg := bytes.NewBuffer([]byte(`{
  652. "version": 15,
  653. "folders": [
  654. {
  655. "id": "foo",
  656. "path": "TestConfigPostOK"
  657. }
  658. ]
  659. }`))
  660. resp, err := testConfigPost(cfg)
  661. if err != nil {
  662. t.Fatal(err)
  663. }
  664. if resp.StatusCode != http.StatusOK {
  665. t.Error("Expected 200 OK, not", resp.Status)
  666. }
  667. os.RemoveAll("TestConfigPostOK")
  668. }
  669. func TestConfigPostDupFolder(t *testing.T) {
  670. t.Parallel()
  671. cfg := bytes.NewBuffer([]byte(`{
  672. "version": 15,
  673. "folders": [
  674. {"id": "foo"},
  675. {"id": "foo"}
  676. ]
  677. }`))
  678. resp, err := testConfigPost(cfg)
  679. if err != nil {
  680. t.Fatal(err)
  681. }
  682. if resp.StatusCode != http.StatusBadRequest {
  683. t.Error("Expected 400 Bad Request, not", resp.Status)
  684. }
  685. }
  686. func testConfigPost(data io.Reader) (*http.Response, error) {
  687. const testAPIKey = "foobarbaz"
  688. cfg := new(mockedConfig)
  689. cfg.gui.APIKey = testAPIKey
  690. baseURL, sup, err := startHTTP(cfg)
  691. if err != nil {
  692. return nil, err
  693. }
  694. defer sup.Stop()
  695. cli := &http.Client{
  696. Timeout: time.Second,
  697. }
  698. req, _ := http.NewRequest("POST", baseURL+"/rest/system/config", data)
  699. req.Header.Set("X-API-Key", testAPIKey)
  700. return cli.Do(req)
  701. }
  702. func TestHostCheck(t *testing.T) {
  703. t.Parallel()
  704. // An API service bound to localhost should reject non-localhost host Headers
  705. cfg := new(mockedConfig)
  706. cfg.gui.RawAddress = "127.0.0.1:0"
  707. baseURL, sup, err := startHTTP(cfg)
  708. if err != nil {
  709. t.Fatal(err)
  710. }
  711. defer sup.Stop()
  712. // A normal HTTP get to the localhost-bound service should succeed
  713. resp, err := http.Get(baseURL)
  714. if err != nil {
  715. t.Fatal(err)
  716. }
  717. resp.Body.Close()
  718. if resp.StatusCode != http.StatusOK {
  719. t.Error("Regular HTTP get: expected 200 OK, not", resp.Status)
  720. }
  721. // A request with a suspicious Host header should fail
  722. req, _ := http.NewRequest("GET", baseURL, nil)
  723. req.Host = "example.com"
  724. resp, err = http.DefaultClient.Do(req)
  725. if err != nil {
  726. t.Fatal(err)
  727. }
  728. resp.Body.Close()
  729. if resp.StatusCode != http.StatusForbidden {
  730. t.Error("Suspicious Host header: expected 403 Forbidden, not", resp.Status)
  731. }
  732. // A request with an explicit "localhost:8384" Host header should pass
  733. req, _ = http.NewRequest("GET", baseURL, nil)
  734. req.Host = "localhost:8384"
  735. resp, err = http.DefaultClient.Do(req)
  736. if err != nil {
  737. t.Fatal(err)
  738. }
  739. resp.Body.Close()
  740. if resp.StatusCode != http.StatusOK {
  741. t.Error("Explicit localhost:8384: expected 200 OK, not", resp.Status)
  742. }
  743. // A request with an explicit "localhost" Host header (no port) should pass
  744. req, _ = http.NewRequest("GET", baseURL, nil)
  745. req.Host = "localhost"
  746. resp, err = http.DefaultClient.Do(req)
  747. if err != nil {
  748. t.Fatal(err)
  749. }
  750. resp.Body.Close()
  751. if resp.StatusCode != http.StatusOK {
  752. t.Error("Explicit localhost: expected 200 OK, not", resp.Status)
  753. }
  754. // A server with InsecureSkipHostCheck set behaves differently
  755. cfg = new(mockedConfig)
  756. cfg.gui.RawAddress = "127.0.0.1:0"
  757. cfg.gui.InsecureSkipHostCheck = true
  758. baseURL, sup, err = startHTTP(cfg)
  759. if err != nil {
  760. t.Fatal(err)
  761. }
  762. defer sup.Stop()
  763. // A request with a suspicious Host header should be allowed
  764. req, _ = http.NewRequest("GET", baseURL, nil)
  765. req.Host = "example.com"
  766. resp, err = http.DefaultClient.Do(req)
  767. if err != nil {
  768. t.Fatal(err)
  769. }
  770. resp.Body.Close()
  771. if resp.StatusCode != http.StatusOK {
  772. t.Error("Incorrect host header, check disabled: expected 200 OK, not", resp.Status)
  773. }
  774. // A server bound to a wildcard address also doesn't do the check
  775. cfg = new(mockedConfig)
  776. cfg.gui.RawAddress = "0.0.0.0:0"
  777. cfg.gui.InsecureSkipHostCheck = true
  778. baseURL, sup, err = startHTTP(cfg)
  779. if err != nil {
  780. t.Fatal(err)
  781. }
  782. defer sup.Stop()
  783. // A request with a suspicious Host header should be allowed
  784. req, _ = http.NewRequest("GET", baseURL, nil)
  785. req.Host = "example.com"
  786. resp, err = http.DefaultClient.Do(req)
  787. if err != nil {
  788. t.Fatal(err)
  789. }
  790. resp.Body.Close()
  791. if resp.StatusCode != http.StatusOK {
  792. t.Error("Incorrect host header, wildcard bound: expected 200 OK, not", resp.Status)
  793. }
  794. // This should all work over IPv6 as well
  795. if runningInContainer() {
  796. // Working IPv6 in Docker can't be taken for granted.
  797. return
  798. }
  799. cfg = new(mockedConfig)
  800. cfg.gui.RawAddress = "[::1]:0"
  801. baseURL, sup, err = startHTTP(cfg)
  802. if err != nil {
  803. t.Fatal(err)
  804. }
  805. defer sup.Stop()
  806. // A normal HTTP get to the localhost-bound service should succeed
  807. resp, err = http.Get(baseURL)
  808. if err != nil {
  809. t.Fatal(err)
  810. }
  811. resp.Body.Close()
  812. if resp.StatusCode != http.StatusOK {
  813. t.Error("Regular HTTP get (IPv6): expected 200 OK, not", resp.Status)
  814. }
  815. // A request with a suspicious Host header should fail
  816. req, _ = http.NewRequest("GET", baseURL, nil)
  817. req.Host = "example.com"
  818. resp, err = http.DefaultClient.Do(req)
  819. if err != nil {
  820. t.Fatal(err)
  821. }
  822. resp.Body.Close()
  823. if resp.StatusCode != http.StatusForbidden {
  824. t.Error("Suspicious Host header (IPv6): expected 403 Forbidden, not", resp.Status)
  825. }
  826. // A request with an explicit "localhost:8384" Host header should pass
  827. req, _ = http.NewRequest("GET", baseURL, nil)
  828. req.Host = "localhost:8384"
  829. resp, err = http.DefaultClient.Do(req)
  830. if err != nil {
  831. t.Fatal(err)
  832. }
  833. resp.Body.Close()
  834. if resp.StatusCode != http.StatusOK {
  835. t.Error("Explicit localhost:8384 (IPv6): expected 200 OK, not", resp.Status)
  836. }
  837. }
  838. func TestAddressIsLocalhost(t *testing.T) {
  839. t.Parallel()
  840. testcases := []struct {
  841. address string
  842. result bool
  843. }{
  844. // These are all valid localhost addresses
  845. {"localhost", true},
  846. {"LOCALHOST", true},
  847. {"localhost.", true},
  848. {"::1", true},
  849. {"127.0.0.1", true},
  850. {"127.23.45.56", true},
  851. {"localhost:8080", true},
  852. {"LOCALHOST:8000", true},
  853. {"localhost.:8080", true},
  854. {"[::1]:8080", true},
  855. {"127.0.0.1:8080", true},
  856. {"127.23.45.56:8080", true},
  857. // These are all non-localhost addresses
  858. {"example.com", false},
  859. {"example.com:8080", false},
  860. {"localhost.com", false},
  861. {"localhost.com:8080", false},
  862. {"www.localhost", false},
  863. {"www.localhost:8080", false},
  864. {"192.0.2.10", false},
  865. {"192.0.2.10:8080", false},
  866. {"0.0.0.0", false},
  867. {"0.0.0.0:8080", false},
  868. {"::", false},
  869. {"[::]:8080", false},
  870. {":8080", false},
  871. }
  872. for _, tc := range testcases {
  873. result := addressIsLocalhost(tc.address)
  874. if result != tc.result {
  875. t.Errorf("addressIsLocalhost(%q)=%v, expected %v", tc.address, result, tc.result)
  876. }
  877. }
  878. }
  879. func TestAccessControlAllowOriginHeader(t *testing.T) {
  880. t.Parallel()
  881. const testAPIKey = "foobarbaz"
  882. cfg := new(mockedConfig)
  883. cfg.gui.APIKey = testAPIKey
  884. baseURL, sup, err := startHTTP(cfg)
  885. if err != nil {
  886. t.Fatal(err)
  887. }
  888. defer sup.Stop()
  889. cli := &http.Client{
  890. Timeout: time.Second,
  891. }
  892. req, _ := http.NewRequest("GET", baseURL+"/rest/system/status", nil)
  893. req.Header.Set("X-API-Key", testAPIKey)
  894. resp, err := cli.Do(req)
  895. if err != nil {
  896. t.Fatal(err)
  897. }
  898. resp.Body.Close()
  899. if resp.StatusCode != http.StatusOK {
  900. t.Fatal("GET on /rest/system/status should succeed, not", resp.Status)
  901. }
  902. if resp.Header.Get("Access-Control-Allow-Origin") != "*" {
  903. t.Fatal("GET on /rest/system/status should return a 'Access-Control-Allow-Origin: *' header")
  904. }
  905. }
  906. func TestOptionsRequest(t *testing.T) {
  907. t.Parallel()
  908. const testAPIKey = "foobarbaz"
  909. cfg := new(mockedConfig)
  910. cfg.gui.APIKey = testAPIKey
  911. baseURL, sup, err := startHTTP(cfg)
  912. if err != nil {
  913. t.Fatal(err)
  914. }
  915. defer sup.Stop()
  916. cli := &http.Client{
  917. Timeout: time.Second,
  918. }
  919. req, _ := http.NewRequest("OPTIONS", baseURL+"/rest/system/status", nil)
  920. resp, err := cli.Do(req)
  921. if err != nil {
  922. t.Fatal(err)
  923. }
  924. resp.Body.Close()
  925. if resp.StatusCode != http.StatusNoContent {
  926. t.Fatal("OPTIONS on /rest/system/status should succeed, not", resp.Status)
  927. }
  928. if resp.Header.Get("Access-Control-Allow-Origin") != "*" {
  929. t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Origin: *' header")
  930. }
  931. if resp.Header.Get("Access-Control-Allow-Methods") != "GET, POST" {
  932. t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Methods: GET, POST' header")
  933. }
  934. if resp.Header.Get("Access-Control-Allow-Headers") != "Content-Type, X-API-Key" {
  935. t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Headers: Content-Type, X-API-KEY' header")
  936. }
  937. }
  938. func TestEventMasks(t *testing.T) {
  939. t.Parallel()
  940. cfg := new(mockedConfig)
  941. defSub := new(mockedEventSub)
  942. diskSub := new(mockedEventSub)
  943. svc := New(protocol.LocalDeviceID, cfg, "", "syncthing", nil, defSub, diskSub, events.NoopLogger, nil, nil, nil, nil, nil, nil, nil, false).(*service)
  944. defer os.Remove(token)
  945. if mask := svc.getEventMask(""); mask != DefaultEventMask {
  946. t.Errorf("incorrect default mask %x != %x", int64(mask), int64(DefaultEventMask))
  947. }
  948. expected := events.FolderSummary | events.LocalChangeDetected
  949. if mask := svc.getEventMask("FolderSummary,LocalChangeDetected"); mask != expected {
  950. t.Errorf("incorrect parsed mask %x != %x", int64(mask), int64(expected))
  951. }
  952. expected = 0
  953. if mask := svc.getEventMask("WeirdEvent,something else that doesn't exist"); mask != expected {
  954. t.Errorf("incorrect parsed mask %x != %x", int64(mask), int64(expected))
  955. }
  956. if res := svc.getEventSub(DefaultEventMask); res != defSub {
  957. t.Errorf("should have returned the given default event sub")
  958. }
  959. if res := svc.getEventSub(DiskEventMask); res != diskSub {
  960. t.Errorf("should have returned the given disk event sub")
  961. }
  962. if res := svc.getEventSub(events.LocalIndexUpdated); res == nil || res == defSub || res == diskSub {
  963. t.Errorf("should have returned a valid, non-default event sub")
  964. }
  965. }
  966. func TestBrowse(t *testing.T) {
  967. t.Parallel()
  968. pathSep := string(os.PathSeparator)
  969. tmpDir, err := ioutil.TempDir("", "syncthing")
  970. if err != nil {
  971. t.Fatal(err)
  972. }
  973. defer os.RemoveAll(tmpDir)
  974. if err := os.Mkdir(filepath.Join(tmpDir, "dir"), 0755); err != nil {
  975. t.Fatal(err)
  976. }
  977. if err := ioutil.WriteFile(filepath.Join(tmpDir, "file"), []byte("hello"), 0644); err != nil {
  978. t.Fatal(err)
  979. }
  980. if err := os.Mkdir(filepath.Join(tmpDir, "MiXEDCase"), 0755); err != nil {
  981. t.Fatal(err)
  982. }
  983. // We expect completion to return the full path to the completed
  984. // directory, with an ending slash.
  985. dirPath := filepath.Join(tmpDir, "dir") + pathSep
  986. mixedCaseDirPath := filepath.Join(tmpDir, "MiXEDCase") + pathSep
  987. cases := []struct {
  988. current string
  989. returns []string
  990. }{
  991. // The direcotory without slash is completed to one with slash.
  992. {tmpDir, []string{tmpDir + pathSep}},
  993. // With slash it's completed to its contents.
  994. // Dirs are given pathSeps.
  995. // Files are not returned.
  996. {tmpDir + pathSep, []string{mixedCaseDirPath, dirPath}},
  997. // Globbing is automatic based on prefix.
  998. {tmpDir + pathSep + "d", []string{dirPath}},
  999. {tmpDir + pathSep + "di", []string{dirPath}},
  1000. {tmpDir + pathSep + "dir", []string{dirPath}},
  1001. {tmpDir + pathSep + "f", nil},
  1002. {tmpDir + pathSep + "q", nil},
  1003. // Globbing is case-insensitve
  1004. {tmpDir + pathSep + "mixed", []string{mixedCaseDirPath}},
  1005. }
  1006. for _, tc := range cases {
  1007. ret := browseFiles(tc.current, fs.FilesystemTypeBasic)
  1008. if !equalStrings(ret, tc.returns) {
  1009. t.Errorf("browseFiles(%q) => %q, expected %q", tc.current, ret, tc.returns)
  1010. }
  1011. }
  1012. }
  1013. func TestPrefixMatch(t *testing.T) {
  1014. t.Parallel()
  1015. cases := []struct {
  1016. s string
  1017. prefix string
  1018. expected int
  1019. }{
  1020. {"aaaA", "aaa", matchExact},
  1021. {"AAAX", "BBB", noMatch},
  1022. {"AAAX", "aAa", matchCaseIns},
  1023. {"äÜX", "äü", matchCaseIns},
  1024. }
  1025. for _, tc := range cases {
  1026. ret := checkPrefixMatch(tc.s, tc.prefix)
  1027. if ret != tc.expected {
  1028. t.Errorf("checkPrefixMatch(%q, %q) => %v, expected %v", tc.s, tc.prefix, ret, tc.expected)
  1029. }
  1030. }
  1031. }
  1032. func TestShouldRegenerateCertificate(t *testing.T) {
  1033. dir, err := ioutil.TempDir("", "syncthing-test")
  1034. if err != nil {
  1035. t.Fatal(err)
  1036. }
  1037. defer os.RemoveAll(dir)
  1038. // Self signed certificates expiring in less than a month are errored so we
  1039. // can regenerate in time.
  1040. crt, err := tlsutil.NewCertificate(filepath.Join(dir, "crt"), filepath.Join(dir, "key"), "foo.example.com", 29)
  1041. if err != nil {
  1042. t.Fatal(err)
  1043. }
  1044. if err := shouldRegenerateCertificate(crt); err == nil {
  1045. t.Error("expected expiry error")
  1046. }
  1047. // Certificates with at least 31 days of life left are fine.
  1048. crt, err = tlsutil.NewCertificate(filepath.Join(dir, "crt"), filepath.Join(dir, "key"), "foo.example.com", 31)
  1049. if err != nil {
  1050. t.Fatal(err)
  1051. }
  1052. if err := shouldRegenerateCertificate(crt); err != nil {
  1053. t.Error("expected no error:", err)
  1054. }
  1055. if runtime.GOOS == "darwin" {
  1056. // Certificates with too long an expiry time are not allowed on macOS
  1057. crt, err = tlsutil.NewCertificate(filepath.Join(dir, "crt"), filepath.Join(dir, "key"), "foo.example.com", 1000)
  1058. if err != nil {
  1059. t.Fatal(err)
  1060. }
  1061. if err := shouldRegenerateCertificate(crt); err == nil {
  1062. t.Error("expected expiry error")
  1063. }
  1064. }
  1065. }
  1066. func TestConfigChanges(t *testing.T) {
  1067. t.Parallel()
  1068. const testAPIKey = "foobarbaz"
  1069. cfg := config.Configuration{
  1070. GUI: config.GUIConfiguration{
  1071. RawAddress: "127.0.0.1:0",
  1072. RawUseTLS: false,
  1073. APIKey: testAPIKey,
  1074. },
  1075. }
  1076. tmpFile, err := ioutil.TempFile("", "syncthing-testConfig-")
  1077. if err != nil {
  1078. panic(err)
  1079. }
  1080. defer os.Remove(tmpFile.Name())
  1081. w := config.Wrap(tmpFile.Name(), cfg, events.NoopLogger)
  1082. tmpFile.Close()
  1083. baseURL, sup, err := startHTTP(w)
  1084. if err != nil {
  1085. t.Fatal("Unexpected error from getting base URL:", err)
  1086. }
  1087. defer sup.Stop()
  1088. cli := &http.Client{
  1089. Timeout: time.Second,
  1090. }
  1091. do := func(req *http.Request, status int) *http.Response {
  1092. t.Helper()
  1093. req.Header.Set("X-API-Key", testAPIKey)
  1094. resp, err := cli.Do(req)
  1095. if err != nil {
  1096. t.Fatal(err)
  1097. }
  1098. if resp.StatusCode != status {
  1099. t.Errorf("Expected status %v, got %v", status, resp.StatusCode)
  1100. }
  1101. return resp
  1102. }
  1103. mod := func(method, path string, data interface{}) {
  1104. t.Helper()
  1105. bs, err := json.Marshal(data)
  1106. if err != nil {
  1107. t.Fatal(err)
  1108. }
  1109. req, _ := http.NewRequest(method, baseURL+path, bytes.NewReader(bs))
  1110. do(req, http.StatusOK).Body.Close()
  1111. }
  1112. get := func(path string) *http.Response {
  1113. t.Helper()
  1114. req, _ := http.NewRequest(http.MethodGet, baseURL+path, nil)
  1115. return do(req, http.StatusOK)
  1116. }
  1117. dev1Path := "/rest/config/devices/" + dev1.String()
  1118. // Create device
  1119. mod(http.MethodPut, "/rest/config/devices", []config.DeviceConfiguration{{DeviceID: dev1}})
  1120. // Check its there
  1121. get(dev1Path).Body.Close()
  1122. // Modify just a single attribute
  1123. mod(http.MethodPatch, dev1Path, map[string]bool{"Paused": true})
  1124. // Check that attribute
  1125. resp := get(dev1Path)
  1126. var dev config.DeviceConfiguration
  1127. if err := unmarshalTo(resp.Body, &dev); err != nil {
  1128. t.Fatal(err)
  1129. }
  1130. if !dev.Paused {
  1131. t.Error("Expected device to be paused")
  1132. }
  1133. folder2Path := "/rest/config/folders/folder2"
  1134. // Create a folder and add another
  1135. mod(http.MethodPut, "/rest/config/folders", []config.FolderConfiguration{{ID: "folder1", Path: "folder1"}})
  1136. mod(http.MethodPut, folder2Path, config.FolderConfiguration{ID: "folder2", Path: "folder2"})
  1137. // Check they are there
  1138. get("/rest/config/folders/folder1").Body.Close()
  1139. get(folder2Path).Body.Close()
  1140. // Modify just a single attribute
  1141. mod(http.MethodPatch, folder2Path, map[string]bool{"Paused": true})
  1142. // Check that attribute
  1143. resp = get(folder2Path)
  1144. var folder config.FolderConfiguration
  1145. if err := unmarshalTo(resp.Body, &folder); err != nil {
  1146. t.Fatal(err)
  1147. }
  1148. if !dev.Paused {
  1149. t.Error("Expected folder to be paused")
  1150. }
  1151. // Delete folder2
  1152. req, _ := http.NewRequest(http.MethodDelete, baseURL+folder2Path, nil)
  1153. do(req, http.StatusOK)
  1154. // Check folder1 is still there and folder2 gone
  1155. get("/rest/config/folders/folder1").Body.Close()
  1156. req, _ = http.NewRequest(http.MethodGet, baseURL+folder2Path, nil)
  1157. do(req, http.StatusNotFound)
  1158. mod(http.MethodPatch, "/rest/config/options", map[string]int{"maxSendKbps": 50})
  1159. resp = get("/rest/config/options")
  1160. var opts config.OptionsConfiguration
  1161. if err := unmarshalTo(resp.Body, &opts); err != nil {
  1162. t.Fatal(err)
  1163. }
  1164. if opts.MaxSendKbps != 50 {
  1165. t.Error("Exepcted 50 for MaxSendKbps, got", opts.MaxSendKbps)
  1166. }
  1167. }
  1168. func equalStrings(a, b []string) bool {
  1169. if len(a) != len(b) {
  1170. return false
  1171. }
  1172. for i := range a {
  1173. if a[i] != b[i] {
  1174. return false
  1175. }
  1176. }
  1177. return true
  1178. }
  1179. // runningInContainer returns true if we are inside Docker or LXC. It might
  1180. // be prone to false negatives if things change in the future, but likely
  1181. // not false positives.
  1182. func runningInContainer() bool {
  1183. if runtime.GOOS != "linux" {
  1184. return false
  1185. }
  1186. bs, err := ioutil.ReadFile("/proc/1/cgroup")
  1187. if err != nil {
  1188. return false
  1189. }
  1190. if bytes.Contains(bs, []byte("/docker/")) {
  1191. return true
  1192. }
  1193. if bytes.Contains(bs, []byte("/lxc/")) {
  1194. return true
  1195. }
  1196. return false
  1197. }