api_test.go 54 KB

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