api_test.go 35 KB

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