api_test.go 53 KB

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