1
0

api_test.go 39 KB

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