api_test.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  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. "context"
  11. "encoding/json"
  12. "fmt"
  13. "io"
  14. "io/ioutil"
  15. "net"
  16. "net/http"
  17. "net/http/httptest"
  18. "os"
  19. "path/filepath"
  20. "runtime"
  21. "strconv"
  22. "strings"
  23. "testing"
  24. "time"
  25. "github.com/d4l3k/messagediff"
  26. "github.com/syncthing/syncthing/lib/assets"
  27. "github.com/syncthing/syncthing/lib/config"
  28. "github.com/syncthing/syncthing/lib/events"
  29. "github.com/syncthing/syncthing/lib/fs"
  30. "github.com/syncthing/syncthing/lib/locations"
  31. "github.com/syncthing/syncthing/lib/protocol"
  32. "github.com/syncthing/syncthing/lib/svcutil"
  33. "github.com/syncthing/syncthing/lib/sync"
  34. "github.com/syncthing/syncthing/lib/tlsutil"
  35. "github.com/syncthing/syncthing/lib/ur"
  36. "github.com/thejerf/suture/v4"
  37. )
  38. var (
  39. confDir = filepath.Join("testdata", "config")
  40. token = filepath.Join(confDir, "csrftokens.txt")
  41. dev1 protocol.DeviceID
  42. )
  43. func init() {
  44. dev1, _ = protocol.DeviceIDFromString("AIR6LPZ-7K4PTTV-UXQSMUU-CPQ5YWH-OEDFIIQ-JUG777G-2YQXXR5-YD6AWQR")
  45. }
  46. func TestMain(m *testing.M) {
  47. orig := locations.GetBaseDir(locations.ConfigBaseDir)
  48. locations.SetBaseDir(locations.ConfigBaseDir, confDir)
  49. exitCode := m.Run()
  50. locations.SetBaseDir(locations.ConfigBaseDir, orig)
  51. os.Exit(exitCode)
  52. }
  53. func TestCSRFToken(t *testing.T) {
  54. t.Parallel()
  55. max := 250
  56. int := 5
  57. if testing.Short() {
  58. max = 20
  59. int = 2
  60. }
  61. m := newCsrfManager("unique", "prefix", config.GUIConfiguration{}, nil, "")
  62. t1 := m.newToken()
  63. t2 := m.newToken()
  64. t3 := m.newToken()
  65. if !m.validToken(t3) {
  66. t.Fatal("t3 should be valid")
  67. }
  68. for i := 0; i < max; i++ {
  69. if i%int == 0 {
  70. // t1 and t2 should remain valid by virtue of us checking them now
  71. // and then.
  72. if !m.validToken(t1) {
  73. t.Fatal("t1 should be valid at iteration", i)
  74. }
  75. if !m.validToken(t2) {
  76. t.Fatal("t2 should be valid at iteration", i)
  77. }
  78. }
  79. // The newly generated token is always valid
  80. t4 := m.newToken()
  81. if !m.validToken(t4) {
  82. t.Fatal("t4 should be valid at iteration", i)
  83. }
  84. }
  85. if m.validToken(t3) {
  86. t.Fatal("t3 should have expired by now")
  87. }
  88. }
  89. func TestStopAfterBrokenConfig(t *testing.T) {
  90. t.Parallel()
  91. cfg := config.Configuration{
  92. GUI: config.GUIConfiguration{
  93. RawAddress: "127.0.0.1:0",
  94. RawUseTLS: false,
  95. },
  96. }
  97. w := config.Wrap("/dev/null", cfg, protocol.LocalDeviceID, events.NoopLogger)
  98. srv := New(protocol.LocalDeviceID, w, "", "syncthing", nil, nil, nil, events.NoopLogger, nil, nil, nil, nil, nil, nil, false).(*service)
  99. defer os.Remove(token)
  100. srv.started = make(chan string)
  101. sup := suture.New("test", svcutil.SpecWithDebugLogger(l))
  102. sup.Add(srv)
  103. ctx, cancel := context.WithCancel(context.Background())
  104. sup.ServeBackground(ctx)
  105. <-srv.started
  106. // Service is now running, listening on a random port on localhost. Now we
  107. // request a config change to a completely invalid listen address. The
  108. // commit will fail and the service will be in a broken state.
  109. newCfg := config.Configuration{
  110. GUI: config.GUIConfiguration{
  111. RawAddress: "totally not a valid address",
  112. RawUseTLS: false,
  113. },
  114. }
  115. if err := srv.VerifyConfiguration(cfg, newCfg); err == nil {
  116. t.Fatal("Verify config should have failed")
  117. }
  118. cancel()
  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, cancel, err := startHTTP(cfg)
  209. if err != nil {
  210. t.Fatal(err)
  211. }
  212. defer cancel()
  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, cancel, err := startHTTP(cfg)
  463. if err != nil {
  464. t.Fatal(err)
  465. }
  466. defer cancel()
  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, context.CancelFunc, 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, 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. ctx, cancel := context.WithCancel(context.Background())
  534. supervisor.ServeBackground(ctx)
  535. // Make sure the API service is listening, and get the URL to use.
  536. addr := <-addrChan
  537. tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
  538. if err != nil {
  539. cancel()
  540. return "", cancel, fmt.Errorf("weird address from API service: %w", err)
  541. }
  542. host, _, _ := net.SplitHostPort(cfg.GUI().RawAddress)
  543. if host == "" || host == "0.0.0.0" {
  544. host = "127.0.0.1"
  545. }
  546. baseURL := fmt.Sprintf("http://%s", net.JoinHostPort(host, strconv.Itoa(tcpAddr.Port)))
  547. return baseURL, cancel, nil
  548. }
  549. func TestCSRFRequired(t *testing.T) {
  550. t.Parallel()
  551. const testAPIKey = "foobarbaz"
  552. cfg := new(mockedConfig)
  553. cfg.gui.APIKey = testAPIKey
  554. baseURL, cancel, err := startHTTP(cfg)
  555. if err != nil {
  556. t.Fatal("Unexpected error from getting base URL:", err)
  557. }
  558. defer cancel()
  559. cli := &http.Client{
  560. Timeout: time.Minute,
  561. }
  562. // Getting the base URL (i.e. "/") should succeed.
  563. resp, err := cli.Get(baseURL)
  564. if err != nil {
  565. t.Fatal("Unexpected error from getting base URL:", err)
  566. }
  567. resp.Body.Close()
  568. if resp.StatusCode != http.StatusOK {
  569. t.Fatal("Getting base URL should succeed, not", resp.Status)
  570. }
  571. // Find the returned CSRF token for future use
  572. var csrfTokenName, csrfTokenValue string
  573. for _, cookie := range resp.Cookies() {
  574. if strings.HasPrefix(cookie.Name, "CSRF-Token") {
  575. csrfTokenName = cookie.Name
  576. csrfTokenValue = cookie.Value
  577. break
  578. }
  579. }
  580. // Calling on /rest without a token should fail
  581. resp, err = cli.Get(baseURL + "/rest/system/config")
  582. if err != nil {
  583. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  584. }
  585. resp.Body.Close()
  586. if resp.StatusCode != http.StatusForbidden {
  587. t.Fatal("Getting /rest/system/config without CSRF token should fail, not", resp.Status)
  588. }
  589. // Calling on /rest with a token should succeed
  590. req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
  591. req.Header.Set("X-"+csrfTokenName, csrfTokenValue)
  592. resp, err = cli.Do(req)
  593. if err != nil {
  594. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  595. }
  596. resp.Body.Close()
  597. if resp.StatusCode != http.StatusOK {
  598. t.Fatal("Getting /rest/system/config with CSRF token should succeed, not", resp.Status)
  599. }
  600. // Calling on /rest with the API key should succeed
  601. req, _ = http.NewRequest("GET", baseURL+"/rest/system/config", nil)
  602. req.Header.Set("X-API-Key", testAPIKey)
  603. resp, err = cli.Do(req)
  604. if err != nil {
  605. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  606. }
  607. resp.Body.Close()
  608. if resp.StatusCode != http.StatusOK {
  609. t.Fatal("Getting /rest/system/config with API key should succeed, not", resp.Status)
  610. }
  611. }
  612. func TestRandomString(t *testing.T) {
  613. t.Parallel()
  614. const testAPIKey = "foobarbaz"
  615. cfg := new(mockedConfig)
  616. cfg.gui.APIKey = testAPIKey
  617. baseURL, cancel, err := startHTTP(cfg)
  618. if err != nil {
  619. t.Fatal(err)
  620. }
  621. defer cancel()
  622. cli := &http.Client{
  623. Timeout: time.Second,
  624. }
  625. // The default should be to return a 32 character random string
  626. for _, url := range []string{"/rest/svc/random/string", "/rest/svc/random/string?length=-1", "/rest/svc/random/string?length=yo"} {
  627. req, _ := http.NewRequest("GET", baseURL+url, nil)
  628. req.Header.Set("X-API-Key", testAPIKey)
  629. resp, err := cli.Do(req)
  630. if err != nil {
  631. t.Fatal(err)
  632. }
  633. var res map[string]string
  634. if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
  635. t.Fatal(err)
  636. }
  637. if len(res["random"]) != 32 {
  638. t.Errorf("Expected 32 random characters, got %q of length %d", res["random"], len(res["random"]))
  639. }
  640. }
  641. // We can ask for a different length if we like
  642. req, _ := http.NewRequest("GET", baseURL+"/rest/svc/random/string?length=27", nil)
  643. req.Header.Set("X-API-Key", testAPIKey)
  644. resp, err := cli.Do(req)
  645. if err != nil {
  646. t.Fatal(err)
  647. }
  648. var res map[string]string
  649. if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
  650. t.Fatal(err)
  651. }
  652. if len(res["random"]) != 27 {
  653. t.Errorf("Expected 27 random characters, got %q of length %d", res["random"], len(res["random"]))
  654. }
  655. }
  656. func TestConfigPostOK(t *testing.T) {
  657. t.Parallel()
  658. cfg := bytes.NewBuffer([]byte(`{
  659. "version": 15,
  660. "folders": [
  661. {
  662. "id": "foo",
  663. "path": "TestConfigPostOK"
  664. }
  665. ]
  666. }`))
  667. resp, err := testConfigPost(cfg)
  668. if err != nil {
  669. t.Fatal(err)
  670. }
  671. if resp.StatusCode != http.StatusOK {
  672. t.Error("Expected 200 OK, not", resp.Status)
  673. }
  674. os.RemoveAll("TestConfigPostOK")
  675. }
  676. func TestConfigPostDupFolder(t *testing.T) {
  677. t.Parallel()
  678. cfg := bytes.NewBuffer([]byte(`{
  679. "version": 15,
  680. "folders": [
  681. {"id": "foo"},
  682. {"id": "foo"}
  683. ]
  684. }`))
  685. resp, err := testConfigPost(cfg)
  686. if err != nil {
  687. t.Fatal(err)
  688. }
  689. if resp.StatusCode != http.StatusBadRequest {
  690. t.Error("Expected 400 Bad Request, not", resp.Status)
  691. }
  692. }
  693. func testConfigPost(data io.Reader) (*http.Response, error) {
  694. const testAPIKey = "foobarbaz"
  695. cfg := new(mockedConfig)
  696. cfg.gui.APIKey = testAPIKey
  697. baseURL, cancel, err := startHTTP(cfg)
  698. if err != nil {
  699. return nil, err
  700. }
  701. defer cancel()
  702. cli := &http.Client{
  703. Timeout: time.Second,
  704. }
  705. req, _ := http.NewRequest("POST", baseURL+"/rest/system/config", data)
  706. req.Header.Set("X-API-Key", testAPIKey)
  707. return cli.Do(req)
  708. }
  709. func TestHostCheck(t *testing.T) {
  710. t.Parallel()
  711. // An API service bound to localhost should reject non-localhost host Headers
  712. cfg := new(mockedConfig)
  713. cfg.gui.RawAddress = "127.0.0.1:0"
  714. baseURL, cancel, err := startHTTP(cfg)
  715. if err != nil {
  716. t.Fatal(err)
  717. }
  718. defer cancel()
  719. // A normal HTTP get to the localhost-bound service should succeed
  720. resp, err := http.Get(baseURL)
  721. if err != nil {
  722. t.Fatal(err)
  723. }
  724. resp.Body.Close()
  725. if resp.StatusCode != http.StatusOK {
  726. t.Error("Regular HTTP get: expected 200 OK, not", resp.Status)
  727. }
  728. // A request with a suspicious Host header should fail
  729. req, _ := http.NewRequest("GET", baseURL, nil)
  730. req.Host = "example.com"
  731. resp, err = http.DefaultClient.Do(req)
  732. if err != nil {
  733. t.Fatal(err)
  734. }
  735. resp.Body.Close()
  736. if resp.StatusCode != http.StatusForbidden {
  737. t.Error("Suspicious Host header: expected 403 Forbidden, not", resp.Status)
  738. }
  739. // A request with an explicit "localhost:8384" Host header should pass
  740. req, _ = http.NewRequest("GET", baseURL, nil)
  741. req.Host = "localhost:8384"
  742. resp, err = http.DefaultClient.Do(req)
  743. if err != nil {
  744. t.Fatal(err)
  745. }
  746. resp.Body.Close()
  747. if resp.StatusCode != http.StatusOK {
  748. t.Error("Explicit localhost:8384: expected 200 OK, not", resp.Status)
  749. }
  750. // A request with an explicit "localhost" Host header (no port) should pass
  751. req, _ = http.NewRequest("GET", baseURL, nil)
  752. req.Host = "localhost"
  753. resp, err = http.DefaultClient.Do(req)
  754. if err != nil {
  755. t.Fatal(err)
  756. }
  757. resp.Body.Close()
  758. if resp.StatusCode != http.StatusOK {
  759. t.Error("Explicit localhost: expected 200 OK, not", resp.Status)
  760. }
  761. // A server with InsecureSkipHostCheck set behaves differently
  762. cfg = new(mockedConfig)
  763. cfg.gui.RawAddress = "127.0.0.1:0"
  764. cfg.gui.InsecureSkipHostCheck = true
  765. baseURL, cancel, err = startHTTP(cfg)
  766. if err != nil {
  767. t.Fatal(err)
  768. }
  769. defer cancel()
  770. // A request with a suspicious Host header should be allowed
  771. req, _ = http.NewRequest("GET", baseURL, nil)
  772. req.Host = "example.com"
  773. resp, err = http.DefaultClient.Do(req)
  774. if err != nil {
  775. t.Fatal(err)
  776. }
  777. resp.Body.Close()
  778. if resp.StatusCode != http.StatusOK {
  779. t.Error("Incorrect host header, check disabled: expected 200 OK, not", resp.Status)
  780. }
  781. // A server bound to a wildcard address also doesn't do the check
  782. cfg = new(mockedConfig)
  783. cfg.gui.RawAddress = "0.0.0.0:0"
  784. cfg.gui.InsecureSkipHostCheck = true
  785. baseURL, cancel, err = startHTTP(cfg)
  786. if err != nil {
  787. t.Fatal(err)
  788. }
  789. defer cancel()
  790. // A request with a suspicious Host header should be allowed
  791. req, _ = http.NewRequest("GET", baseURL, nil)
  792. req.Host = "example.com"
  793. resp, err = http.DefaultClient.Do(req)
  794. if err != nil {
  795. t.Fatal(err)
  796. }
  797. resp.Body.Close()
  798. if resp.StatusCode != http.StatusOK {
  799. t.Error("Incorrect host header, wildcard bound: expected 200 OK, not", resp.Status)
  800. }
  801. // This should all work over IPv6 as well
  802. if runningInContainer() {
  803. // Working IPv6 in Docker can't be taken for granted.
  804. return
  805. }
  806. cfg = new(mockedConfig)
  807. cfg.gui.RawAddress = "[::1]:0"
  808. baseURL, cancel, err = startHTTP(cfg)
  809. if err != nil {
  810. t.Fatal(err)
  811. }
  812. defer cancel()
  813. // A normal HTTP get to the localhost-bound service should succeed
  814. resp, err = http.Get(baseURL)
  815. if err != nil {
  816. t.Fatal(err)
  817. }
  818. resp.Body.Close()
  819. if resp.StatusCode != http.StatusOK {
  820. t.Error("Regular HTTP get (IPv6): expected 200 OK, not", resp.Status)
  821. }
  822. // A request with a suspicious Host header should fail
  823. req, _ = http.NewRequest("GET", baseURL, nil)
  824. req.Host = "example.com"
  825. resp, err = http.DefaultClient.Do(req)
  826. if err != nil {
  827. t.Fatal(err)
  828. }
  829. resp.Body.Close()
  830. if resp.StatusCode != http.StatusForbidden {
  831. t.Error("Suspicious Host header (IPv6): expected 403 Forbidden, not", resp.Status)
  832. }
  833. // A request with an explicit "localhost:8384" Host header should pass
  834. req, _ = http.NewRequest("GET", baseURL, nil)
  835. req.Host = "localhost:8384"
  836. resp, err = http.DefaultClient.Do(req)
  837. if err != nil {
  838. t.Fatal(err)
  839. }
  840. resp.Body.Close()
  841. if resp.StatusCode != http.StatusOK {
  842. t.Error("Explicit localhost:8384 (IPv6): expected 200 OK, not", resp.Status)
  843. }
  844. }
  845. func TestAddressIsLocalhost(t *testing.T) {
  846. t.Parallel()
  847. testcases := []struct {
  848. address string
  849. result bool
  850. }{
  851. // These are all valid localhost addresses
  852. {"localhost", true},
  853. {"LOCALHOST", true},
  854. {"localhost.", true},
  855. {"::1", true},
  856. {"127.0.0.1", true},
  857. {"127.23.45.56", true},
  858. {"localhost:8080", true},
  859. {"LOCALHOST:8000", true},
  860. {"localhost.:8080", true},
  861. {"[::1]:8080", true},
  862. {"127.0.0.1:8080", true},
  863. {"127.23.45.56:8080", true},
  864. // These are all non-localhost addresses
  865. {"example.com", false},
  866. {"example.com:8080", false},
  867. {"localhost.com", false},
  868. {"localhost.com:8080", false},
  869. {"www.localhost", false},
  870. {"www.localhost:8080", false},
  871. {"192.0.2.10", false},
  872. {"192.0.2.10:8080", false},
  873. {"0.0.0.0", false},
  874. {"0.0.0.0:8080", false},
  875. {"::", false},
  876. {"[::]:8080", false},
  877. {":8080", false},
  878. }
  879. for _, tc := range testcases {
  880. result := addressIsLocalhost(tc.address)
  881. if result != tc.result {
  882. t.Errorf("addressIsLocalhost(%q)=%v, expected %v", tc.address, result, tc.result)
  883. }
  884. }
  885. }
  886. func TestAccessControlAllowOriginHeader(t *testing.T) {
  887. t.Parallel()
  888. const testAPIKey = "foobarbaz"
  889. cfg := new(mockedConfig)
  890. cfg.gui.APIKey = testAPIKey
  891. baseURL, cancel, err := startHTTP(cfg)
  892. if err != nil {
  893. t.Fatal(err)
  894. }
  895. defer cancel()
  896. cli := &http.Client{
  897. Timeout: time.Second,
  898. }
  899. req, _ := http.NewRequest("GET", baseURL+"/rest/system/status", nil)
  900. req.Header.Set("X-API-Key", testAPIKey)
  901. resp, err := cli.Do(req)
  902. if err != nil {
  903. t.Fatal(err)
  904. }
  905. resp.Body.Close()
  906. if resp.StatusCode != http.StatusOK {
  907. t.Fatal("GET on /rest/system/status should succeed, not", resp.Status)
  908. }
  909. if resp.Header.Get("Access-Control-Allow-Origin") != "*" {
  910. t.Fatal("GET on /rest/system/status should return a 'Access-Control-Allow-Origin: *' header")
  911. }
  912. }
  913. func TestOptionsRequest(t *testing.T) {
  914. t.Parallel()
  915. const testAPIKey = "foobarbaz"
  916. cfg := new(mockedConfig)
  917. cfg.gui.APIKey = testAPIKey
  918. baseURL, cancel, err := startHTTP(cfg)
  919. if err != nil {
  920. t.Fatal(err)
  921. }
  922. defer cancel()
  923. cli := &http.Client{
  924. Timeout: time.Second,
  925. }
  926. req, _ := http.NewRequest("OPTIONS", baseURL+"/rest/system/status", nil)
  927. resp, err := cli.Do(req)
  928. if err != nil {
  929. t.Fatal(err)
  930. }
  931. resp.Body.Close()
  932. if resp.StatusCode != http.StatusNoContent {
  933. t.Fatal("OPTIONS on /rest/system/status should succeed, not", resp.Status)
  934. }
  935. if resp.Header.Get("Access-Control-Allow-Origin") != "*" {
  936. t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Origin: *' header")
  937. }
  938. if resp.Header.Get("Access-Control-Allow-Methods") != "GET, POST, PUT, PATCH, DELETE, OPTIONS" {
  939. t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS' header")
  940. }
  941. if resp.Header.Get("Access-Control-Allow-Headers") != "Content-Type, X-API-Key" {
  942. t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Headers: Content-Type, X-API-KEY' header")
  943. }
  944. }
  945. func TestEventMasks(t *testing.T) {
  946. t.Parallel()
  947. cfg := new(mockedConfig)
  948. defSub := new(mockedEventSub)
  949. diskSub := new(mockedEventSub)
  950. svc := New(protocol.LocalDeviceID, cfg, "", "syncthing", nil, defSub, diskSub, events.NoopLogger, nil, nil, nil, nil, nil, nil, false).(*service)
  951. defer os.Remove(token)
  952. if mask := svc.getEventMask(""); mask != DefaultEventMask {
  953. t.Errorf("incorrect default mask %x != %x", int64(mask), int64(DefaultEventMask))
  954. }
  955. expected := events.FolderSummary | events.LocalChangeDetected
  956. if mask := svc.getEventMask("FolderSummary,LocalChangeDetected"); mask != expected {
  957. t.Errorf("incorrect parsed mask %x != %x", int64(mask), int64(expected))
  958. }
  959. expected = 0
  960. if mask := svc.getEventMask("WeirdEvent,something else that doesn't exist"); mask != expected {
  961. t.Errorf("incorrect parsed mask %x != %x", int64(mask), int64(expected))
  962. }
  963. if res := svc.getEventSub(DefaultEventMask); res != defSub {
  964. t.Errorf("should have returned the given default event sub")
  965. }
  966. if res := svc.getEventSub(DiskEventMask); res != diskSub {
  967. t.Errorf("should have returned the given disk event sub")
  968. }
  969. if res := svc.getEventSub(events.LocalIndexUpdated); res == nil || res == defSub || res == diskSub {
  970. t.Errorf("should have returned a valid, non-default event sub")
  971. }
  972. }
  973. func TestBrowse(t *testing.T) {
  974. t.Parallel()
  975. pathSep := string(os.PathSeparator)
  976. tmpDir, err := ioutil.TempDir("", "syncthing")
  977. if err != nil {
  978. t.Fatal(err)
  979. }
  980. defer os.RemoveAll(tmpDir)
  981. if err := os.Mkdir(filepath.Join(tmpDir, "dir"), 0755); err != nil {
  982. t.Fatal(err)
  983. }
  984. if err := ioutil.WriteFile(filepath.Join(tmpDir, "file"), []byte("hello"), 0644); err != nil {
  985. t.Fatal(err)
  986. }
  987. if err := os.Mkdir(filepath.Join(tmpDir, "MiXEDCase"), 0755); err != nil {
  988. t.Fatal(err)
  989. }
  990. // We expect completion to return the full path to the completed
  991. // directory, with an ending slash.
  992. dirPath := filepath.Join(tmpDir, "dir") + pathSep
  993. mixedCaseDirPath := filepath.Join(tmpDir, "MiXEDCase") + pathSep
  994. cases := []struct {
  995. current string
  996. returns []string
  997. }{
  998. // The direcotory without slash is completed to one with slash.
  999. {tmpDir, []string{tmpDir + pathSep}},
  1000. // With slash it's completed to its contents.
  1001. // Dirs are given pathSeps.
  1002. // Files are not returned.
  1003. {tmpDir + pathSep, []string{mixedCaseDirPath, dirPath}},
  1004. // Globbing is automatic based on prefix.
  1005. {tmpDir + pathSep + "d", []string{dirPath}},
  1006. {tmpDir + pathSep + "di", []string{dirPath}},
  1007. {tmpDir + pathSep + "dir", []string{dirPath}},
  1008. {tmpDir + pathSep + "f", nil},
  1009. {tmpDir + pathSep + "q", nil},
  1010. // Globbing is case-insensitve
  1011. {tmpDir + pathSep + "mixed", []string{mixedCaseDirPath}},
  1012. }
  1013. for _, tc := range cases {
  1014. ret := browseFiles(tc.current, fs.FilesystemTypeBasic)
  1015. if !equalStrings(ret, tc.returns) {
  1016. t.Errorf("browseFiles(%q) => %q, expected %q", tc.current, ret, tc.returns)
  1017. }
  1018. }
  1019. }
  1020. func TestPrefixMatch(t *testing.T) {
  1021. t.Parallel()
  1022. cases := []struct {
  1023. s string
  1024. prefix string
  1025. expected int
  1026. }{
  1027. {"aaaA", "aaa", matchExact},
  1028. {"AAAX", "BBB", noMatch},
  1029. {"AAAX", "aAa", matchCaseIns},
  1030. {"äÜX", "äü", matchCaseIns},
  1031. }
  1032. for _, tc := range cases {
  1033. ret := checkPrefixMatch(tc.s, tc.prefix)
  1034. if ret != tc.expected {
  1035. t.Errorf("checkPrefixMatch(%q, %q) => %v, expected %v", tc.s, tc.prefix, ret, tc.expected)
  1036. }
  1037. }
  1038. }
  1039. func TestShouldRegenerateCertificate(t *testing.T) {
  1040. dir, err := ioutil.TempDir("", "syncthing-test")
  1041. if err != nil {
  1042. t.Fatal(err)
  1043. }
  1044. defer os.RemoveAll(dir)
  1045. // Self signed certificates expiring in less than a month are errored so we
  1046. // can regenerate in time.
  1047. crt, err := tlsutil.NewCertificate(filepath.Join(dir, "crt"), filepath.Join(dir, "key"), "foo.example.com", 29)
  1048. if err != nil {
  1049. t.Fatal(err)
  1050. }
  1051. if err := shouldRegenerateCertificate(crt); err == nil {
  1052. t.Error("expected expiry error")
  1053. }
  1054. // Certificates with at least 31 days of life left are fine.
  1055. crt, err = tlsutil.NewCertificate(filepath.Join(dir, "crt"), filepath.Join(dir, "key"), "foo.example.com", 31)
  1056. if err != nil {
  1057. t.Fatal(err)
  1058. }
  1059. if err := shouldRegenerateCertificate(crt); err != nil {
  1060. t.Error("expected no error:", err)
  1061. }
  1062. if runtime.GOOS == "darwin" {
  1063. // Certificates with too long an expiry time are not allowed on macOS
  1064. crt, err = tlsutil.NewCertificate(filepath.Join(dir, "crt"), filepath.Join(dir, "key"), "foo.example.com", 1000)
  1065. if err != nil {
  1066. t.Fatal(err)
  1067. }
  1068. if err := shouldRegenerateCertificate(crt); err == nil {
  1069. t.Error("expected expiry error")
  1070. }
  1071. }
  1072. }
  1073. func TestConfigChanges(t *testing.T) {
  1074. t.Parallel()
  1075. const testAPIKey = "foobarbaz"
  1076. cfg := config.Configuration{
  1077. GUI: config.GUIConfiguration{
  1078. RawAddress: "127.0.0.1:0",
  1079. RawUseTLS: false,
  1080. APIKey: testAPIKey,
  1081. },
  1082. }
  1083. tmpFile, err := ioutil.TempFile("", "syncthing-testConfig-")
  1084. if err != nil {
  1085. panic(err)
  1086. }
  1087. defer os.Remove(tmpFile.Name())
  1088. w := config.Wrap(tmpFile.Name(), cfg, protocol.LocalDeviceID, events.NoopLogger)
  1089. tmpFile.Close()
  1090. if cfgService, ok := w.(suture.Service); ok {
  1091. cfgCtx, cfgCancel := context.WithCancel(context.Background())
  1092. go cfgService.Serve(cfgCtx)
  1093. defer cfgCancel()
  1094. }
  1095. baseURL, cancel, err := startHTTP(w)
  1096. if err != nil {
  1097. t.Fatal("Unexpected error from getting base URL:", err)
  1098. }
  1099. defer cancel()
  1100. cli := &http.Client{
  1101. Timeout: time.Second,
  1102. }
  1103. do := func(req *http.Request, status int) *http.Response {
  1104. t.Helper()
  1105. req.Header.Set("X-API-Key", testAPIKey)
  1106. resp, err := cli.Do(req)
  1107. if err != nil {
  1108. t.Fatal(err)
  1109. }
  1110. if resp.StatusCode != status {
  1111. t.Errorf("Expected status %v, got %v", status, resp.StatusCode)
  1112. }
  1113. return resp
  1114. }
  1115. mod := func(method, path string, data interface{}) {
  1116. t.Helper()
  1117. bs, err := json.Marshal(data)
  1118. if err != nil {
  1119. t.Fatal(err)
  1120. }
  1121. req, _ := http.NewRequest(method, baseURL+path, bytes.NewReader(bs))
  1122. do(req, http.StatusOK).Body.Close()
  1123. }
  1124. get := func(path string) *http.Response {
  1125. t.Helper()
  1126. req, _ := http.NewRequest(http.MethodGet, baseURL+path, nil)
  1127. return do(req, http.StatusOK)
  1128. }
  1129. dev1Path := "/rest/config/devices/" + dev1.String()
  1130. // Create device
  1131. mod(http.MethodPut, "/rest/config/devices", []config.DeviceConfiguration{{DeviceID: dev1}})
  1132. // Check its there
  1133. get(dev1Path).Body.Close()
  1134. // Modify just a single attribute
  1135. mod(http.MethodPatch, dev1Path, map[string]bool{"Paused": true})
  1136. // Check that attribute
  1137. resp := get(dev1Path)
  1138. var dev config.DeviceConfiguration
  1139. if err := unmarshalTo(resp.Body, &dev); err != nil {
  1140. t.Fatal(err)
  1141. }
  1142. if !dev.Paused {
  1143. t.Error("Expected device to be paused")
  1144. }
  1145. folder2Path := "/rest/config/folders/folder2"
  1146. // Create a folder and add another
  1147. mod(http.MethodPut, "/rest/config/folders", []config.FolderConfiguration{{ID: "folder1", Path: "folder1"}})
  1148. mod(http.MethodPut, folder2Path, config.FolderConfiguration{ID: "folder2", Path: "folder2"})
  1149. // Check they are there
  1150. get("/rest/config/folders/folder1").Body.Close()
  1151. get(folder2Path).Body.Close()
  1152. // Modify just a single attribute
  1153. mod(http.MethodPatch, folder2Path, map[string]bool{"Paused": true})
  1154. // Check that attribute
  1155. resp = get(folder2Path)
  1156. var folder config.FolderConfiguration
  1157. if err := unmarshalTo(resp.Body, &folder); err != nil {
  1158. t.Fatal(err)
  1159. }
  1160. if !dev.Paused {
  1161. t.Error("Expected folder to be paused")
  1162. }
  1163. // Delete folder2
  1164. req, _ := http.NewRequest(http.MethodDelete, baseURL+folder2Path, nil)
  1165. do(req, http.StatusOK)
  1166. // Check folder1 is still there and folder2 gone
  1167. get("/rest/config/folders/folder1").Body.Close()
  1168. req, _ = http.NewRequest(http.MethodGet, baseURL+folder2Path, nil)
  1169. do(req, http.StatusNotFound)
  1170. mod(http.MethodPatch, "/rest/config/options", map[string]int{"maxSendKbps": 50})
  1171. resp = get("/rest/config/options")
  1172. var opts config.OptionsConfiguration
  1173. if err := unmarshalTo(resp.Body, &opts); err != nil {
  1174. t.Fatal(err)
  1175. }
  1176. if opts.MaxSendKbps != 50 {
  1177. t.Error("Exepcted 50 for MaxSendKbps, got", opts.MaxSendKbps)
  1178. }
  1179. }
  1180. func equalStrings(a, b []string) bool {
  1181. if len(a) != len(b) {
  1182. return false
  1183. }
  1184. for i := range a {
  1185. if a[i] != b[i] {
  1186. return false
  1187. }
  1188. }
  1189. return true
  1190. }
  1191. // runningInContainer returns true if we are inside Docker or LXC. It might
  1192. // be prone to false negatives if things change in the future, but likely
  1193. // not false positives.
  1194. func runningInContainer() bool {
  1195. if runtime.GOOS != "linux" {
  1196. return false
  1197. }
  1198. bs, err := ioutil.ReadFile("/proc/1/cgroup")
  1199. if err != nil {
  1200. return false
  1201. }
  1202. if bytes.Contains(bs, []byte("/docker/")) {
  1203. return true
  1204. }
  1205. if bytes.Contains(bs, []byte("/lxc/")) {
  1206. return true
  1207. }
  1208. return false
  1209. }