api_test.go 35 KB

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