api_test.go 50 KB

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