api_test.go 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781
  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. "slices"
  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. "github.com/syncthing/syncthing/lib/db"
  30. "github.com/syncthing/syncthing/lib/db/backend"
  31. discovermocks "github.com/syncthing/syncthing/lib/discover/mocks"
  32. "github.com/syncthing/syncthing/lib/events"
  33. eventmocks "github.com/syncthing/syncthing/lib/events/mocks"
  34. "github.com/syncthing/syncthing/lib/fs"
  35. "github.com/syncthing/syncthing/lib/locations"
  36. "github.com/syncthing/syncthing/lib/logger"
  37. loggermocks "github.com/syncthing/syncthing/lib/logger/mocks"
  38. "github.com/syncthing/syncthing/lib/model"
  39. modelmocks "github.com/syncthing/syncthing/lib/model/mocks"
  40. "github.com/syncthing/syncthing/lib/protocol"
  41. "github.com/syncthing/syncthing/lib/rand"
  42. "github.com/syncthing/syncthing/lib/svcutil"
  43. "github.com/syncthing/syncthing/lib/sync"
  44. "github.com/syncthing/syncthing/lib/tlsutil"
  45. "github.com/syncthing/syncthing/lib/ur"
  46. "github.com/thejerf/suture/v4"
  47. )
  48. var (
  49. confDir = filepath.Join("testdata", "config")
  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 TestStopAfterBrokenConfig(t *testing.T) {
  66. t.Parallel()
  67. cfg := config.Configuration{
  68. GUI: config.GUIConfiguration{
  69. RawAddress: "127.0.0.1:0",
  70. RawUseTLS: false,
  71. },
  72. }
  73. w := config.Wrap("/dev/null", cfg, protocol.LocalDeviceID, events.NoopLogger)
  74. mdb, _ := db.NewLowlevel(backend.OpenMemory(), events.NoopLogger)
  75. kdb := db.NewMiscDataNamespace(mdb)
  76. srv := New(protocol.LocalDeviceID, w, "", "syncthing", nil, nil, nil, events.NoopLogger, nil, nil, nil, nil, nil, nil, false, kdb).(*service)
  77. srv.started = make(chan string)
  78. sup := suture.New("test", svcutil.SpecWithDebugLogger(l))
  79. sup.Add(srv)
  80. ctx, cancel := context.WithCancel(context.Background())
  81. sup.ServeBackground(ctx)
  82. <-srv.started
  83. // Service is now running, listening on a random port on localhost. Now we
  84. // request a config change to a completely invalid listen address. The
  85. // commit will fail and the service will be in a broken state.
  86. newCfg := config.Configuration{
  87. GUI: config.GUIConfiguration{
  88. RawAddress: "totally not a valid address",
  89. RawUseTLS: false,
  90. },
  91. }
  92. if err := srv.VerifyConfiguration(cfg, newCfg); err == nil {
  93. t.Fatal("Verify config should have failed")
  94. }
  95. cancel()
  96. }
  97. func TestAssetsDir(t *testing.T) {
  98. t.Parallel()
  99. // For any given request to $FILE, we should return the first found of
  100. // - assetsdir/$THEME/$FILE
  101. // - compiled in asset $THEME/$FILE
  102. // - assetsdir/default/$FILE
  103. // - compiled in asset default/$FILE
  104. // The asset map contains compressed assets, so create a couple of gzip compressed assets here.
  105. buf := new(bytes.Buffer)
  106. gw := gzip.NewWriter(buf)
  107. gw.Write([]byte("default"))
  108. gw.Close()
  109. def := assets.Asset{
  110. Content: buf.String(),
  111. Gzipped: true,
  112. }
  113. buf = new(bytes.Buffer)
  114. gw = gzip.NewWriter(buf)
  115. gw.Write([]byte("foo"))
  116. gw.Close()
  117. foo := assets.Asset{
  118. Content: buf.String(),
  119. Gzipped: true,
  120. }
  121. e := &staticsServer{
  122. theme: "foo",
  123. mut: sync.NewRWMutex(),
  124. assetDir: "testdata",
  125. assets: map[string]assets.Asset{
  126. "foo/a": foo, // overridden in foo/a
  127. "foo/b": foo,
  128. "default/a": def, // overridden in default/a (but foo/a takes precedence)
  129. "default/b": def, // overridden in default/b (but foo/b takes precedence)
  130. "default/c": def,
  131. },
  132. }
  133. s := httptest.NewServer(e)
  134. defer s.Close()
  135. // assetsdir/foo/a exists, overrides compiled in
  136. expectURLToContain(t, s.URL+"/a", "overridden-foo")
  137. // foo/b is compiled in, default/b is overridden, return compiled in
  138. expectURLToContain(t, s.URL+"/b", "foo")
  139. // only exists as compiled in default/c so use that
  140. expectURLToContain(t, s.URL+"/c", "default")
  141. // only exists as overridden default/d so use that
  142. expectURLToContain(t, s.URL+"/d", "overridden-default")
  143. }
  144. func expectURLToContain(t *testing.T, url, exp string) {
  145. res, err := http.Get(url)
  146. if err != nil {
  147. t.Error(err)
  148. return
  149. }
  150. if res.StatusCode != 200 {
  151. t.Errorf("Got %s instead of 200 OK", res.Status)
  152. return
  153. }
  154. data, err := io.ReadAll(res.Body)
  155. res.Body.Close()
  156. if err != nil {
  157. t.Error(err)
  158. return
  159. }
  160. if string(data) != exp {
  161. t.Errorf("Got %q instead of %q on %q", data, exp, url)
  162. return
  163. }
  164. }
  165. func TestDirNames(t *testing.T) {
  166. t.Parallel()
  167. names := dirNames("testdata")
  168. expected := []string{"config", "default", "foo", "testfolder"}
  169. if diff, equal := messagediff.PrettyDiff(expected, names); !equal {
  170. t.Errorf("Unexpected dirNames return: %#v\n%s", names, diff)
  171. }
  172. }
  173. type httpTestCase struct {
  174. URL string // URL to check
  175. Code int // Expected result code
  176. Type string // Expected content type
  177. Prefix string // Expected result prefix
  178. Timeout time.Duration // Defaults to a second
  179. }
  180. func TestAPIServiceRequests(t *testing.T) {
  181. t.Parallel()
  182. baseURL, cancel, err := startHTTP(apiCfg)
  183. if err != nil {
  184. t.Fatal(err)
  185. }
  186. t.Cleanup(cancel)
  187. cases := []httpTestCase{
  188. // /rest/db
  189. {
  190. URL: "/rest/db/completion?device=" + protocol.LocalDeviceID.String() + "&folder=default",
  191. Code: 200,
  192. Type: "application/json",
  193. Prefix: "{",
  194. Timeout: 15 * time.Second,
  195. },
  196. {
  197. URL: "/rest/db/file?folder=default&file=something",
  198. Code: 404,
  199. },
  200. {
  201. URL: "/rest/db/ignores?folder=default",
  202. Code: 200,
  203. Type: "application/json",
  204. Prefix: "{",
  205. },
  206. {
  207. URL: "/rest/db/need?folder=default",
  208. Code: 200,
  209. Type: "application/json",
  210. Prefix: "{",
  211. },
  212. {
  213. URL: "/rest/db/status?folder=default",
  214. Code: 200,
  215. Type: "application/json",
  216. Prefix: "{",
  217. },
  218. {
  219. URL: "/rest/db/browse?folder=default",
  220. Code: 200,
  221. Type: "application/json",
  222. Prefix: "null",
  223. },
  224. {
  225. URL: "/rest/db/status?folder=default",
  226. Code: 200,
  227. Type: "application/json",
  228. Prefix: "",
  229. },
  230. // /rest/stats
  231. {
  232. URL: "/rest/stats/device",
  233. Code: 200,
  234. Type: "application/json",
  235. Prefix: "null",
  236. },
  237. {
  238. URL: "/rest/stats/folder",
  239. Code: 200,
  240. Type: "application/json",
  241. Prefix: "null",
  242. },
  243. // /rest/svc
  244. {
  245. URL: "/rest/svc/deviceid?id=" + protocol.LocalDeviceID.String(),
  246. Code: 200,
  247. Type: "application/json",
  248. Prefix: "{",
  249. },
  250. {
  251. URL: "/rest/svc/lang",
  252. Code: 200,
  253. Type: "application/json",
  254. Prefix: "[",
  255. },
  256. {
  257. URL: "/rest/svc/report",
  258. Code: 200,
  259. Type: "application/json",
  260. Prefix: "{",
  261. Timeout: 5 * time.Second,
  262. },
  263. // /rest/system
  264. {
  265. URL: "/rest/system/browse?current=~",
  266. Code: 200,
  267. Type: "application/json",
  268. Prefix: "[",
  269. },
  270. {
  271. URL: "/rest/system/config",
  272. Code: 200,
  273. Type: "application/json",
  274. Prefix: "{",
  275. },
  276. {
  277. URL: "/rest/system/config/insync",
  278. Code: 200,
  279. Type: "application/json",
  280. Prefix: "{",
  281. },
  282. {
  283. URL: "/rest/system/connections",
  284. Code: 200,
  285. Type: "application/json",
  286. Prefix: "null",
  287. },
  288. {
  289. URL: "/rest/system/discovery",
  290. Code: 200,
  291. Type: "application/json",
  292. Prefix: "{",
  293. },
  294. {
  295. URL: "/rest/system/error?since=0",
  296. Code: 200,
  297. Type: "application/json",
  298. Prefix: "{",
  299. },
  300. {
  301. URL: "/rest/system/ping",
  302. Code: 200,
  303. Type: "application/json",
  304. Prefix: "{",
  305. },
  306. {
  307. URL: "/rest/system/status",
  308. Code: 200,
  309. Type: "application/json",
  310. Prefix: "{",
  311. },
  312. {
  313. URL: "/rest/system/version",
  314. Code: 200,
  315. Type: "application/json",
  316. Prefix: "{",
  317. },
  318. {
  319. URL: "/rest/system/debug",
  320. Code: 200,
  321. Type: "application/json",
  322. Prefix: "{",
  323. },
  324. {
  325. URL: "/rest/system/log?since=0",
  326. Code: 200,
  327. Type: "application/json",
  328. Prefix: "{",
  329. },
  330. {
  331. URL: "/rest/system/log.txt?since=0",
  332. Code: 200,
  333. Type: "text/plain",
  334. Prefix: "",
  335. },
  336. // /rest/config
  337. {
  338. URL: "/rest/config",
  339. Code: 200,
  340. Type: "application/json",
  341. Prefix: "",
  342. },
  343. {
  344. URL: "/rest/config/folders",
  345. Code: 200,
  346. Type: "application/json",
  347. Prefix: "",
  348. },
  349. {
  350. URL: "/rest/config/folders/missing",
  351. Code: 404,
  352. Type: "text/plain",
  353. Prefix: "",
  354. },
  355. {
  356. URL: "/rest/config/devices",
  357. Code: 200,
  358. Type: "application/json",
  359. Prefix: "",
  360. },
  361. {
  362. URL: "/rest/config/devices/illegalid",
  363. Code: 400,
  364. Type: "text/plain",
  365. Prefix: "",
  366. },
  367. {
  368. URL: "/rest/config/devices/" + protocol.GlobalDeviceID.String(),
  369. Code: 404,
  370. Type: "text/plain",
  371. Prefix: "",
  372. },
  373. {
  374. URL: "/rest/config/options",
  375. Code: 200,
  376. Type: "application/json",
  377. Prefix: "{",
  378. },
  379. {
  380. URL: "/rest/config/gui",
  381. Code: 200,
  382. Type: "application/json",
  383. Prefix: "{",
  384. },
  385. {
  386. URL: "/rest/config/ldap",
  387. Code: 200,
  388. Type: "application/json",
  389. Prefix: "{",
  390. },
  391. }
  392. for _, tc := range cases {
  393. tc := tc
  394. t.Run(tc.URL, func(t *testing.T) {
  395. t.Parallel()
  396. testHTTPRequest(t, baseURL, tc, testAPIKey)
  397. })
  398. }
  399. }
  400. // testHTTPRequest tries the given test case, comparing the result code,
  401. // content type, and result prefix.
  402. func testHTTPRequest(t *testing.T, baseURL string, tc httpTestCase, apikey string) {
  403. // Since running tests in parallel, the previous 1s timeout proved to be too short.
  404. // https://github.com/syncthing/syncthing/issues/9455
  405. timeout := 10 * time.Second
  406. if tc.Timeout > 0 {
  407. timeout = tc.Timeout
  408. }
  409. cli := &http.Client{
  410. Timeout: timeout,
  411. }
  412. req, err := http.NewRequest("GET", baseURL+tc.URL, nil)
  413. if err != nil {
  414. t.Errorf("Unexpected error requesting %s: %v", tc.URL, err)
  415. return
  416. }
  417. req.Header.Set("X-API-Key", apikey)
  418. resp, err := cli.Do(req)
  419. if err != nil {
  420. t.Errorf("Unexpected error requesting %s: %v", tc.URL, err)
  421. return
  422. }
  423. defer resp.Body.Close()
  424. if resp.StatusCode != tc.Code {
  425. t.Errorf("Get on %s should have returned status code %d, not %s", tc.URL, tc.Code, resp.Status)
  426. return
  427. }
  428. ct := resp.Header.Get("Content-Type")
  429. if !strings.HasPrefix(ct, tc.Type) {
  430. t.Errorf("The content type on %s should be %q, not %q", tc.URL, tc.Type, ct)
  431. return
  432. }
  433. data, err := io.ReadAll(resp.Body)
  434. if err != nil {
  435. t.Errorf("Unexpected error reading %s: %v", tc.URL, err)
  436. return
  437. }
  438. if !bytes.HasPrefix(data, []byte(tc.Prefix)) {
  439. t.Errorf("Returned data from %s does not have prefix %q: %s", tc.URL, tc.Prefix, data)
  440. return
  441. }
  442. }
  443. func hasSessionCookie(cookies []*http.Cookie) bool {
  444. for _, cookie := range cookies {
  445. if cookie.MaxAge >= 0 && strings.HasPrefix(cookie.Name, "sessionid") {
  446. return true
  447. }
  448. }
  449. return false
  450. }
  451. func hasDeleteSessionCookie(cookies []*http.Cookie) bool {
  452. for _, cookie := range cookies {
  453. if cookie.MaxAge < 0 && strings.HasPrefix(cookie.Name, "sessionid") {
  454. return true
  455. }
  456. }
  457. return false
  458. }
  459. func httpGet(url string, basicAuthUsername string, basicAuthPassword string, xapikeyHeader string, authorizationBearer string, cookies []*http.Cookie, t *testing.T) *http.Response {
  460. req, err := http.NewRequest("GET", url, nil)
  461. for _, cookie := range cookies {
  462. req.AddCookie(cookie)
  463. }
  464. if err != nil {
  465. t.Fatal(err)
  466. }
  467. if basicAuthUsername != "" || basicAuthPassword != "" {
  468. req.SetBasicAuth(basicAuthUsername, basicAuthPassword)
  469. }
  470. if xapikeyHeader != "" {
  471. req.Header.Set("X-API-Key", xapikeyHeader)
  472. }
  473. if authorizationBearer != "" {
  474. req.Header.Set("Authorization", "Bearer "+authorizationBearer)
  475. }
  476. resp, err := http.DefaultClient.Do(req)
  477. if err != nil {
  478. t.Fatal(err)
  479. }
  480. return resp
  481. }
  482. func httpPost(url string, body map[string]string, cookies []*http.Cookie, t *testing.T) *http.Response {
  483. bodyBytes, err := json.Marshal(body)
  484. if err != nil {
  485. t.Fatal(err)
  486. }
  487. req, err := http.NewRequest("POST", url, bytes.NewReader(bodyBytes))
  488. if err != nil {
  489. t.Fatal(err)
  490. }
  491. for _, cookie := range cookies {
  492. req.AddCookie(cookie)
  493. }
  494. resp, err := http.DefaultClient.Do(req)
  495. if err != nil {
  496. t.Fatal(err)
  497. }
  498. return resp
  499. }
  500. func TestHTTPLogin(t *testing.T) {
  501. t.Parallel()
  502. httpGetBasicAuth := func(url string, username string, password string) *http.Response {
  503. return httpGet(url, username, password, "", "", nil, t)
  504. }
  505. httpGetXapikey := func(url string, xapikeyHeader string) *http.Response {
  506. return httpGet(url, "", "", xapikeyHeader, "", nil, t)
  507. }
  508. httpGetAuthorizationBearer := func(url string, bearer string) *http.Response {
  509. return httpGet(url, "", "", "", bearer, nil, t)
  510. }
  511. testWith := func(sendBasicAuthPrompt bool, expectedOkStatus int, expectedFailStatus int, path string) {
  512. cfg := newMockedConfig()
  513. cfg.GUIReturns(config.GUIConfiguration{
  514. User: "üser",
  515. Password: "$2a$10$IdIZTxTg/dCNuNEGlmLynOjqg4B1FvDKuIV5e0BB3pnWVHNb8.GSq", // bcrypt of "räksmörgås" in UTF-8
  516. RawAddress: "127.0.0.1:0",
  517. APIKey: testAPIKey,
  518. SendBasicAuthPrompt: sendBasicAuthPrompt,
  519. })
  520. baseURL, cancel, err := startHTTP(cfg)
  521. if err != nil {
  522. t.Fatal(err)
  523. }
  524. t.Cleanup(cancel)
  525. url := baseURL + path
  526. t.Run(fmt.Sprintf("%d path", expectedOkStatus), func(t *testing.T) {
  527. t.Run("no auth is rejected", func(t *testing.T) {
  528. t.Parallel()
  529. resp := httpGetBasicAuth(url, "", "")
  530. if resp.StatusCode != expectedFailStatus {
  531. t.Errorf("Unexpected non-%d return code %d for unauthed request", expectedFailStatus, resp.StatusCode)
  532. }
  533. if hasSessionCookie(resp.Cookies()) {
  534. t.Errorf("Unexpected session cookie for unauthed request")
  535. }
  536. })
  537. t.Run("incorrect password is rejected", func(t *testing.T) {
  538. t.Parallel()
  539. resp := httpGetBasicAuth(url, "üser", "rksmrgs")
  540. if resp.StatusCode != expectedFailStatus {
  541. t.Errorf("Unexpected non-%d return code %d for incorrect password", expectedFailStatus, resp.StatusCode)
  542. }
  543. if hasSessionCookie(resp.Cookies()) {
  544. t.Errorf("Unexpected session cookie for incorrect password")
  545. }
  546. })
  547. t.Run("incorrect username is rejected", func(t *testing.T) {
  548. t.Parallel()
  549. resp := httpGetBasicAuth(url, "user", "räksmörgås") // string literals in Go source code are in UTF-8
  550. if resp.StatusCode != expectedFailStatus {
  551. t.Errorf("Unexpected non-%d return code %d for incorrect username", expectedFailStatus, resp.StatusCode)
  552. }
  553. if hasSessionCookie(resp.Cookies()) {
  554. t.Errorf("Unexpected session cookie for incorrect username")
  555. }
  556. })
  557. t.Run("UTF-8 auth works", func(t *testing.T) {
  558. t.Parallel()
  559. resp := httpGetBasicAuth(url, "üser", "räksmörgås") // string literals in Go source code are in UTF-8
  560. if resp.StatusCode != expectedOkStatus {
  561. t.Errorf("Unexpected non-%d return code %d for authed request (UTF-8)", expectedOkStatus, resp.StatusCode)
  562. }
  563. if !hasSessionCookie(resp.Cookies()) {
  564. t.Errorf("Expected session cookie for authed request (UTF-8)")
  565. }
  566. })
  567. t.Run("Logout removes the session cookie", func(t *testing.T) {
  568. t.Parallel()
  569. resp := httpGetBasicAuth(url, "üser", "räksmörgås") // string literals in Go source code are in UTF-8
  570. if resp.StatusCode != expectedOkStatus {
  571. t.Errorf("Unexpected non-%d return code %d for authed request (UTF-8)", expectedOkStatus, resp.StatusCode)
  572. }
  573. if !hasSessionCookie(resp.Cookies()) {
  574. t.Errorf("Expected session cookie for authed request (UTF-8)")
  575. }
  576. logoutResp := httpPost(baseURL+"/rest/noauth/auth/logout", nil, resp.Cookies(), t)
  577. if !hasDeleteSessionCookie(logoutResp.Cookies()) {
  578. t.Errorf("Expected session cookie to be deleted for logout request")
  579. }
  580. })
  581. t.Run("Session cookie is invalid after logout", func(t *testing.T) {
  582. t.Parallel()
  583. loginResp := httpGetBasicAuth(url, "üser", "räksmörgås") // string literals in Go source code are in UTF-8
  584. if loginResp.StatusCode != expectedOkStatus {
  585. t.Errorf("Unexpected non-%d return code %d for authed request (UTF-8)", expectedOkStatus, loginResp.StatusCode)
  586. }
  587. if !hasSessionCookie(loginResp.Cookies()) {
  588. t.Errorf("Expected session cookie for authed request (UTF-8)")
  589. }
  590. resp := httpGet(url, "", "", "", "", loginResp.Cookies(), t)
  591. if resp.StatusCode != expectedOkStatus {
  592. t.Errorf("Unexpected non-%d return code %d for cookie-authed request (UTF-8)", expectedOkStatus, resp.StatusCode)
  593. }
  594. httpPost(baseURL+"/rest/noauth/auth/logout", nil, loginResp.Cookies(), t)
  595. resp = httpGet(url, "", "", "", "", loginResp.Cookies(), t)
  596. if resp.StatusCode != expectedFailStatus {
  597. t.Errorf("Expected session to be invalid (status %d) after logout, got status: %d", expectedFailStatus, resp.StatusCode)
  598. }
  599. })
  600. t.Run("ISO-8859-1 auth works", func(t *testing.T) {
  601. t.Parallel()
  602. resp := httpGetBasicAuth(url, "\xfcser", "r\xe4ksm\xf6rg\xe5s") // escaped ISO-8859-1
  603. if resp.StatusCode != expectedOkStatus {
  604. t.Errorf("Unexpected non-%d return code %d for authed request (ISO-8859-1)", expectedOkStatus, resp.StatusCode)
  605. }
  606. if !hasSessionCookie(resp.Cookies()) {
  607. t.Errorf("Expected session cookie for authed request (ISO-8859-1)")
  608. }
  609. })
  610. t.Run("bad X-API-Key is rejected", func(t *testing.T) {
  611. t.Parallel()
  612. resp := httpGetXapikey(url, testAPIKey+"X")
  613. if resp.StatusCode != expectedFailStatus {
  614. t.Errorf("Unexpected non-%d return code %d for bad API key", expectedFailStatus, resp.StatusCode)
  615. }
  616. if hasSessionCookie(resp.Cookies()) {
  617. t.Errorf("Unexpected session cookie for bad API key")
  618. }
  619. })
  620. t.Run("good X-API-Key is accepted", func(t *testing.T) {
  621. t.Parallel()
  622. resp := httpGetXapikey(url, testAPIKey)
  623. if resp.StatusCode != expectedOkStatus {
  624. t.Errorf("Unexpected non-%d return code %d for API key", expectedOkStatus, resp.StatusCode)
  625. }
  626. if hasSessionCookie(resp.Cookies()) {
  627. t.Errorf("Unexpected session cookie for API key")
  628. }
  629. })
  630. t.Run("bad Bearer is rejected", func(t *testing.T) {
  631. t.Parallel()
  632. resp := httpGetAuthorizationBearer(url, testAPIKey+"X")
  633. if resp.StatusCode != expectedFailStatus {
  634. t.Errorf("Unexpected non-%d return code %d for bad Authorization: Bearer", expectedFailStatus, resp.StatusCode)
  635. }
  636. if hasSessionCookie(resp.Cookies()) {
  637. t.Errorf("Unexpected session cookie for bad Authorization: Bearer")
  638. }
  639. })
  640. t.Run("good Bearer is accepted", func(t *testing.T) {
  641. t.Parallel()
  642. resp := httpGetAuthorizationBearer(url, testAPIKey)
  643. if resp.StatusCode != expectedOkStatus {
  644. t.Errorf("Unexpected non-%d return code %d for Authorization: Bearer", expectedOkStatus, resp.StatusCode)
  645. }
  646. if hasSessionCookie(resp.Cookies()) {
  647. t.Errorf("Unexpected session cookie for bad Authorization: Bearer")
  648. }
  649. })
  650. })
  651. }
  652. testWith(true, http.StatusOK, http.StatusOK, "/")
  653. testWith(true, http.StatusOK, http.StatusUnauthorized, "/meta.js")
  654. testWith(true, http.StatusNotFound, http.StatusUnauthorized, "/any-path/that/does/nooooooot/match-any/noauth-pattern")
  655. testWith(false, http.StatusOK, http.StatusOK, "/")
  656. testWith(false, http.StatusOK, http.StatusForbidden, "/meta.js")
  657. testWith(false, http.StatusNotFound, http.StatusForbidden, "/any-path/that/does/nooooooot/match-any/noauth-pattern")
  658. }
  659. func TestHtmlFormLogin(t *testing.T) {
  660. t.Parallel()
  661. cfg := newMockedConfig()
  662. cfg.GUIReturns(config.GUIConfiguration{
  663. User: "üser",
  664. Password: "$2a$10$IdIZTxTg/dCNuNEGlmLynOjqg4B1FvDKuIV5e0BB3pnWVHNb8.GSq", // bcrypt of "räksmörgås" in UTF-8
  665. SendBasicAuthPrompt: false,
  666. })
  667. baseURL, cancel, err := startHTTP(cfg)
  668. if err != nil {
  669. t.Fatal(err)
  670. }
  671. t.Cleanup(cancel)
  672. loginUrl := baseURL + "/rest/noauth/auth/password"
  673. resourceUrl := baseURL + "/meta.js"
  674. resourceUrl404 := baseURL + "/any-path/that/does/nooooooot/match-any/noauth-pattern"
  675. performLogin := func(username string, password string) *http.Response {
  676. return httpPost(loginUrl, map[string]string{"username": username, "password": password}, nil, t)
  677. }
  678. performResourceRequest := func(url string, cookies []*http.Cookie) *http.Response {
  679. return httpGet(url, "", "", "", "", cookies, t)
  680. }
  681. testNoAuthPath := func(noAuthPath string) {
  682. t.Run("auth is not needed for "+noAuthPath, func(t *testing.T) {
  683. t.Parallel()
  684. resp := httpGet(baseURL+noAuthPath, "", "", "", "", nil, t)
  685. if resp.StatusCode != http.StatusOK {
  686. t.Errorf("Unexpected non-200 return code %d at %s", resp.StatusCode, noAuthPath)
  687. }
  688. if hasSessionCookie(resp.Cookies()) {
  689. t.Errorf("Unexpected session cookie at " + noAuthPath)
  690. }
  691. })
  692. }
  693. testNoAuthPath("/index.html")
  694. testNoAuthPath("/rest/svc/lang")
  695. t.Run("incorrect password is rejected with 403", func(t *testing.T) {
  696. t.Parallel()
  697. resp := performLogin("üser", "rksmrgs") // string literals in Go source code are in UTF-8
  698. if resp.StatusCode != http.StatusForbidden {
  699. t.Errorf("Unexpected non-403 return code %d for incorrect password", resp.StatusCode)
  700. }
  701. if hasSessionCookie(resp.Cookies()) {
  702. t.Errorf("Unexpected session cookie for incorrect password")
  703. }
  704. resp = performResourceRequest(resourceUrl, resp.Cookies())
  705. if resp.StatusCode != http.StatusForbidden {
  706. t.Errorf("Unexpected non-403 return code %d for incorrect password", resp.StatusCode)
  707. }
  708. })
  709. t.Run("incorrect username is rejected with 403", func(t *testing.T) {
  710. t.Parallel()
  711. resp := performLogin("user", "räksmörgås") // string literals in Go source code are in UTF-8
  712. if resp.StatusCode != http.StatusForbidden {
  713. t.Errorf("Unexpected non-403 return code %d for incorrect username", resp.StatusCode)
  714. }
  715. if hasSessionCookie(resp.Cookies()) {
  716. t.Errorf("Unexpected session cookie for incorrect username")
  717. }
  718. resp = performResourceRequest(resourceUrl, resp.Cookies())
  719. if resp.StatusCode != http.StatusForbidden {
  720. t.Errorf("Unexpected non-403 return code %d for incorrect username", resp.StatusCode)
  721. }
  722. })
  723. t.Run("UTF-8 auth works", func(t *testing.T) {
  724. t.Parallel()
  725. // JSON is always UTF-8, so ISO-8859-1 case is not applicable
  726. resp := performLogin("üser", "räksmörgås") // string literals in Go source code are in UTF-8
  727. if resp.StatusCode != http.StatusNoContent {
  728. t.Errorf("Unexpected non-204 return code %d for authed request (UTF-8)", resp.StatusCode)
  729. }
  730. resp = performResourceRequest(resourceUrl, resp.Cookies())
  731. if resp.StatusCode != http.StatusOK {
  732. t.Errorf("Unexpected non-200 return code %d for authed request (UTF-8)", resp.StatusCode)
  733. }
  734. })
  735. t.Run("Logout removes the session cookie", func(t *testing.T) {
  736. t.Parallel()
  737. // JSON is always UTF-8, so ISO-8859-1 case is not applicable
  738. resp := performLogin("üser", "räksmörgås") // string literals in Go source code are in UTF-8
  739. if resp.StatusCode != http.StatusNoContent {
  740. t.Errorf("Unexpected non-204 return code %d for authed request (UTF-8)", resp.StatusCode)
  741. }
  742. logoutResp := httpPost(baseURL+"/rest/noauth/auth/logout", nil, resp.Cookies(), t)
  743. if !hasDeleteSessionCookie(logoutResp.Cookies()) {
  744. t.Errorf("Expected session cookie to be deleted for logout request")
  745. }
  746. })
  747. t.Run("Session cookie is invalid after logout", func(t *testing.T) {
  748. t.Parallel()
  749. // JSON is always UTF-8, so ISO-8859-1 case is not applicable
  750. loginResp := performLogin("üser", "räksmörgås") // string literals in Go source code are in UTF-8
  751. if loginResp.StatusCode != http.StatusNoContent {
  752. t.Errorf("Unexpected non-204 return code %d for authed request (UTF-8)", loginResp.StatusCode)
  753. }
  754. resp := performResourceRequest(resourceUrl, loginResp.Cookies())
  755. if resp.StatusCode != http.StatusOK {
  756. t.Errorf("Unexpected non-200 return code %d for authed request (UTF-8)", resp.StatusCode)
  757. }
  758. httpPost(baseURL+"/rest/noauth/auth/logout", nil, loginResp.Cookies(), t)
  759. resp = performResourceRequest(resourceUrl, loginResp.Cookies())
  760. if resp.StatusCode != http.StatusForbidden {
  761. t.Errorf("Expected session to be invalid (status 403) after logout, got status: %d", resp.StatusCode)
  762. }
  763. })
  764. t.Run("form login is not applicable to other URLs", func(t *testing.T) {
  765. t.Parallel()
  766. resp := httpPost(baseURL+"/meta.js", map[string]string{"username": "üser", "password": "räksmörgås"}, nil, t)
  767. if resp.StatusCode != http.StatusForbidden {
  768. t.Errorf("Unexpected non-403 return code %d for incorrect form login URL", resp.StatusCode)
  769. }
  770. if hasSessionCookie(resp.Cookies()) {
  771. t.Errorf("Unexpected session cookie for incorrect form login URL")
  772. }
  773. })
  774. t.Run("invalid URL returns 403 before auth and 404 after auth", func(t *testing.T) {
  775. t.Parallel()
  776. resp := performResourceRequest(resourceUrl404, nil)
  777. if resp.StatusCode != http.StatusForbidden {
  778. t.Errorf("Unexpected non-403 return code %d for unauthed request", resp.StatusCode)
  779. }
  780. resp = performLogin("üser", "räksmörgås")
  781. if resp.StatusCode != http.StatusNoContent {
  782. t.Errorf("Unexpected non-204 return code %d for authed request", resp.StatusCode)
  783. }
  784. resp = performResourceRequest(resourceUrl404, resp.Cookies())
  785. if resp.StatusCode != http.StatusNotFound {
  786. t.Errorf("Unexpected non-404 return code %d for authed request", resp.StatusCode)
  787. }
  788. })
  789. }
  790. func TestApiCache(t *testing.T) {
  791. t.Parallel()
  792. cfg := newMockedConfig()
  793. cfg.GUIReturns(config.GUIConfiguration{
  794. RawAddress: "127.0.0.1:0",
  795. APIKey: testAPIKey,
  796. })
  797. baseURL, cancel, err := startHTTP(cfg)
  798. if err != nil {
  799. t.Fatal(err)
  800. }
  801. t.Cleanup(cancel)
  802. httpGet := func(url string, bearer string) *http.Response {
  803. return httpGet(url, "", "", "", bearer, nil, t)
  804. }
  805. t.Run("meta.js has no-cache headers", func(t *testing.T) {
  806. t.Parallel()
  807. url := baseURL + "/meta.js"
  808. resp := httpGet(url, testAPIKey)
  809. if resp.Header.Get("Cache-Control") != "max-age=0, no-cache, no-store" {
  810. t.Errorf("Expected no-cache headers at %s", url)
  811. }
  812. })
  813. t.Run("/rest/ has no-cache headers", func(t *testing.T) {
  814. t.Parallel()
  815. url := baseURL + "/rest/system/version"
  816. resp := httpGet(url, testAPIKey)
  817. if resp.Header.Get("Cache-Control") != "max-age=0, no-cache, no-store" {
  818. t.Errorf("Expected no-cache headers at %s", url)
  819. }
  820. })
  821. }
  822. func startHTTP(cfg config.Wrapper) (string, context.CancelFunc, error) {
  823. m := new(modelmocks.Model)
  824. assetDir := "../../gui"
  825. eventSub := new(eventmocks.BufferedSubscription)
  826. diskEventSub := new(eventmocks.BufferedSubscription)
  827. discoverer := new(discovermocks.Manager)
  828. connections := new(connmocks.Service)
  829. errorLog := new(loggermocks.Recorder)
  830. systemLog := new(loggermocks.Recorder)
  831. for _, l := range []*loggermocks.Recorder{errorLog, systemLog} {
  832. l.SinceReturns([]logger.Line{
  833. {
  834. When: time.Now(),
  835. Message: "Test message",
  836. },
  837. })
  838. }
  839. addrChan := make(chan string)
  840. mockedSummary := &modelmocks.FolderSummaryService{}
  841. mockedSummary.SummaryReturns(new(model.FolderSummary), nil)
  842. // Instantiate the API service
  843. urService := ur.New(cfg, m, connections, false)
  844. mdb, _ := db.NewLowlevel(backend.OpenMemory(), events.NoopLogger)
  845. kdb := db.NewMiscDataNamespace(mdb)
  846. svc := New(protocol.LocalDeviceID, cfg, assetDir, "syncthing", m, eventSub, diskEventSub, events.NoopLogger, discoverer, connections, urService, mockedSummary, errorLog, systemLog, false, kdb).(*service)
  847. svc.started = addrChan
  848. // Actually start the API service
  849. supervisor := suture.New("API test", suture.Spec{
  850. PassThroughPanics: true,
  851. })
  852. supervisor.Add(svc)
  853. ctx, cancel := context.WithCancel(context.Background())
  854. supervisor.ServeBackground(ctx)
  855. // Make sure the API service is listening, and get the URL to use.
  856. addr := <-addrChan
  857. tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
  858. if err != nil {
  859. cancel()
  860. return "", cancel, fmt.Errorf("weird address from API service: %w", err)
  861. }
  862. host, _, _ := net.SplitHostPort(cfg.GUI().RawAddress)
  863. if host == "" || host == "0.0.0.0" {
  864. host = "127.0.0.1"
  865. }
  866. baseURL := fmt.Sprintf("http://%s", net.JoinHostPort(host, strconv.Itoa(tcpAddr.Port)))
  867. return baseURL, cancel, nil
  868. }
  869. func TestCSRFRequired(t *testing.T) {
  870. t.Parallel()
  871. baseURL, cancel, err := startHTTP(apiCfg)
  872. if err != nil {
  873. t.Fatal("Unexpected error from getting base URL:", err)
  874. }
  875. t.Cleanup(cancel)
  876. cli := &http.Client{
  877. Timeout: time.Minute,
  878. }
  879. // Getting the base URL (i.e. "/") should succeed.
  880. resp, err := cli.Get(baseURL)
  881. if err != nil {
  882. t.Fatal("Unexpected error from getting base URL:", err)
  883. }
  884. resp.Body.Close()
  885. if resp.StatusCode != http.StatusOK {
  886. t.Fatal("Getting base URL should succeed, not", resp.Status)
  887. }
  888. // Find the returned CSRF token for future use
  889. var csrfTokenName, csrfTokenValue string
  890. for _, cookie := range resp.Cookies() {
  891. if strings.HasPrefix(cookie.Name, "CSRF-Token") {
  892. csrfTokenName = cookie.Name
  893. csrfTokenValue = cookie.Value
  894. break
  895. }
  896. }
  897. if csrfTokenValue == "" {
  898. t.Fatal("Failed to initialize CSRF test: no CSRF cookie returned from " + baseURL)
  899. }
  900. t.Run("/rest without a token should fail", func(t *testing.T) {
  901. t.Parallel()
  902. resp, err := cli.Get(baseURL + "/rest/system/config")
  903. if err != nil {
  904. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  905. }
  906. resp.Body.Close()
  907. if resp.StatusCode != http.StatusForbidden {
  908. t.Fatal("Getting /rest/system/config without CSRF token should fail, not", resp.Status)
  909. }
  910. })
  911. t.Run("/rest with a token should succeed", func(t *testing.T) {
  912. t.Parallel()
  913. req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
  914. req.Header.Set("X-"+csrfTokenName, csrfTokenValue)
  915. resp, err := cli.Do(req)
  916. if err != nil {
  917. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  918. }
  919. resp.Body.Close()
  920. if resp.StatusCode != http.StatusOK {
  921. t.Fatal("Getting /rest/system/config with CSRF token should succeed, not", resp.Status)
  922. }
  923. })
  924. t.Run("/rest with an incorrect API key should fail, X-API-Key version", func(t *testing.T) {
  925. t.Parallel()
  926. req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
  927. req.Header.Set("X-API-Key", testAPIKey+"X")
  928. resp, err := cli.Do(req)
  929. if err != nil {
  930. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  931. }
  932. resp.Body.Close()
  933. if resp.StatusCode != http.StatusForbidden {
  934. t.Fatal("Getting /rest/system/config with incorrect API token should fail, not", resp.Status)
  935. }
  936. })
  937. t.Run("/rest with an incorrect API key should fail, Bearer auth version", func(t *testing.T) {
  938. t.Parallel()
  939. req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
  940. req.Header.Set("Authorization", "Bearer "+testAPIKey+"X")
  941. resp, err := cli.Do(req)
  942. if err != nil {
  943. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  944. }
  945. resp.Body.Close()
  946. if resp.StatusCode != http.StatusForbidden {
  947. t.Fatal("Getting /rest/system/config with incorrect API token should fail, not", resp.Status)
  948. }
  949. })
  950. t.Run("/rest with the API key should succeed", func(t *testing.T) {
  951. t.Parallel()
  952. req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
  953. req.Header.Set("X-API-Key", testAPIKey)
  954. resp, err := cli.Do(req)
  955. if err != nil {
  956. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  957. }
  958. resp.Body.Close()
  959. if resp.StatusCode != http.StatusOK {
  960. t.Fatal("Getting /rest/system/config with API key should succeed, not", resp.Status)
  961. }
  962. })
  963. t.Run("/rest with the API key as a bearer token should succeed", func(t *testing.T) {
  964. t.Parallel()
  965. req, _ := http.NewRequest("GET", baseURL+"/rest/system/config", nil)
  966. req.Header.Set("Authorization", "Bearer "+testAPIKey)
  967. resp, err := cli.Do(req)
  968. if err != nil {
  969. t.Fatal("Unexpected error from getting /rest/system/config:", err)
  970. }
  971. resp.Body.Close()
  972. if resp.StatusCode != http.StatusOK {
  973. t.Fatal("Getting /rest/system/config with API key should succeed, not", resp.Status)
  974. }
  975. })
  976. }
  977. func TestRandomString(t *testing.T) {
  978. t.Parallel()
  979. baseURL, cancel, err := startHTTP(apiCfg)
  980. if err != nil {
  981. t.Fatal(err)
  982. }
  983. defer cancel()
  984. cli := &http.Client{
  985. Timeout: time.Second,
  986. }
  987. // The default should be to return a 32 character random string
  988. for _, url := range []string{"/rest/svc/random/string", "/rest/svc/random/string?length=-1", "/rest/svc/random/string?length=yo"} {
  989. req, _ := http.NewRequest("GET", baseURL+url, nil)
  990. req.Header.Set("X-API-Key", testAPIKey)
  991. resp, err := cli.Do(req)
  992. if err != nil {
  993. t.Fatal(err)
  994. }
  995. var res map[string]string
  996. if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
  997. t.Fatal(err)
  998. }
  999. if len(res["random"]) != 32 {
  1000. t.Errorf("Expected 32 random characters, got %q of length %d", res["random"], len(res["random"]))
  1001. }
  1002. }
  1003. // We can ask for a different length if we like
  1004. req, _ := http.NewRequest("GET", baseURL+"/rest/svc/random/string?length=27", nil)
  1005. req.Header.Set("X-API-Key", testAPIKey)
  1006. resp, err := cli.Do(req)
  1007. if err != nil {
  1008. t.Fatal(err)
  1009. }
  1010. var res map[string]string
  1011. if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
  1012. t.Fatal(err)
  1013. }
  1014. if len(res["random"]) != 27 {
  1015. t.Errorf("Expected 27 random characters, got %q of length %d", res["random"], len(res["random"]))
  1016. }
  1017. }
  1018. func TestConfigPostOK(t *testing.T) {
  1019. t.Parallel()
  1020. cfg := bytes.NewBuffer([]byte(`{
  1021. "version": 15,
  1022. "folders": [
  1023. {
  1024. "id": "foo",
  1025. "path": "TestConfigPostOK"
  1026. }
  1027. ]
  1028. }`))
  1029. resp, err := testConfigPost(cfg)
  1030. if err != nil {
  1031. t.Fatal(err)
  1032. }
  1033. if resp.StatusCode != http.StatusOK {
  1034. t.Error("Expected 200 OK, not", resp.Status)
  1035. }
  1036. os.RemoveAll("TestConfigPostOK")
  1037. }
  1038. func TestConfigPostDupFolder(t *testing.T) {
  1039. t.Parallel()
  1040. cfg := bytes.NewBuffer([]byte(`{
  1041. "version": 15,
  1042. "folders": [
  1043. {"id": "foo"},
  1044. {"id": "foo"}
  1045. ]
  1046. }`))
  1047. resp, err := testConfigPost(cfg)
  1048. if err != nil {
  1049. t.Fatal(err)
  1050. }
  1051. if resp.StatusCode != http.StatusBadRequest {
  1052. t.Error("Expected 400 Bad Request, not", resp.Status)
  1053. }
  1054. }
  1055. func testConfigPost(data io.Reader) (*http.Response, error) {
  1056. baseURL, cancel, err := startHTTP(apiCfg)
  1057. if err != nil {
  1058. return nil, err
  1059. }
  1060. defer cancel()
  1061. cli := &http.Client{
  1062. Timeout: time.Second,
  1063. }
  1064. req, _ := http.NewRequest("POST", baseURL+"/rest/system/config", data)
  1065. req.Header.Set("X-API-Key", testAPIKey)
  1066. return cli.Do(req)
  1067. }
  1068. func TestHostCheck(t *testing.T) {
  1069. t.Parallel()
  1070. // An API service bound to localhost should reject non-localhost host Headers
  1071. cfg := newMockedConfig()
  1072. cfg.GUIReturns(config.GUIConfiguration{RawAddress: "127.0.0.1:0"})
  1073. baseURL, cancel, err := startHTTP(cfg)
  1074. if err != nil {
  1075. t.Fatal(err)
  1076. }
  1077. defer cancel()
  1078. // A normal HTTP get to the localhost-bound service should succeed
  1079. resp, err := http.Get(baseURL)
  1080. if err != nil {
  1081. t.Fatal(err)
  1082. }
  1083. resp.Body.Close()
  1084. if resp.StatusCode != http.StatusOK {
  1085. t.Error("Regular HTTP get: expected 200 OK, not", resp.Status)
  1086. }
  1087. // A request with a suspicious Host header should fail
  1088. req, _ := http.NewRequest("GET", baseURL, nil)
  1089. req.Host = "example.com"
  1090. resp, err = http.DefaultClient.Do(req)
  1091. if err != nil {
  1092. t.Fatal(err)
  1093. }
  1094. resp.Body.Close()
  1095. if resp.StatusCode != http.StatusForbidden {
  1096. t.Error("Suspicious Host header: expected 403 Forbidden, not", resp.Status)
  1097. }
  1098. // A request with an explicit "localhost:8384" Host header should pass
  1099. req, _ = http.NewRequest("GET", baseURL, nil)
  1100. req.Host = "localhost:8384"
  1101. resp, err = http.DefaultClient.Do(req)
  1102. if err != nil {
  1103. t.Fatal(err)
  1104. }
  1105. resp.Body.Close()
  1106. if resp.StatusCode != http.StatusOK {
  1107. t.Error("Explicit localhost:8384: expected 200 OK, not", resp.Status)
  1108. }
  1109. // A request with an explicit "localhost" Host header (no port) should pass
  1110. req, _ = http.NewRequest("GET", baseURL, nil)
  1111. req.Host = "localhost"
  1112. resp, err = http.DefaultClient.Do(req)
  1113. if err != nil {
  1114. t.Fatal(err)
  1115. }
  1116. resp.Body.Close()
  1117. if resp.StatusCode != http.StatusOK {
  1118. t.Error("Explicit localhost: expected 200 OK, not", resp.Status)
  1119. }
  1120. // A server with InsecureSkipHostCheck set behaves differently
  1121. cfg = newMockedConfig()
  1122. cfg.GUIReturns(config.GUIConfiguration{
  1123. RawAddress: "127.0.0.1:0",
  1124. InsecureSkipHostCheck: true,
  1125. })
  1126. baseURL, cancel, err = startHTTP(cfg)
  1127. if err != nil {
  1128. t.Fatal(err)
  1129. }
  1130. defer cancel()
  1131. // A request with a suspicious Host header should be allowed
  1132. req, _ = http.NewRequest("GET", baseURL, nil)
  1133. req.Host = "example.com"
  1134. resp, err = http.DefaultClient.Do(req)
  1135. if err != nil {
  1136. t.Fatal(err)
  1137. }
  1138. resp.Body.Close()
  1139. if resp.StatusCode != http.StatusOK {
  1140. t.Error("Incorrect host header, check disabled: expected 200 OK, not", resp.Status)
  1141. }
  1142. if !testing.Short() {
  1143. // A server bound to a wildcard address also doesn't do the check
  1144. cfg = newMockedConfig()
  1145. cfg.GUIReturns(config.GUIConfiguration{
  1146. RawAddress: "0.0.0.0:0",
  1147. })
  1148. baseURL, cancel, err = startHTTP(cfg)
  1149. if err != nil {
  1150. t.Fatal(err)
  1151. }
  1152. defer cancel()
  1153. // A request with a suspicious Host header should be allowed
  1154. req, _ = http.NewRequest("GET", baseURL, nil)
  1155. req.Host = "example.com"
  1156. resp, err = http.DefaultClient.Do(req)
  1157. if err != nil {
  1158. t.Fatal(err)
  1159. }
  1160. resp.Body.Close()
  1161. if resp.StatusCode != http.StatusOK {
  1162. t.Error("Incorrect host header, wildcard bound: expected 200 OK, not", resp.Status)
  1163. }
  1164. }
  1165. // This should all work over IPv6 as well
  1166. if runningInContainer() {
  1167. // Working IPv6 in Docker can't be taken for granted.
  1168. return
  1169. }
  1170. cfg = newMockedConfig()
  1171. cfg.GUIReturns(config.GUIConfiguration{
  1172. RawAddress: "[::1]:0",
  1173. })
  1174. baseURL, cancel, err = startHTTP(cfg)
  1175. if err != nil {
  1176. t.Fatal(err)
  1177. }
  1178. defer cancel()
  1179. // A normal HTTP get to the localhost-bound service should succeed
  1180. resp, err = http.Get(baseURL)
  1181. if err != nil {
  1182. t.Fatal(err)
  1183. }
  1184. resp.Body.Close()
  1185. if resp.StatusCode != http.StatusOK {
  1186. t.Error("Regular HTTP get (IPv6): expected 200 OK, not", resp.Status)
  1187. }
  1188. // A request with a suspicious Host header should fail
  1189. req, _ = http.NewRequest("GET", baseURL, nil)
  1190. req.Host = "example.com"
  1191. resp, err = http.DefaultClient.Do(req)
  1192. if err != nil {
  1193. t.Fatal(err)
  1194. }
  1195. resp.Body.Close()
  1196. if resp.StatusCode != http.StatusForbidden {
  1197. t.Error("Suspicious Host header (IPv6): expected 403 Forbidden, not", resp.Status)
  1198. }
  1199. // A request with an explicit "localhost:8384" Host header should pass
  1200. req, _ = http.NewRequest("GET", baseURL, nil)
  1201. req.Host = "localhost:8384"
  1202. resp, err = http.DefaultClient.Do(req)
  1203. if err != nil {
  1204. t.Fatal(err)
  1205. }
  1206. resp.Body.Close()
  1207. if resp.StatusCode != http.StatusOK {
  1208. t.Error("Explicit localhost:8384 (IPv6): expected 200 OK, not", resp.Status)
  1209. }
  1210. }
  1211. func TestAddressIsLocalhost(t *testing.T) {
  1212. t.Parallel()
  1213. testcases := []struct {
  1214. address string
  1215. result bool
  1216. }{
  1217. // These are all valid localhost addresses
  1218. {"localhost", true},
  1219. {"LOCALHOST", true},
  1220. {"localhost.", true},
  1221. {"::1", true},
  1222. {"127.0.0.1", true},
  1223. {"127.23.45.56", true},
  1224. {"localhost:8080", true},
  1225. {"LOCALHOST:8000", true},
  1226. {"localhost.:8080", true},
  1227. {"[::1]:8080", true},
  1228. {"127.0.0.1:8080", true},
  1229. {"127.23.45.56:8080", true},
  1230. {"www.localhost", true},
  1231. {"www.localhost:8080", true},
  1232. // These are all non-localhost addresses
  1233. {"example.com", false},
  1234. {"example.com:8080", false},
  1235. {"localhost.com", false},
  1236. {"localhost.com:8080", false},
  1237. {"192.0.2.10", false},
  1238. {"192.0.2.10:8080", false},
  1239. {"0.0.0.0", false},
  1240. {"0.0.0.0:8080", false},
  1241. {"::", false},
  1242. {"[::]:8080", false},
  1243. {":8080", false},
  1244. }
  1245. for _, tc := range testcases {
  1246. result := addressIsLocalhost(tc.address)
  1247. if result != tc.result {
  1248. t.Errorf("addressIsLocalhost(%q)=%v, expected %v", tc.address, result, tc.result)
  1249. }
  1250. }
  1251. }
  1252. func TestAccessControlAllowOriginHeader(t *testing.T) {
  1253. t.Parallel()
  1254. baseURL, cancel, err := startHTTP(apiCfg)
  1255. if err != nil {
  1256. t.Fatal(err)
  1257. }
  1258. defer cancel()
  1259. cli := &http.Client{
  1260. Timeout: time.Second,
  1261. }
  1262. req, _ := http.NewRequest("GET", baseURL+"/rest/system/status", nil)
  1263. req.Header.Set("X-API-Key", testAPIKey)
  1264. resp, err := cli.Do(req)
  1265. if err != nil {
  1266. t.Fatal(err)
  1267. }
  1268. resp.Body.Close()
  1269. if resp.StatusCode != http.StatusOK {
  1270. t.Fatal("GET on /rest/system/status should succeed, not", resp.Status)
  1271. }
  1272. if resp.Header.Get("Access-Control-Allow-Origin") != "*" {
  1273. t.Fatal("GET on /rest/system/status should return a 'Access-Control-Allow-Origin: *' header")
  1274. }
  1275. }
  1276. func TestOptionsRequest(t *testing.T) {
  1277. t.Parallel()
  1278. baseURL, cancel, err := startHTTP(apiCfg)
  1279. if err != nil {
  1280. t.Fatal(err)
  1281. }
  1282. defer cancel()
  1283. cli := &http.Client{
  1284. Timeout: time.Second,
  1285. }
  1286. req, _ := http.NewRequest("OPTIONS", baseURL+"/rest/system/status", nil)
  1287. resp, err := cli.Do(req)
  1288. if err != nil {
  1289. t.Fatal(err)
  1290. }
  1291. resp.Body.Close()
  1292. if resp.StatusCode != http.StatusNoContent {
  1293. t.Fatal("OPTIONS on /rest/system/status should succeed, not", resp.Status)
  1294. }
  1295. if resp.Header.Get("Access-Control-Allow-Origin") != "*" {
  1296. t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Origin: *' header")
  1297. }
  1298. if resp.Header.Get("Access-Control-Allow-Methods") != "GET, POST, PUT, PATCH, DELETE, OPTIONS" {
  1299. t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS' header")
  1300. }
  1301. if resp.Header.Get("Access-Control-Allow-Headers") != "Content-Type, X-API-Key" {
  1302. t.Fatal("OPTIONS on /rest/system/status should return a 'Access-Control-Allow-Headers: Content-Type, X-API-KEY' header")
  1303. }
  1304. }
  1305. func TestEventMasks(t *testing.T) {
  1306. t.Parallel()
  1307. cfg := newMockedConfig()
  1308. defSub := new(eventmocks.BufferedSubscription)
  1309. diskSub := new(eventmocks.BufferedSubscription)
  1310. mdb, _ := db.NewLowlevel(backend.OpenMemory(), events.NoopLogger)
  1311. kdb := db.NewMiscDataNamespace(mdb)
  1312. svc := New(protocol.LocalDeviceID, cfg, "", "syncthing", nil, defSub, diskSub, events.NoopLogger, nil, nil, nil, nil, nil, nil, false, kdb).(*service)
  1313. if mask := svc.getEventMask(""); mask != DefaultEventMask {
  1314. t.Errorf("incorrect default mask %x != %x", int64(mask), int64(DefaultEventMask))
  1315. }
  1316. expected := events.FolderSummary | events.LocalChangeDetected
  1317. if mask := svc.getEventMask("FolderSummary,LocalChangeDetected"); mask != expected {
  1318. t.Errorf("incorrect parsed mask %x != %x", int64(mask), int64(expected))
  1319. }
  1320. expected = 0
  1321. if mask := svc.getEventMask("WeirdEvent,something else that doesn't exist"); mask != expected {
  1322. t.Errorf("incorrect parsed mask %x != %x", int64(mask), int64(expected))
  1323. }
  1324. if res := svc.getEventSub(DefaultEventMask); res != defSub {
  1325. t.Errorf("should have returned the given default event sub")
  1326. }
  1327. if res := svc.getEventSub(DiskEventMask); res != diskSub {
  1328. t.Errorf("should have returned the given disk event sub")
  1329. }
  1330. if res := svc.getEventSub(events.LocalIndexUpdated); res == nil || res == defSub || res == diskSub {
  1331. t.Errorf("should have returned a valid, non-default event sub")
  1332. }
  1333. }
  1334. func TestBrowse(t *testing.T) {
  1335. t.Parallel()
  1336. pathSep := string(os.PathSeparator)
  1337. ffs := fs.NewFilesystem(fs.FilesystemTypeFake, rand.String(32)+"?nostfolder=true")
  1338. _ = ffs.Mkdir("dir", 0o755)
  1339. _ = fs.WriteFile(ffs, "file", []byte("hello"), 0o644)
  1340. _ = ffs.Mkdir("MiXEDCase", 0o755)
  1341. // We expect completion to return the full path to the completed
  1342. // directory, with an ending slash.
  1343. dirPath := "dir" + pathSep
  1344. mixedCaseDirPath := "MiXEDCase" + pathSep
  1345. cases := []struct {
  1346. current string
  1347. returns []string
  1348. }{
  1349. // The directory without slash is completed to one with slash.
  1350. {"dir", []string{"dir" + pathSep}},
  1351. // With slash it's completed to its contents.
  1352. // Dirs are given pathSeps.
  1353. // Files are not returned.
  1354. {"", []string{mixedCaseDirPath, dirPath}},
  1355. // Globbing is automatic based on prefix.
  1356. {"d", []string{dirPath}},
  1357. {"di", []string{dirPath}},
  1358. {"dir", []string{dirPath}},
  1359. {"f", nil},
  1360. {"q", nil},
  1361. // Globbing is case-insensitive
  1362. {"mixed", []string{mixedCaseDirPath}},
  1363. }
  1364. for _, tc := range cases {
  1365. ret := browseFiles(ffs, tc.current)
  1366. if !slices.Equal(ret, tc.returns) {
  1367. t.Errorf("browseFiles(%q) => %q, expected %q", tc.current, ret, tc.returns)
  1368. }
  1369. }
  1370. }
  1371. func TestPrefixMatch(t *testing.T) {
  1372. t.Parallel()
  1373. cases := []struct {
  1374. s string
  1375. prefix string
  1376. expected int
  1377. }{
  1378. {"aaaA", "aaa", matchExact},
  1379. {"AAAX", "BBB", noMatch},
  1380. {"AAAX", "aAa", matchCaseIns},
  1381. {"äÜX", "äü", matchCaseIns},
  1382. }
  1383. for _, tc := range cases {
  1384. ret := checkPrefixMatch(tc.s, tc.prefix)
  1385. if ret != tc.expected {
  1386. t.Errorf("checkPrefixMatch(%q, %q) => %v, expected %v", tc.s, tc.prefix, ret, tc.expected)
  1387. }
  1388. }
  1389. }
  1390. func TestShouldRegenerateCertificate(t *testing.T) {
  1391. // Self signed certificates expiring in less than a month are errored so we
  1392. // can regenerate in time.
  1393. crt, err := tlsutil.NewCertificateInMemory("foo.example.com", 29)
  1394. if err != nil {
  1395. t.Fatal(err)
  1396. }
  1397. if err := shouldRegenerateCertificate(crt); err == nil {
  1398. t.Error("expected expiry error")
  1399. }
  1400. // Certificates with at least 31 days of life left are fine.
  1401. crt, err = tlsutil.NewCertificateInMemory("foo.example.com", 31)
  1402. if err != nil {
  1403. t.Fatal(err)
  1404. }
  1405. if err := shouldRegenerateCertificate(crt); err != nil {
  1406. t.Error("expected no error:", err)
  1407. }
  1408. if build.IsDarwin {
  1409. // Certificates with too long an expiry time are not allowed on macOS
  1410. crt, err = tlsutil.NewCertificateInMemory("foo.example.com", 1000)
  1411. if err != nil {
  1412. t.Fatal(err)
  1413. }
  1414. if err := shouldRegenerateCertificate(crt); err == nil {
  1415. t.Error("expected expiry error")
  1416. }
  1417. }
  1418. }
  1419. func TestConfigChanges(t *testing.T) {
  1420. t.Parallel()
  1421. const testAPIKey = "foobarbaz"
  1422. cfg := config.Configuration{
  1423. GUI: config.GUIConfiguration{
  1424. RawAddress: "127.0.0.1:0",
  1425. RawUseTLS: false,
  1426. APIKey: testAPIKey,
  1427. },
  1428. }
  1429. tmpFile, err := os.CreateTemp("", "syncthing-testConfig-")
  1430. if err != nil {
  1431. panic(err)
  1432. }
  1433. defer os.Remove(tmpFile.Name())
  1434. w := config.Wrap(tmpFile.Name(), cfg, protocol.LocalDeviceID, events.NoopLogger)
  1435. tmpFile.Close()
  1436. cfgCtx, cfgCancel := context.WithCancel(context.Background())
  1437. go w.Serve(cfgCtx)
  1438. defer cfgCancel()
  1439. baseURL, cancel, err := startHTTP(w)
  1440. if err != nil {
  1441. t.Fatal("Unexpected error from getting base URL:", err)
  1442. }
  1443. defer cancel()
  1444. cli := &http.Client{
  1445. Timeout: time.Minute,
  1446. }
  1447. do := func(req *http.Request, status int) *http.Response {
  1448. t.Helper()
  1449. req.Header.Set("X-API-Key", testAPIKey)
  1450. resp, err := cli.Do(req)
  1451. if err != nil {
  1452. t.Fatal(err)
  1453. }
  1454. if resp.StatusCode != status {
  1455. t.Errorf("Expected status %v, got %v", status, resp.StatusCode)
  1456. }
  1457. return resp
  1458. }
  1459. mod := func(method, path string, data interface{}) {
  1460. t.Helper()
  1461. bs, err := json.Marshal(data)
  1462. if err != nil {
  1463. t.Fatal(err)
  1464. }
  1465. req, _ := http.NewRequest(method, baseURL+path, bytes.NewReader(bs))
  1466. do(req, http.StatusOK).Body.Close()
  1467. }
  1468. get := func(path string) *http.Response {
  1469. t.Helper()
  1470. req, _ := http.NewRequest(http.MethodGet, baseURL+path, nil)
  1471. return do(req, http.StatusOK)
  1472. }
  1473. dev1Path := "/rest/config/devices/" + dev1.String()
  1474. // Create device
  1475. mod(http.MethodPut, "/rest/config/devices", []config.DeviceConfiguration{{DeviceID: dev1}})
  1476. // Check its there
  1477. get(dev1Path).Body.Close()
  1478. // Modify just a single attribute
  1479. mod(http.MethodPatch, dev1Path, map[string]bool{"Paused": true})
  1480. // Check that attribute
  1481. resp := get(dev1Path)
  1482. var dev config.DeviceConfiguration
  1483. if err := unmarshalTo(resp.Body, &dev); err != nil {
  1484. t.Fatal(err)
  1485. }
  1486. if !dev.Paused {
  1487. t.Error("Expected device to be paused")
  1488. }
  1489. folder2Path := "/rest/config/folders/folder2"
  1490. // Create a folder and add another
  1491. mod(http.MethodPut, "/rest/config/folders", []config.FolderConfiguration{{ID: "folder1", Path: "folder1"}})
  1492. mod(http.MethodPut, folder2Path, config.FolderConfiguration{ID: "folder2", Path: "folder2"})
  1493. // Check they are there
  1494. get("/rest/config/folders/folder1").Body.Close()
  1495. get(folder2Path).Body.Close()
  1496. // Modify just a single attribute
  1497. mod(http.MethodPatch, folder2Path, map[string]bool{"Paused": true})
  1498. // Check that attribute
  1499. resp = get(folder2Path)
  1500. var folder config.FolderConfiguration
  1501. if err := unmarshalTo(resp.Body, &folder); err != nil {
  1502. t.Fatal(err)
  1503. }
  1504. if !dev.Paused {
  1505. t.Error("Expected folder to be paused")
  1506. }
  1507. // Delete folder2
  1508. req, _ := http.NewRequest(http.MethodDelete, baseURL+folder2Path, nil)
  1509. do(req, http.StatusOK)
  1510. // Check folder1 is still there and folder2 gone
  1511. get("/rest/config/folders/folder1").Body.Close()
  1512. req, _ = http.NewRequest(http.MethodGet, baseURL+folder2Path, nil)
  1513. do(req, http.StatusNotFound)
  1514. mod(http.MethodPatch, "/rest/config/options", map[string]int{"maxSendKbps": 50})
  1515. resp = get("/rest/config/options")
  1516. var opts config.OptionsConfiguration
  1517. if err := unmarshalTo(resp.Body, &opts); err != nil {
  1518. t.Fatal(err)
  1519. }
  1520. if opts.MaxSendKbps != 50 {
  1521. t.Error("Expected 50 for MaxSendKbps, got", opts.MaxSendKbps)
  1522. }
  1523. }
  1524. func TestSanitizedHostname(t *testing.T) {
  1525. cases := []struct {
  1526. in, out string
  1527. }{
  1528. {"foo.BAR-baz", "foo.bar-baz"},
  1529. {"~.~-Min 1:a Räksmörgås-dator 😀😎 ~.~-", "min1araksmorgas-dator"},
  1530. {"Vicenç-PC", "vicenc-pc"},
  1531. {"~.~-~.~-", ""},
  1532. {"", ""},
  1533. }
  1534. for _, tc := range cases {
  1535. res, err := sanitizedHostname(tc.in)
  1536. if tc.out == "" && err == nil {
  1537. t.Errorf("%q should cause error", tc.in)
  1538. } else if res != tc.out {
  1539. t.Errorf("%q => %q, expected %q", tc.in, res, tc.out)
  1540. }
  1541. }
  1542. }
  1543. // runningInContainer returns true if we are inside Docker or LXC. It might
  1544. // be prone to false negatives if things change in the future, but likely
  1545. // not false positives.
  1546. func runningInContainer() bool {
  1547. if !build.IsLinux {
  1548. return false
  1549. }
  1550. bs, err := os.ReadFile("/proc/1/cgroup")
  1551. if err != nil {
  1552. return false
  1553. }
  1554. if bytes.Contains(bs, []byte("/docker/")) {
  1555. return true
  1556. }
  1557. if bytes.Contains(bs, []byte("/lxc/")) {
  1558. return true
  1559. }
  1560. return false
  1561. }