api_test.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423
  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. cfgCtx, cfgCancel := context.WithCancel(context.Background())
  1100. go w.Serve(cfgCtx)
  1101. defer cfgCancel()
  1102. baseURL, cancel, err := startHTTP(w)
  1103. if err != nil {
  1104. t.Fatal("Unexpected error from getting base URL:", err)
  1105. }
  1106. defer cancel()
  1107. cli := &http.Client{
  1108. Timeout: time.Minute,
  1109. }
  1110. do := func(req *http.Request, status int) *http.Response {
  1111. t.Helper()
  1112. req.Header.Set("X-API-Key", testAPIKey)
  1113. resp, err := cli.Do(req)
  1114. if err != nil {
  1115. t.Fatal(err)
  1116. }
  1117. if resp.StatusCode != status {
  1118. t.Errorf("Expected status %v, got %v", status, resp.StatusCode)
  1119. }
  1120. return resp
  1121. }
  1122. mod := func(method, path string, data interface{}) {
  1123. t.Helper()
  1124. bs, err := json.Marshal(data)
  1125. if err != nil {
  1126. t.Fatal(err)
  1127. }
  1128. req, _ := http.NewRequest(method, baseURL+path, bytes.NewReader(bs))
  1129. do(req, http.StatusOK).Body.Close()
  1130. }
  1131. get := func(path string) *http.Response {
  1132. t.Helper()
  1133. req, _ := http.NewRequest(http.MethodGet, baseURL+path, nil)
  1134. return do(req, http.StatusOK)
  1135. }
  1136. dev1Path := "/rest/config/devices/" + dev1.String()
  1137. // Create device
  1138. mod(http.MethodPut, "/rest/config/devices", []config.DeviceConfiguration{{DeviceID: dev1}})
  1139. // Check its there
  1140. get(dev1Path).Body.Close()
  1141. // Modify just a single attribute
  1142. mod(http.MethodPatch, dev1Path, map[string]bool{"Paused": true})
  1143. // Check that attribute
  1144. resp := get(dev1Path)
  1145. var dev config.DeviceConfiguration
  1146. if err := unmarshalTo(resp.Body, &dev); err != nil {
  1147. t.Fatal(err)
  1148. }
  1149. if !dev.Paused {
  1150. t.Error("Expected device to be paused")
  1151. }
  1152. folder2Path := "/rest/config/folders/folder2"
  1153. // Create a folder and add another
  1154. mod(http.MethodPut, "/rest/config/folders", []config.FolderConfiguration{{ID: "folder1", Path: "folder1"}})
  1155. mod(http.MethodPut, folder2Path, config.FolderConfiguration{ID: "folder2", Path: "folder2"})
  1156. // Check they are there
  1157. get("/rest/config/folders/folder1").Body.Close()
  1158. get(folder2Path).Body.Close()
  1159. // Modify just a single attribute
  1160. mod(http.MethodPatch, folder2Path, map[string]bool{"Paused": true})
  1161. // Check that attribute
  1162. resp = get(folder2Path)
  1163. var folder config.FolderConfiguration
  1164. if err := unmarshalTo(resp.Body, &folder); err != nil {
  1165. t.Fatal(err)
  1166. }
  1167. if !dev.Paused {
  1168. t.Error("Expected folder to be paused")
  1169. }
  1170. // Delete folder2
  1171. req, _ := http.NewRequest(http.MethodDelete, baseURL+folder2Path, nil)
  1172. do(req, http.StatusOK)
  1173. // Check folder1 is still there and folder2 gone
  1174. get("/rest/config/folders/folder1").Body.Close()
  1175. req, _ = http.NewRequest(http.MethodGet, baseURL+folder2Path, nil)
  1176. do(req, http.StatusNotFound)
  1177. mod(http.MethodPatch, "/rest/config/options", map[string]int{"maxSendKbps": 50})
  1178. resp = get("/rest/config/options")
  1179. var opts config.OptionsConfiguration
  1180. if err := unmarshalTo(resp.Body, &opts); err != nil {
  1181. t.Fatal(err)
  1182. }
  1183. if opts.MaxSendKbps != 50 {
  1184. t.Error("Exepcted 50 for MaxSendKbps, got", opts.MaxSendKbps)
  1185. }
  1186. }
  1187. func TestSanitizedHostname(t *testing.T) {
  1188. cases := []struct {
  1189. in, out string
  1190. }{
  1191. {"foo.BAR-baz", "foo.bar-baz"},
  1192. {"~.~-Min 1:a Räksmörgås-dator 😀😎 ~.~-", "min1araksmorgas-dator"},
  1193. {"Vicenç-PC", "vicenc-pc"},
  1194. {"~.~-~.~-", ""},
  1195. {"", ""},
  1196. }
  1197. for _, tc := range cases {
  1198. res, err := sanitizedHostname(tc.in)
  1199. if tc.out == "" && err == nil {
  1200. t.Errorf("%q should cause error", tc.in)
  1201. } else if res != tc.out {
  1202. t.Errorf("%q => %q, expected %q", tc.in, res, tc.out)
  1203. }
  1204. }
  1205. }
  1206. func equalStrings(a, b []string) bool {
  1207. if len(a) != len(b) {
  1208. return false
  1209. }
  1210. for i := range a {
  1211. if a[i] != b[i] {
  1212. return false
  1213. }
  1214. }
  1215. return true
  1216. }
  1217. // runningInContainer returns true if we are inside Docker or LXC. It might
  1218. // be prone to false negatives if things change in the future, but likely
  1219. // not false positives.
  1220. func runningInContainer() bool {
  1221. if runtime.GOOS != "linux" {
  1222. return false
  1223. }
  1224. bs, err := ioutil.ReadFile("/proc/1/cgroup")
  1225. if err != nil {
  1226. return false
  1227. }
  1228. if bytes.Contains(bs, []byte("/docker/")) {
  1229. return true
  1230. }
  1231. if bytes.Contains(bs, []byte("/lxc/")) {
  1232. return true
  1233. }
  1234. return false
  1235. }