api_test.go 35 KB

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