api_test.go 49 KB

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