api_test.go 52 KB

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