api_test.go 49 KB

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