api_test.go 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412
  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. // Should not be parallelized, as that just causes timeouts eventually with more test-cases
  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 := t.TempDir()
  995. if err := os.Mkdir(filepath.Join(tmpDir, "dir"), 0755); err != nil {
  996. t.Fatal(err)
  997. }
  998. if err := os.WriteFile(filepath.Join(tmpDir, "file"), []byte("hello"), 0644); err != nil {
  999. t.Fatal(err)
  1000. }
  1001. if err := os.Mkdir(filepath.Join(tmpDir, "MiXEDCase"), 0755); err != nil {
  1002. t.Fatal(err)
  1003. }
  1004. // We expect completion to return the full path to the completed
  1005. // directory, with an ending slash.
  1006. dirPath := filepath.Join(tmpDir, "dir") + pathSep
  1007. mixedCaseDirPath := filepath.Join(tmpDir, "MiXEDCase") + pathSep
  1008. cases := []struct {
  1009. current string
  1010. returns []string
  1011. }{
  1012. // The direcotory without slash is completed to one with slash.
  1013. {tmpDir, []string{tmpDir + pathSep}},
  1014. // With slash it's completed to its contents.
  1015. // Dirs are given pathSeps.
  1016. // Files are not returned.
  1017. {tmpDir + pathSep, []string{mixedCaseDirPath, dirPath}},
  1018. // Globbing is automatic based on prefix.
  1019. {tmpDir + pathSep + "d", []string{dirPath}},
  1020. {tmpDir + pathSep + "di", []string{dirPath}},
  1021. {tmpDir + pathSep + "dir", []string{dirPath}},
  1022. {tmpDir + pathSep + "f", nil},
  1023. {tmpDir + pathSep + "q", nil},
  1024. // Globbing is case-insensitve
  1025. {tmpDir + pathSep + "mixed", []string{mixedCaseDirPath}},
  1026. }
  1027. for _, tc := range cases {
  1028. ret := browseFiles(tc.current, fs.FilesystemTypeBasic)
  1029. if !util.EqualStrings(ret, tc.returns) {
  1030. t.Errorf("browseFiles(%q) => %q, expected %q", tc.current, ret, tc.returns)
  1031. }
  1032. }
  1033. }
  1034. func TestPrefixMatch(t *testing.T) {
  1035. t.Parallel()
  1036. cases := []struct {
  1037. s string
  1038. prefix string
  1039. expected int
  1040. }{
  1041. {"aaaA", "aaa", matchExact},
  1042. {"AAAX", "BBB", noMatch},
  1043. {"AAAX", "aAa", matchCaseIns},
  1044. {"äÜX", "äü", matchCaseIns},
  1045. }
  1046. for _, tc := range cases {
  1047. ret := checkPrefixMatch(tc.s, tc.prefix)
  1048. if ret != tc.expected {
  1049. t.Errorf("checkPrefixMatch(%q, %q) => %v, expected %v", tc.s, tc.prefix, ret, tc.expected)
  1050. }
  1051. }
  1052. }
  1053. func TestShouldRegenerateCertificate(t *testing.T) {
  1054. // Self signed certificates expiring in less than a month are errored so we
  1055. // can regenerate in time.
  1056. crt, err := tlsutil.NewCertificateInMemory("foo.example.com", 29)
  1057. if err != nil {
  1058. t.Fatal(err)
  1059. }
  1060. if err := shouldRegenerateCertificate(crt); err == nil {
  1061. t.Error("expected expiry error")
  1062. }
  1063. // Certificates with at least 31 days of life left are fine.
  1064. crt, err = tlsutil.NewCertificateInMemory("foo.example.com", 31)
  1065. if err != nil {
  1066. t.Fatal(err)
  1067. }
  1068. if err := shouldRegenerateCertificate(crt); err != nil {
  1069. t.Error("expected no error:", err)
  1070. }
  1071. if runtime.GOOS == "darwin" {
  1072. // Certificates with too long an expiry time are not allowed on macOS
  1073. crt, err = tlsutil.NewCertificateInMemory("foo.example.com", 1000)
  1074. if err != nil {
  1075. t.Fatal(err)
  1076. }
  1077. if err := shouldRegenerateCertificate(crt); err == nil {
  1078. t.Error("expected expiry error")
  1079. }
  1080. }
  1081. }
  1082. func TestConfigChanges(t *testing.T) {
  1083. t.Parallel()
  1084. const testAPIKey = "foobarbaz"
  1085. cfg := config.Configuration{
  1086. GUI: config.GUIConfiguration{
  1087. RawAddress: "127.0.0.1:0",
  1088. RawUseTLS: false,
  1089. APIKey: testAPIKey,
  1090. },
  1091. }
  1092. tmpFile, err := os.CreateTemp("", "syncthing-testConfig-")
  1093. if err != nil {
  1094. panic(err)
  1095. }
  1096. defer os.Remove(tmpFile.Name())
  1097. w := config.Wrap(tmpFile.Name(), cfg, protocol.LocalDeviceID, events.NoopLogger)
  1098. tmpFile.Close()
  1099. cfgCtx, cfgCancel := context.WithCancel(context.Background())
  1100. go w.Serve(cfgCtx)
  1101. defer cfgCancel()
  1102. baseURL, cancel, err := startHTTP(w)
  1103. if err != nil {
  1104. t.Fatal("Unexpected error from getting base URL:", err)
  1105. }
  1106. defer cancel()
  1107. cli := &http.Client{
  1108. Timeout: time.Minute,
  1109. }
  1110. do := func(req *http.Request, status int) *http.Response {
  1111. t.Helper()
  1112. req.Header.Set("X-API-Key", testAPIKey)
  1113. resp, err := cli.Do(req)
  1114. if err != nil {
  1115. t.Fatal(err)
  1116. }
  1117. if resp.StatusCode != status {
  1118. t.Errorf("Expected status %v, got %v", status, resp.StatusCode)
  1119. }
  1120. return resp
  1121. }
  1122. mod := func(method, path string, data interface{}) {
  1123. t.Helper()
  1124. bs, err := json.Marshal(data)
  1125. if err != nil {
  1126. t.Fatal(err)
  1127. }
  1128. req, _ := http.NewRequest(method, baseURL+path, bytes.NewReader(bs))
  1129. do(req, http.StatusOK).Body.Close()
  1130. }
  1131. get := func(path string) *http.Response {
  1132. t.Helper()
  1133. req, _ := http.NewRequest(http.MethodGet, baseURL+path, nil)
  1134. return do(req, http.StatusOK)
  1135. }
  1136. dev1Path := "/rest/config/devices/" + dev1.String()
  1137. // Create device
  1138. mod(http.MethodPut, "/rest/config/devices", []config.DeviceConfiguration{{DeviceID: dev1}})
  1139. // Check its there
  1140. get(dev1Path).Body.Close()
  1141. // Modify just a single attribute
  1142. mod(http.MethodPatch, dev1Path, map[string]bool{"Paused": true})
  1143. // Check that attribute
  1144. resp := get(dev1Path)
  1145. var dev config.DeviceConfiguration
  1146. if err := unmarshalTo(resp.Body, &dev); err != nil {
  1147. t.Fatal(err)
  1148. }
  1149. if !dev.Paused {
  1150. t.Error("Expected device to be paused")
  1151. }
  1152. folder2Path := "/rest/config/folders/folder2"
  1153. // Create a folder and add another
  1154. mod(http.MethodPut, "/rest/config/folders", []config.FolderConfiguration{{ID: "folder1", Path: "folder1"}})
  1155. mod(http.MethodPut, folder2Path, config.FolderConfiguration{ID: "folder2", Path: "folder2"})
  1156. // Check they are there
  1157. get("/rest/config/folders/folder1").Body.Close()
  1158. get(folder2Path).Body.Close()
  1159. // Modify just a single attribute
  1160. mod(http.MethodPatch, folder2Path, map[string]bool{"Paused": true})
  1161. // Check that attribute
  1162. resp = get(folder2Path)
  1163. var folder config.FolderConfiguration
  1164. if err := unmarshalTo(resp.Body, &folder); err != nil {
  1165. t.Fatal(err)
  1166. }
  1167. if !dev.Paused {
  1168. t.Error("Expected folder to be paused")
  1169. }
  1170. // Delete folder2
  1171. req, _ := http.NewRequest(http.MethodDelete, baseURL+folder2Path, nil)
  1172. do(req, http.StatusOK)
  1173. // Check folder1 is still there and folder2 gone
  1174. get("/rest/config/folders/folder1").Body.Close()
  1175. req, _ = http.NewRequest(http.MethodGet, baseURL+folder2Path, nil)
  1176. do(req, http.StatusNotFound)
  1177. mod(http.MethodPatch, "/rest/config/options", map[string]int{"maxSendKbps": 50})
  1178. resp = get("/rest/config/options")
  1179. var opts config.OptionsConfiguration
  1180. if err := unmarshalTo(resp.Body, &opts); err != nil {
  1181. t.Fatal(err)
  1182. }
  1183. if opts.MaxSendKbps != 50 {
  1184. t.Error("Exepcted 50 for MaxSendKbps, got", opts.MaxSendKbps)
  1185. }
  1186. }
  1187. func TestSanitizedHostname(t *testing.T) {
  1188. cases := []struct {
  1189. in, out string
  1190. }{
  1191. {"foo.BAR-baz", "foo.bar-baz"},
  1192. {"~.~-Min 1:a Räksmörgås-dator 😀😎 ~.~-", "min1araksmorgas-dator"},
  1193. {"Vicenç-PC", "vicenc-pc"},
  1194. {"~.~-~.~-", ""},
  1195. {"", ""},
  1196. }
  1197. for _, tc := range cases {
  1198. res, err := sanitizedHostname(tc.in)
  1199. if tc.out == "" && err == nil {
  1200. t.Errorf("%q should cause error", tc.in)
  1201. } else if res != tc.out {
  1202. t.Errorf("%q => %q, expected %q", tc.in, res, tc.out)
  1203. }
  1204. }
  1205. }
  1206. // runningInContainer returns true if we are inside Docker or LXC. It might
  1207. // be prone to false negatives if things change in the future, but likely
  1208. // not false positives.
  1209. func runningInContainer() bool {
  1210. if runtime.GOOS != "linux" {
  1211. return false
  1212. }
  1213. bs, err := os.ReadFile("/proc/1/cgroup")
  1214. if err != nil {
  1215. return false
  1216. }
  1217. if bytes.Contains(bs, []byte("/docker/")) {
  1218. return true
  1219. }
  1220. if bytes.Contains(bs, []byte("/lxc/")) {
  1221. return true
  1222. }
  1223. return false
  1224. }