api_test.go 35 KB

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