api_test.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  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/thejerf/suture/v4"
  45. "golang.org/x/exp/slices"
  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, RawAddress: "127.0.0.1:0"})
  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. tc := tc
  445. t.Run(cases[0].URL, func(t *testing.T) {
  446. t.Parallel()
  447. testHTTPRequest(t, baseURL, tc, testAPIKey)
  448. })
  449. }
  450. }
  451. // testHTTPRequest tries the given test case, comparing the result code,
  452. // content type, and result prefix.
  453. func testHTTPRequest(t *testing.T, baseURL string, tc httpTestCase, apikey string) {
  454. // Should not be parallelized, as that just causes timeouts eventually with more test-cases
  455. timeout := time.Second
  456. if tc.Timeout > 0 {
  457. timeout = tc.Timeout
  458. }
  459. cli := &http.Client{
  460. Timeout: timeout,
  461. }
  462. req, err := http.NewRequest("GET", baseURL+tc.URL, nil)
  463. if err != nil {
  464. t.Errorf("Unexpected error requesting %s: %v", tc.URL, err)
  465. return
  466. }
  467. req.Header.Set("X-API-Key", apikey)
  468. resp, err := cli.Do(req)
  469. if err != nil {
  470. t.Errorf("Unexpected error requesting %s: %v", tc.URL, err)
  471. return
  472. }
  473. defer resp.Body.Close()
  474. if resp.StatusCode != tc.Code {
  475. t.Errorf("Get on %s should have returned status code %d, not %s", tc.URL, tc.Code, resp.Status)
  476. return
  477. }
  478. ct := resp.Header.Get("Content-Type")
  479. if !strings.HasPrefix(ct, tc.Type) {
  480. t.Errorf("The content type on %s should be %q, not %q", tc.URL, tc.Type, ct)
  481. return
  482. }
  483. data, err := io.ReadAll(resp.Body)
  484. if err != nil {
  485. t.Errorf("Unexpected error reading %s: %v", tc.URL, err)
  486. return
  487. }
  488. if !bytes.HasPrefix(data, []byte(tc.Prefix)) {
  489. t.Errorf("Returned data from %s does not have prefix %q: %s", tc.URL, tc.Prefix, data)
  490. return
  491. }
  492. }
  493. func TestHTTPLogin(t *testing.T) {
  494. t.Parallel()
  495. cfg := newMockedConfig()
  496. cfg.GUIReturns(config.GUIConfiguration{
  497. User: "üser",
  498. Password: "$2a$10$IdIZTxTg/dCNuNEGlmLynOjqg4B1FvDKuIV5e0BB3pnWVHNb8.GSq", // bcrypt of "räksmörgås" in UTF-8
  499. RawAddress: "127.0.0.1:0",
  500. APIKey: testAPIKey,
  501. })
  502. baseURL, cancel, err := startHTTP(cfg)
  503. if err != nil {
  504. t.Fatal(err)
  505. }
  506. t.Cleanup(cancel)
  507. t.Run("no auth is rejected", func(t *testing.T) {
  508. t.Parallel()
  509. req, _ := http.NewRequest("GET", baseURL, nil)
  510. resp, err := http.DefaultClient.Do(req)
  511. if err != nil {
  512. t.Fatal(err)
  513. }
  514. if resp.StatusCode != http.StatusUnauthorized {
  515. t.Errorf("Unexpected non-401 return code %d for unauthed request", resp.StatusCode)
  516. }
  517. })
  518. t.Run("incorrect password is rejected", func(t *testing.T) {
  519. t.Parallel()
  520. req, _ := http.NewRequest("GET", baseURL, nil)
  521. req.SetBasicAuth("üser", "rksmrgs")
  522. resp, err := http.DefaultClient.Do(req)
  523. if err != nil {
  524. t.Fatal(err)
  525. }
  526. if resp.StatusCode != http.StatusUnauthorized {
  527. t.Errorf("Unexpected non-401 return code %d for incorrect password", resp.StatusCode)
  528. }
  529. })
  530. t.Run("incorrect username is rejected", func(t *testing.T) {
  531. t.Parallel()
  532. req, _ := http.NewRequest("GET", baseURL, nil)
  533. req.SetBasicAuth("user", "räksmörgås") // string literals in Go source code are in UTF-8
  534. resp, err := http.DefaultClient.Do(req)
  535. if err != nil {
  536. t.Fatal(err)
  537. }
  538. if resp.StatusCode != http.StatusUnauthorized {
  539. t.Errorf("Unexpected non-401 return code %d for incorrect username", resp.StatusCode)
  540. }
  541. })
  542. t.Run("UTF-8 auth works", func(t *testing.T) {
  543. t.Parallel()
  544. req, _ := http.NewRequest("GET", baseURL, nil)
  545. req.SetBasicAuth("üser", "räksmörgås") // string literals in Go source code are in UTF-8
  546. resp, err := http.DefaultClient.Do(req)
  547. if err != nil {
  548. t.Fatal(err)
  549. }
  550. if resp.StatusCode != http.StatusOK {
  551. t.Errorf("Unexpected non-200 return code %d for authed request (UTF-8)", resp.StatusCode)
  552. }
  553. })
  554. t.Run("ISO-8859-1 auth work", func(t *testing.T) {
  555. t.Parallel()
  556. req, _ := http.NewRequest("GET", baseURL, nil)
  557. req.SetBasicAuth("\xfcser", "r\xe4ksm\xf6rg\xe5s") // escaped ISO-8859-1
  558. resp, err := http.DefaultClient.Do(req)
  559. if err != nil {
  560. t.Fatal(err)
  561. }
  562. if resp.StatusCode != http.StatusOK {
  563. t.Errorf("Unexpected non-200 return code %d for authed request (ISO-8859-1)", resp.StatusCode)
  564. }
  565. })
  566. t.Run("bad X-API-Key is rejected", func(t *testing.T) {
  567. t.Parallel()
  568. req, _ := http.NewRequest("GET", baseURL, nil)
  569. req.Header.Set("X-API-Key", testAPIKey+"X")
  570. resp, err := http.DefaultClient.Do(req)
  571. if err != nil {
  572. t.Fatal(err)
  573. }
  574. if resp.StatusCode != http.StatusUnauthorized {
  575. t.Errorf("Unexpected non-401 return code %d for bad API key", resp.StatusCode)
  576. }
  577. })
  578. t.Run("good X-API-Key is accepted", func(t *testing.T) {
  579. t.Parallel()
  580. req, _ := http.NewRequest("GET", baseURL, nil)
  581. req.Header.Set("X-API-Key", testAPIKey)
  582. resp, err := http.DefaultClient.Do(req)
  583. if err != nil {
  584. t.Fatal(err)
  585. }
  586. if resp.StatusCode != http.StatusOK {
  587. t.Errorf("Unexpected non-200 return code %d for API key", resp.StatusCode)
  588. }
  589. })
  590. t.Run("bad Bearer is rejected", func(t *testing.T) {
  591. t.Parallel()
  592. req, _ := http.NewRequest("GET", baseURL, nil)
  593. req.Header.Set("Authorization", "Bearer "+testAPIKey+"X")
  594. resp, err := http.DefaultClient.Do(req)
  595. if err != nil {
  596. t.Fatal(err)
  597. }
  598. if resp.StatusCode != http.StatusUnauthorized {
  599. t.Errorf("Unexpected non-401 return code %d for bad API key", resp.StatusCode)
  600. }
  601. })
  602. t.Run("good Bearer is accepted", func(t *testing.T) {
  603. t.Parallel()
  604. req, _ := http.NewRequest("GET", baseURL, nil)
  605. req.Header.Set("Authorization", "Bearer "+testAPIKey)
  606. resp, err := http.DefaultClient.Do(req)
  607. if err != nil {
  608. t.Fatal(err)
  609. }
  610. if resp.StatusCode != http.StatusOK {
  611. t.Errorf("Unexpected non-200 return code %d for API key", resp.StatusCode)
  612. }
  613. })
  614. }
  615. func startHTTP(cfg config.Wrapper) (string, context.CancelFunc, error) {
  616. m := new(modelmocks.Model)
  617. assetDir := "../../gui"
  618. eventSub := new(eventmocks.BufferedSubscription)
  619. diskEventSub := new(eventmocks.BufferedSubscription)
  620. discoverer := new(discovermocks.Manager)
  621. connections := new(connmocks.Service)
  622. errorLog := new(loggermocks.Recorder)
  623. systemLog := new(loggermocks.Recorder)
  624. for _, l := range []*loggermocks.Recorder{errorLog, systemLog} {
  625. l.SinceReturns([]logger.Line{
  626. {
  627. When: time.Now(),
  628. Message: "Test message",
  629. },
  630. })
  631. }
  632. addrChan := make(chan string)
  633. mockedSummary := &modelmocks.FolderSummaryService{}
  634. mockedSummary.SummaryReturns(new(model.FolderSummary), nil)
  635. // Instantiate the API service
  636. urService := ur.New(cfg, m, connections, false)
  637. svc := New(protocol.LocalDeviceID, cfg, assetDir, "syncthing", m, eventSub, diskEventSub, events.NoopLogger, discoverer, connections, urService, mockedSummary, errorLog, systemLog, false).(*service)
  638. defer os.Remove(token)
  639. svc.started = addrChan
  640. // Actually start the API service
  641. supervisor := suture.New("API test", suture.Spec{
  642. PassThroughPanics: true,
  643. })
  644. supervisor.Add(svc)
  645. ctx, cancel := context.WithCancel(context.Background())
  646. supervisor.ServeBackground(ctx)
  647. // Make sure the API service is listening, and get the URL to use.
  648. addr := <-addrChan
  649. tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
  650. if err != nil {
  651. cancel()
  652. return "", cancel, fmt.Errorf("weird address from API service: %w", err)
  653. }
  654. host, _, _ := net.SplitHostPort(cfg.GUI().RawAddress)
  655. if host == "" || host == "0.0.0.0" {
  656. host = "127.0.0.1"
  657. }
  658. baseURL := fmt.Sprintf("http://%s", net.JoinHostPort(host, strconv.Itoa(tcpAddr.Port)))
  659. return baseURL, cancel, nil
  660. }
  661. func TestCSRFRequired(t *testing.T) {
  662. t.Parallel()
  663. baseURL, cancel, err := startHTTP(apiCfg)
  664. if err != nil {
  665. t.Fatal("Unexpected error from getting base URL:", err)
  666. }
  667. t.Cleanup(cancel)
  668. cli := &http.Client{
  669. Timeout: time.Minute,
  670. }
  671. // Getting the base URL (i.e. "/") should succeed.
  672. resp, err := cli.Get(baseURL)
  673. if err != nil {
  674. t.Fatal("Unexpected error from getting base URL:", err)
  675. }
  676. resp.Body.Close()
  677. if resp.StatusCode != http.StatusOK {
  678. t.Fatal("Getting base URL should succeed, not", resp.Status)
  679. }
  680. // Find the returned CSRF token for future use
  681. var csrfTokenName, csrfTokenValue string
  682. for _, cookie := range resp.Cookies() {
  683. if strings.HasPrefix(cookie.Name, "CSRF-Token") {
  684. csrfTokenName = cookie.Name
  685. csrfTokenValue = cookie.Value
  686. break
  687. }
  688. }
  689. t.Run("/rest without a token should fail", func(t *testing.T) {
  690. t.Parallel()
  691. resp, err := cli.Get(baseURL + "/rest/system/config")
  692. if err != nil {
  693. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  694. }
  695. resp.Body.Close()
  696. if resp.StatusCode != http.StatusForbidden {
  697. t.Fatal("Getting /rest/system/config without CSRF token should fail, not", resp.Status)
  698. }
  699. })
  700. t.Run("/rest with a token should succeed", func(t *testing.T) {
  701. t.Parallel()
  702. req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
  703. req.Header.Set("X-"+csrfTokenName, csrfTokenValue)
  704. resp, err := cli.Do(req)
  705. if err != nil {
  706. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  707. }
  708. resp.Body.Close()
  709. if resp.StatusCode != http.StatusOK {
  710. t.Fatal("Getting /rest/system/config with CSRF token should succeed, not", resp.Status)
  711. }
  712. })
  713. t.Run("/rest with an incorrect API key should fail, X-API-Key version", func(t *testing.T) {
  714. t.Parallel()
  715. req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
  716. req.Header.Set("X-API-Key", testAPIKey+"X")
  717. resp, err := cli.Do(req)
  718. if err != nil {
  719. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  720. }
  721. resp.Body.Close()
  722. if resp.StatusCode != http.StatusForbidden {
  723. t.Fatal("Getting /rest/system/config with incorrect API token should fail, not", resp.Status)
  724. }
  725. })
  726. t.Run("/rest with an incorrect API key should fail, Bearer auth version", func(t *testing.T) {
  727. t.Parallel()
  728. req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
  729. req.Header.Set("Authorization", "Bearer "+testAPIKey+"X")
  730. resp, err := cli.Do(req)
  731. if err != nil {
  732. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  733. }
  734. resp.Body.Close()
  735. if resp.StatusCode != http.StatusForbidden {
  736. t.Fatal("Getting /rest/system/config with incorrect API token should fail, not", resp.Status)
  737. }
  738. })
  739. t.Run("/rest with the API key should succeed", func(t *testing.T) {
  740. t.Parallel()
  741. req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
  742. req.Header.Set("X-API-Key", testAPIKey)
  743. resp, err := cli.Do(req)
  744. if err != nil {
  745. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  746. }
  747. resp.Body.Close()
  748. if resp.StatusCode != http.StatusOK {
  749. t.Fatal("Getting /rest/system/config with API key should succeed, not", resp.Status)
  750. }
  751. })
  752. t.Run("/rest with the API key as a bearer token should succeed", func(t *testing.T) {
  753. t.Parallel()
  754. req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
  755. req.Header.Set("Authorization", "Bearer "+testAPIKey)
  756. resp, err := cli.Do(req)
  757. if err != nil {
  758. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  759. }
  760. resp.Body.Close()
  761. if resp.StatusCode != http.StatusOK {
  762. t.Fatal("Getting /rest/system/config with API key should succeed, not", resp.Status)
  763. }
  764. })
  765. }
  766. func TestRandomString(t *testing.T) {
  767. t.Parallel()
  768. baseURL, cancel, err := startHTTP(apiCfg)
  769. if err != nil {
  770. t.Fatal(err)
  771. }
  772. defer cancel()
  773. cli := &http.Client{
  774. Timeout: time.Second,
  775. }
  776. // The default should be to return a 32 character random string
  777. for _, url := range []string{"/rest/svc/random/string", "/rest/svc/random/string?length=-1", "/rest/svc/random/string?length=yo"} {
  778. req, _ := http.NewRequest("GET", baseURL+url, nil)
  779. req.Header.Set("X-API-Key", testAPIKey)
  780. resp, err := cli.Do(req)
  781. if err != nil {
  782. t.Fatal(err)
  783. }
  784. var res map[string]string
  785. if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
  786. t.Fatal(err)
  787. }
  788. if len(res["random"]) != 32 {
  789. t.Errorf("Expected 32 random characters, got %q of length %d", res["random"], len(res["random"]))
  790. }
  791. }
  792. // We can ask for a different length if we like
  793. req, _ := http.NewRequest("GET", baseURL+"/rest/svc/random/string?length=27", nil)
  794. req.Header.Set("X-API-Key", testAPIKey)
  795. resp, err := cli.Do(req)
  796. if err != nil {
  797. t.Fatal(err)
  798. }
  799. var res map[string]string
  800. if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
  801. t.Fatal(err)
  802. }
  803. if len(res["random"]) != 27 {
  804. t.Errorf("Expected 27 random characters, got %q of length %d", res["random"], len(res["random"]))
  805. }
  806. }
  807. func TestConfigPostOK(t *testing.T) {
  808. t.Parallel()
  809. cfg := bytes.NewBuffer([]byte(`{
  810. "version": 15,
  811. "folders": [
  812. {
  813. "id": "foo",
  814. "path": "TestConfigPostOK"
  815. }
  816. ]
  817. }`))
  818. resp, err := testConfigPost(cfg)
  819. if err != nil {
  820. t.Fatal(err)
  821. }
  822. if resp.StatusCode != http.StatusOK {
  823. t.Error("Expected 200 OK, not", resp.Status)
  824. }
  825. os.RemoveAll("TestConfigPostOK")
  826. }
  827. func TestConfigPostDupFolder(t *testing.T) {
  828. t.Parallel()
  829. cfg := bytes.NewBuffer([]byte(`{
  830. "version": 15,
  831. "folders": [
  832. {"id": "foo"},
  833. {"id": "foo"}
  834. ]
  835. }`))
  836. resp, err := testConfigPost(cfg)
  837. if err != nil {
  838. t.Fatal(err)
  839. }
  840. if resp.StatusCode != http.StatusBadRequest {
  841. t.Error("Expected 400 Bad Request, not", resp.Status)
  842. }
  843. }
  844. func testConfigPost(data io.Reader) (*http.Response, error) {
  845. baseURL, cancel, err := startHTTP(apiCfg)
  846. if err != nil {
  847. return nil, err
  848. }
  849. defer cancel()
  850. cli := &http.Client{
  851. Timeout: time.Second,
  852. }
  853. req, _ := http.NewRequest("POST", baseURL+"/rest/system/config", data)
  854. req.Header.Set("X-API-Key", testAPIKey)
  855. return cli.Do(req)
  856. }
  857. func TestHostCheck(t *testing.T) {
  858. t.Parallel()
  859. // An API service bound to localhost should reject non-localhost host Headers
  860. cfg := newMockedConfig()
  861. cfg.GUIReturns(config.GUIConfiguration{RawAddress: "127.0.0.1:0"})
  862. baseURL, cancel, err := startHTTP(cfg)
  863. if err != nil {
  864. t.Fatal(err)
  865. }
  866. defer cancel()
  867. // A normal HTTP get to the localhost-bound service should succeed
  868. resp, err := http.Get(baseURL)
  869. if err != nil {
  870. t.Fatal(err)
  871. }
  872. resp.Body.Close()
  873. if resp.StatusCode != http.StatusOK {
  874. t.Error("Regular HTTP get: expected 200 OK, not", resp.Status)
  875. }
  876. // A request with a suspicious Host header should fail
  877. req, _ := http.NewRequest("GET", baseURL, nil)
  878. req.Host = "example.com"
  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.StatusForbidden {
  885. t.Error("Suspicious Host header: expected 403 Forbidden, not", resp.Status)
  886. }
  887. // A request with an explicit "localhost:8384" Host header should pass
  888. req, _ = http.NewRequest("GET", baseURL, nil)
  889. req.Host = "localhost:8384"
  890. resp, err = http.DefaultClient.Do(req)
  891. if err != nil {
  892. t.Fatal(err)
  893. }
  894. resp.Body.Close()
  895. if resp.StatusCode != http.StatusOK {
  896. t.Error("Explicit localhost:8384: expected 200 OK, not", resp.Status)
  897. }
  898. // A request with an explicit "localhost" Host header (no port) should pass
  899. req, _ = http.NewRequest("GET", baseURL, nil)
  900. req.Host = "localhost"
  901. resp, err = http.DefaultClient.Do(req)
  902. if err != nil {
  903. t.Fatal(err)
  904. }
  905. resp.Body.Close()
  906. if resp.StatusCode != http.StatusOK {
  907. t.Error("Explicit localhost: expected 200 OK, not", resp.Status)
  908. }
  909. // A server with InsecureSkipHostCheck set behaves differently
  910. cfg = newMockedConfig()
  911. cfg.GUIReturns(config.GUIConfiguration{
  912. RawAddress: "127.0.0.1:0",
  913. InsecureSkipHostCheck: true,
  914. })
  915. baseURL, cancel, err = startHTTP(cfg)
  916. if err != nil {
  917. t.Fatal(err)
  918. }
  919. defer cancel()
  920. // A request with a suspicious Host header should be allowed
  921. req, _ = http.NewRequest("GET", baseURL, nil)
  922. req.Host = "example.com"
  923. resp, err = http.DefaultClient.Do(req)
  924. if err != nil {
  925. t.Fatal(err)
  926. }
  927. resp.Body.Close()
  928. if resp.StatusCode != http.StatusOK {
  929. t.Error("Incorrect host header, check disabled: expected 200 OK, not", resp.Status)
  930. }
  931. if !testing.Short() {
  932. // A server bound to a wildcard address also doesn't do the check
  933. cfg = newMockedConfig()
  934. cfg.GUIReturns(config.GUIConfiguration{
  935. RawAddress: "0.0.0.0:0",
  936. })
  937. baseURL, cancel, err = startHTTP(cfg)
  938. if err != nil {
  939. t.Fatal(err)
  940. }
  941. defer cancel()
  942. // A request with a suspicious Host header should be allowed
  943. req, _ = http.NewRequest("GET", baseURL, nil)
  944. req.Host = "example.com"
  945. resp, err = http.DefaultClient.Do(req)
  946. if err != nil {
  947. t.Fatal(err)
  948. }
  949. resp.Body.Close()
  950. if resp.StatusCode != http.StatusOK {
  951. t.Error("Incorrect host header, wildcard bound: expected 200 OK, not", resp.Status)
  952. }
  953. }
  954. // This should all work over IPv6 as well
  955. if runningInContainer() {
  956. // Working IPv6 in Docker can't be taken for granted.
  957. return
  958. }
  959. cfg = newMockedConfig()
  960. cfg.GUIReturns(config.GUIConfiguration{
  961. RawAddress: "[::1]:0",
  962. })
  963. baseURL, cancel, err = startHTTP(cfg)
  964. if err != nil {
  965. t.Fatal(err)
  966. }
  967. defer cancel()
  968. // A normal HTTP get to the localhost-bound service should succeed
  969. resp, err = http.Get(baseURL)
  970. if err != nil {
  971. t.Fatal(err)
  972. }
  973. resp.Body.Close()
  974. if resp.StatusCode != http.StatusOK {
  975. t.Error("Regular HTTP get (IPv6): expected 200 OK, not", resp.Status)
  976. }
  977. // A request with a suspicious Host header should fail
  978. req, _ = http.NewRequest("GET", baseURL, nil)
  979. req.Host = "example.com"
  980. resp, err = http.DefaultClient.Do(req)
  981. if err != nil {
  982. t.Fatal(err)
  983. }
  984. resp.Body.Close()
  985. if resp.StatusCode != http.StatusForbidden {
  986. t.Error("Suspicious Host header (IPv6): expected 403 Forbidden, not", resp.Status)
  987. }
  988. // A request with an explicit "localhost:8384" Host header should pass
  989. req, _ = http.NewRequest("GET", baseURL, nil)
  990. req.Host = "localhost:8384"
  991. resp, err = http.DefaultClient.Do(req)
  992. if err != nil {
  993. t.Fatal(err)
  994. }
  995. resp.Body.Close()
  996. if resp.StatusCode != http.StatusOK {
  997. t.Error("Explicit localhost:8384 (IPv6): expected 200 OK, not", resp.Status)
  998. }
  999. }
  1000. func TestAddressIsLocalhost(t *testing.T) {
  1001. t.Parallel()
  1002. testcases := []struct {
  1003. address string
  1004. result bool
  1005. }{
  1006. // These are all valid localhost addresses
  1007. {"localhost", true},
  1008. {"LOCALHOST", true},
  1009. {"localhost.", true},
  1010. {"::1", true},
  1011. {"127.0.0.1", true},
  1012. {"127.23.45.56", true},
  1013. {"localhost:8080", true},
  1014. {"LOCALHOST:8000", true},
  1015. {"localhost.:8080", true},
  1016. {"[::1]:8080", true},
  1017. {"127.0.0.1:8080", true},
  1018. {"127.23.45.56:8080", true},
  1019. {"www.localhost", true},
  1020. {"www.localhost:8080", true},
  1021. // These are all non-localhost addresses
  1022. {"example.com", false},
  1023. {"example.com:8080", false},
  1024. {"localhost.com", false},
  1025. {"localhost.com:8080", false},
  1026. {"192.0.2.10", false},
  1027. {"192.0.2.10:8080", false},
  1028. {"0.0.0.0", false},
  1029. {"0.0.0.0:8080", false},
  1030. {"::", false},
  1031. {"[::]:8080", false},
  1032. {":8080", false},
  1033. }
  1034. for _, tc := range testcases {
  1035. result := addressIsLocalhost(tc.address)
  1036. if result != tc.result {
  1037. t.Errorf("addressIsLocalhost(%q)=%v, expected %v", tc.address, result, tc.result)
  1038. }
  1039. }
  1040. }
  1041. func TestAccessControlAllowOriginHeader(t *testing.T) {
  1042. t.Parallel()
  1043. baseURL, cancel, err := startHTTP(apiCfg)
  1044. if err != nil {
  1045. t.Fatal(err)
  1046. }
  1047. defer cancel()
  1048. cli := &http.Client{
  1049. Timeout: time.Second,
  1050. }
  1051. req, _ := http.NewRequest("GET", baseURL+"/rest/system/status", nil)
  1052. req.Header.Set("X-API-Key", testAPIKey)
  1053. resp, err := cli.Do(req)
  1054. if err != nil {
  1055. t.Fatal(err)
  1056. }
  1057. resp.Body.Close()
  1058. if resp.StatusCode != http.StatusOK {
  1059. t.Fatal("GET on /rest/system/status should succeed, not", resp.Status)
  1060. }
  1061. if resp.Header.Get("Access-Control-Allow-Origin") != "*" {
  1062. t.Fatal("GET on /rest/system/status should return a 'Access-Control-Allow-Origin: *' header")
  1063. }
  1064. }
  1065. func TestOptionsRequest(t *testing.T) {
  1066. t.Parallel()
  1067. baseURL, cancel, err := startHTTP(apiCfg)
  1068. if err != nil {
  1069. t.Fatal(err)
  1070. }
  1071. defer cancel()
  1072. cli := &http.Client{
  1073. Timeout: time.Second,
  1074. }
  1075. req, _ := http.NewRequest("OPTIONS", baseURL+"/rest/system/status", nil)
  1076. resp, err := cli.Do(req)
  1077. if err != nil {
  1078. t.Fatal(err)
  1079. }
  1080. resp.Body.Close()
  1081. if resp.StatusCode != http.StatusNoContent {
  1082. t.Fatal("OPTIONS on /rest/system/status should succeed, not", resp.Status)
  1083. }
  1084. if resp.Header.Get("Access-Control-Allow-Origin") != "*" {
  1085. t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Origin: *' header")
  1086. }
  1087. if resp.Header.Get("Access-Control-Allow-Methods") != "GET, POST, PUT, PATCH, DELETE, OPTIONS" {
  1088. t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS' header")
  1089. }
  1090. if resp.Header.Get("Access-Control-Allow-Headers") != "Content-Type, X-API-Key" {
  1091. t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Headers: Content-Type, X-API-KEY' header")
  1092. }
  1093. }
  1094. func TestEventMasks(t *testing.T) {
  1095. t.Parallel()
  1096. cfg := newMockedConfig()
  1097. defSub := new(eventmocks.BufferedSubscription)
  1098. diskSub := new(eventmocks.BufferedSubscription)
  1099. svc := New(protocol.LocalDeviceID, cfg, "", "syncthing", nil, defSub, diskSub, events.NoopLogger, nil, nil, nil, nil, nil, nil, false).(*service)
  1100. defer os.Remove(token)
  1101. if mask := svc.getEventMask(""); mask != DefaultEventMask {
  1102. t.Errorf("incorrect default mask %x != %x", int64(mask), int64(DefaultEventMask))
  1103. }
  1104. expected := events.FolderSummary | events.LocalChangeDetected
  1105. if mask := svc.getEventMask("FolderSummary,LocalChangeDetected"); mask != expected {
  1106. t.Errorf("incorrect parsed mask %x != %x", int64(mask), int64(expected))
  1107. }
  1108. expected = 0
  1109. if mask := svc.getEventMask("WeirdEvent,something else that doesn't exist"); mask != expected {
  1110. t.Errorf("incorrect parsed mask %x != %x", int64(mask), int64(expected))
  1111. }
  1112. if res := svc.getEventSub(DefaultEventMask); res != defSub {
  1113. t.Errorf("should have returned the given default event sub")
  1114. }
  1115. if res := svc.getEventSub(DiskEventMask); res != diskSub {
  1116. t.Errorf("should have returned the given disk event sub")
  1117. }
  1118. if res := svc.getEventSub(events.LocalIndexUpdated); res == nil || res == defSub || res == diskSub {
  1119. t.Errorf("should have returned a valid, non-default event sub")
  1120. }
  1121. }
  1122. func TestBrowse(t *testing.T) {
  1123. t.Parallel()
  1124. pathSep := string(os.PathSeparator)
  1125. ffs := fs.NewFilesystem(fs.FilesystemTypeFake, rand.String(32)+"?nostfolder=true")
  1126. _ = ffs.Mkdir("dir", 0o755)
  1127. _ = fs.WriteFile(ffs, "file", []byte("hello"), 0o644)
  1128. _ = ffs.Mkdir("MiXEDCase", 0o755)
  1129. // We expect completion to return the full path to the completed
  1130. // directory, with an ending slash.
  1131. dirPath := "dir" + pathSep
  1132. mixedCaseDirPath := "MiXEDCase" + pathSep
  1133. cases := []struct {
  1134. current string
  1135. returns []string
  1136. }{
  1137. // The directory without slash is completed to one with slash.
  1138. {"dir", []string{"dir" + pathSep}},
  1139. // With slash it's completed to its contents.
  1140. // Dirs are given pathSeps.
  1141. // Files are not returned.
  1142. {"", []string{mixedCaseDirPath, dirPath}},
  1143. // Globbing is automatic based on prefix.
  1144. {"d", []string{dirPath}},
  1145. {"di", []string{dirPath}},
  1146. {"dir", []string{dirPath}},
  1147. {"f", nil},
  1148. {"q", nil},
  1149. // Globbing is case-insensitive
  1150. {"mixed", []string{mixedCaseDirPath}},
  1151. }
  1152. for _, tc := range cases {
  1153. ret := browseFiles(ffs, tc.current)
  1154. if !slices.Equal(ret, tc.returns) {
  1155. t.Errorf("browseFiles(%q) => %q, expected %q", tc.current, ret, tc.returns)
  1156. }
  1157. }
  1158. }
  1159. func TestPrefixMatch(t *testing.T) {
  1160. t.Parallel()
  1161. cases := []struct {
  1162. s string
  1163. prefix string
  1164. expected int
  1165. }{
  1166. {"aaaA", "aaa", matchExact},
  1167. {"AAAX", "BBB", noMatch},
  1168. {"AAAX", "aAa", matchCaseIns},
  1169. {"äÜX", "äü", matchCaseIns},
  1170. }
  1171. for _, tc := range cases {
  1172. ret := checkPrefixMatch(tc.s, tc.prefix)
  1173. if ret != tc.expected {
  1174. t.Errorf("checkPrefixMatch(%q, %q) => %v, expected %v", tc.s, tc.prefix, ret, tc.expected)
  1175. }
  1176. }
  1177. }
  1178. func TestShouldRegenerateCertificate(t *testing.T) {
  1179. // Self signed certificates expiring in less than a month are errored so we
  1180. // can regenerate in time.
  1181. crt, err := tlsutil.NewCertificateInMemory("foo.example.com", 29)
  1182. if err != nil {
  1183. t.Fatal(err)
  1184. }
  1185. if err := shouldRegenerateCertificate(crt); err == nil {
  1186. t.Error("expected expiry error")
  1187. }
  1188. // Certificates with at least 31 days of life left are fine.
  1189. crt, err = tlsutil.NewCertificateInMemory("foo.example.com", 31)
  1190. if err != nil {
  1191. t.Fatal(err)
  1192. }
  1193. if err := shouldRegenerateCertificate(crt); err != nil {
  1194. t.Error("expected no error:", err)
  1195. }
  1196. if build.IsDarwin {
  1197. // Certificates with too long an expiry time are not allowed on macOS
  1198. crt, err = tlsutil.NewCertificateInMemory("foo.example.com", 1000)
  1199. if err != nil {
  1200. t.Fatal(err)
  1201. }
  1202. if err := shouldRegenerateCertificate(crt); err == nil {
  1203. t.Error("expected expiry error")
  1204. }
  1205. }
  1206. }
  1207. func TestConfigChanges(t *testing.T) {
  1208. t.Parallel()
  1209. const testAPIKey = "foobarbaz"
  1210. cfg := config.Configuration{
  1211. GUI: config.GUIConfiguration{
  1212. RawAddress: "127.0.0.1:0",
  1213. RawUseTLS: false,
  1214. APIKey: testAPIKey,
  1215. },
  1216. }
  1217. tmpFile, err := os.CreateTemp("", "syncthing-testConfig-")
  1218. if err != nil {
  1219. panic(err)
  1220. }
  1221. defer os.Remove(tmpFile.Name())
  1222. w := config.Wrap(tmpFile.Name(), cfg, protocol.LocalDeviceID, events.NoopLogger)
  1223. tmpFile.Close()
  1224. cfgCtx, cfgCancel := context.WithCancel(context.Background())
  1225. go w.Serve(cfgCtx)
  1226. defer cfgCancel()
  1227. baseURL, cancel, err := startHTTP(w)
  1228. if err != nil {
  1229. t.Fatal("Unexpected error from getting base URL:", err)
  1230. }
  1231. defer cancel()
  1232. cli := &http.Client{
  1233. Timeout: time.Minute,
  1234. }
  1235. do := func(req *http.Request, status int) *http.Response {
  1236. t.Helper()
  1237. req.Header.Set("X-API-Key", testAPIKey)
  1238. resp, err := cli.Do(req)
  1239. if err != nil {
  1240. t.Fatal(err)
  1241. }
  1242. if resp.StatusCode != status {
  1243. t.Errorf("Expected status %v, got %v", status, resp.StatusCode)
  1244. }
  1245. return resp
  1246. }
  1247. mod := func(method, path string, data interface{}) {
  1248. t.Helper()
  1249. bs, err := json.Marshal(data)
  1250. if err != nil {
  1251. t.Fatal(err)
  1252. }
  1253. req, _ := http.NewRequest(method, baseURL+path, bytes.NewReader(bs))
  1254. do(req, http.StatusOK).Body.Close()
  1255. }
  1256. get := func(path string) *http.Response {
  1257. t.Helper()
  1258. req, _ := http.NewRequest(http.MethodGet, baseURL+path, nil)
  1259. return do(req, http.StatusOK)
  1260. }
  1261. dev1Path := "/rest/config/devices/" + dev1.String()
  1262. // Create device
  1263. mod(http.MethodPut, "/rest/config/devices", []config.DeviceConfiguration{{DeviceID: dev1}})
  1264. // Check its there
  1265. get(dev1Path).Body.Close()
  1266. // Modify just a single attribute
  1267. mod(http.MethodPatch, dev1Path, map[string]bool{"Paused": true})
  1268. // Check that attribute
  1269. resp := get(dev1Path)
  1270. var dev config.DeviceConfiguration
  1271. if err := unmarshalTo(resp.Body, &dev); err != nil {
  1272. t.Fatal(err)
  1273. }
  1274. if !dev.Paused {
  1275. t.Error("Expected device to be paused")
  1276. }
  1277. folder2Path := "/rest/config/folders/folder2"
  1278. // Create a folder and add another
  1279. mod(http.MethodPut, "/rest/config/folders", []config.FolderConfiguration{{ID: "folder1", Path: "folder1"}})
  1280. mod(http.MethodPut, folder2Path, config.FolderConfiguration{ID: "folder2", Path: "folder2"})
  1281. // Check they are there
  1282. get("/rest/config/folders/folder1").Body.Close()
  1283. get(folder2Path).Body.Close()
  1284. // Modify just a single attribute
  1285. mod(http.MethodPatch, folder2Path, map[string]bool{"Paused": true})
  1286. // Check that attribute
  1287. resp = get(folder2Path)
  1288. var folder config.FolderConfiguration
  1289. if err := unmarshalTo(resp.Body, &folder); err != nil {
  1290. t.Fatal(err)
  1291. }
  1292. if !dev.Paused {
  1293. t.Error("Expected folder to be paused")
  1294. }
  1295. // Delete folder2
  1296. req, _ := http.NewRequest(http.MethodDelete, baseURL+folder2Path, nil)
  1297. do(req, http.StatusOK)
  1298. // Check folder1 is still there and folder2 gone
  1299. get("/rest/config/folders/folder1").Body.Close()
  1300. req, _ = http.NewRequest(http.MethodGet, baseURL+folder2Path, nil)
  1301. do(req, http.StatusNotFound)
  1302. mod(http.MethodPatch, "/rest/config/options", map[string]int{"maxSendKbps": 50})
  1303. resp = get("/rest/config/options")
  1304. var opts config.OptionsConfiguration
  1305. if err := unmarshalTo(resp.Body, &opts); err != nil {
  1306. t.Fatal(err)
  1307. }
  1308. if opts.MaxSendKbps != 50 {
  1309. t.Error("Expected 50 for MaxSendKbps, got", opts.MaxSendKbps)
  1310. }
  1311. }
  1312. func TestSanitizedHostname(t *testing.T) {
  1313. cases := []struct {
  1314. in, out string
  1315. }{
  1316. {"foo.BAR-baz", "foo.bar-baz"},
  1317. {"~.~-Min 1:a Räksmörgås-dator 😀😎 ~.~-", "min1araksmorgas-dator"},
  1318. {"Vicenç-PC", "vicenc-pc"},
  1319. {"~.~-~.~-", ""},
  1320. {"", ""},
  1321. }
  1322. for _, tc := range cases {
  1323. res, err := sanitizedHostname(tc.in)
  1324. if tc.out == "" && err == nil {
  1325. t.Errorf("%q should cause error", tc.in)
  1326. } else if res != tc.out {
  1327. t.Errorf("%q => %q, expected %q", tc.in, res, tc.out)
  1328. }
  1329. }
  1330. }
  1331. // runningInContainer returns true if we are inside Docker or LXC. It might
  1332. // be prone to false negatives if things change in the future, but likely
  1333. // not false positives.
  1334. func runningInContainer() bool {
  1335. if !build.IsLinux {
  1336. return false
  1337. }
  1338. bs, err := os.ReadFile("/proc/1/cgroup")
  1339. if err != nil {
  1340. return false
  1341. }
  1342. if bytes.Contains(bs, []byte("/docker/")) {
  1343. return true
  1344. }
  1345. if bytes.Contains(bs, []byte("/lxc/")) {
  1346. return true
  1347. }
  1348. return false
  1349. }