api_test.go 35 KB

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