api_test.go 35 KB

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