api_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. package api_test
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "net/http"
  8. "net/http/httptest"
  9. "os"
  10. "path/filepath"
  11. "runtime"
  12. "strconv"
  13. "testing"
  14. "time"
  15. "github.com/go-chi/render"
  16. _ "github.com/go-sql-driver/mysql"
  17. _ "github.com/lib/pq"
  18. _ "github.com/mattn/go-sqlite3"
  19. "github.com/rs/zerolog"
  20. "github.com/drakkan/sftpgo/api"
  21. "github.com/drakkan/sftpgo/config"
  22. "github.com/drakkan/sftpgo/dataprovider"
  23. "github.com/drakkan/sftpgo/logger"
  24. "github.com/drakkan/sftpgo/sftpd"
  25. )
  26. const (
  27. defaultUsername = "test_user"
  28. defaultPassword = "test_password"
  29. testPubKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC03jj0D+djk7pxIf/0OhrxrchJTRZklofJ1NoIu4752Sq02mdXmarMVsqJ1cAjV5LBVy3D1F5U6XW4rppkXeVtd04Pxb09ehtH0pRRPaoHHlALiJt8CoMpbKYMA8b3KXPPriGxgGomvtU2T2RMURSwOZbMtpsugfjYSWenyYX+VORYhylWnSXL961LTyC21ehd6d6QnW9G7E5hYMITMY9TuQZz3bROYzXiTsgN0+g6Hn7exFQp50p45StUMfV/SftCMdCxlxuyGny2CrN/vfjO7xxOo2uv7q1qm10Q46KPWJQv+pgZ/OfL+EDjy07n5QVSKHlbx+2nT4Q0EgOSQaCTYwn3YjtABfIxWwgAFdyj6YlPulCL22qU4MYhDcA6PSBwDdf8hvxBfvsiHdM+JcSHvv8/VeJhk6CmnZxGY0fxBupov27z3yEO8nAg8k+6PaUiW1MSUfuGMF/ktB8LOstXsEPXSszuyXiOv4DaryOXUiSn7bmRqKcEFlJusO6aZP0= nicola@p1"
  30. logSender = "APITesting"
  31. userPath = "/api/v1/user"
  32. activeConnectionsPath = "/api/v1/sftp_connection"
  33. quotaScanPath = "/api/v1/quota_scan"
  34. )
  35. var (
  36. defaultPerms = []string{dataprovider.PermAny}
  37. homeBasePath string
  38. testServer *httptest.Server
  39. )
  40. func TestMain(m *testing.M) {
  41. if runtime.GOOS == "windows" {
  42. homeBasePath = "C:\\"
  43. } else {
  44. homeBasePath = "/tmp"
  45. }
  46. configDir := ".."
  47. logfilePath := filepath.Join(configDir, "sftpgo_api_test.log")
  48. confName := "sftpgo.conf"
  49. logger.InitLogger(logfilePath, 5, 1, 28, false, zerolog.DebugLevel)
  50. configFilePath := filepath.Join(configDir, confName)
  51. config.LoadConfig(configFilePath)
  52. providerConf := config.GetProviderConf()
  53. err := dataprovider.Initialize(providerConf, configDir)
  54. if err != nil {
  55. logger.Warn(logSender, "error initializing data provider: %v", err)
  56. os.Exit(1)
  57. }
  58. dataProvider := dataprovider.GetProvider()
  59. httpdConf := config.GetHTTPDConfig()
  60. router := api.GetHTTPRouter()
  61. httpdConf.BindPort = 8081
  62. api.SetBaseURL("http://127.0.0.1:8081")
  63. sftpd.SetDataProvider(dataProvider)
  64. api.SetDataProvider(dataProvider)
  65. go func() {
  66. logger.Debug(logSender, "initializing HTTP server with config %+v", httpdConf)
  67. s := &http.Server{
  68. Addr: fmt.Sprintf("%s:%d", httpdConf.BindAddress, httpdConf.BindPort),
  69. Handler: router,
  70. ReadTimeout: 300 * time.Second,
  71. WriteTimeout: 300 * time.Second,
  72. MaxHeaderBytes: 1 << 20, // 1MB
  73. }
  74. if err := s.ListenAndServe(); err != nil {
  75. logger.Error(logSender, "could not start HTTP server: %v", err)
  76. }
  77. }()
  78. testServer = httptest.NewServer(api.GetHTTPRouter())
  79. defer testServer.Close()
  80. waitTCPListening(fmt.Sprintf("%s:%d", httpdConf.BindAddress, httpdConf.BindPort))
  81. exitCode := m.Run()
  82. os.Remove(logfilePath)
  83. os.Exit(exitCode)
  84. }
  85. func TestBasicUserHandling(t *testing.T) {
  86. user, err := api.AddUser(getTestUser(), http.StatusOK)
  87. if err != nil {
  88. t.Errorf("unable to add user: %v", err)
  89. }
  90. user.MaxSessions = 10
  91. user.QuotaSize = 4096
  92. user.QuotaFiles = 2
  93. user.UploadBandwidth = 128
  94. user.DownloadBandwidth = 64
  95. user, err = api.UpdateUser(user, http.StatusOK)
  96. if err != nil {
  97. t.Errorf("unable to update user: %v", err)
  98. }
  99. users, err := api.GetUsers(0, 0, defaultUsername, http.StatusOK)
  100. if err != nil {
  101. t.Errorf("unable to get users: %v", err)
  102. }
  103. if len(users) != 1 {
  104. t.Errorf("number of users mismatch, expected: 1, actual: %v", len(users))
  105. }
  106. err = api.RemoveUser(user, http.StatusOK)
  107. if err != nil {
  108. t.Errorf("unable to remove: %v", err)
  109. }
  110. }
  111. func TestAddUserNoCredentials(t *testing.T) {
  112. u := getTestUser()
  113. u.Password = ""
  114. u.PublicKey = ""
  115. _, err := api.AddUser(u, http.StatusBadRequest)
  116. if err != nil {
  117. t.Errorf("unexpected error adding user with no credentials: %v", err)
  118. }
  119. }
  120. func TestAddUserNoUsername(t *testing.T) {
  121. u := getTestUser()
  122. u.Username = ""
  123. _, err := api.AddUser(u, http.StatusBadRequest)
  124. if err != nil {
  125. t.Errorf("unexpected error adding user with no home dir: %v", err)
  126. }
  127. }
  128. func TestAddUserNoHomeDir(t *testing.T) {
  129. u := getTestUser()
  130. u.HomeDir = ""
  131. _, err := api.AddUser(u, http.StatusBadRequest)
  132. if err != nil {
  133. t.Errorf("unexpected error adding user with no home dir: %v", err)
  134. }
  135. }
  136. func TestAddUserInvalidHomeDir(t *testing.T) {
  137. u := getTestUser()
  138. u.HomeDir = "relative_path"
  139. _, err := api.AddUser(u, http.StatusBadRequest)
  140. if err != nil {
  141. t.Errorf("unexpected error adding user with invalid home dir: %v", err)
  142. }
  143. }
  144. func TestAddUserNoPerms(t *testing.T) {
  145. u := getTestUser()
  146. u.Permissions = []string{}
  147. _, err := api.AddUser(u, http.StatusBadRequest)
  148. if err != nil {
  149. t.Errorf("unexpected error adding user with no perms: %v", err)
  150. }
  151. }
  152. func TestAddUserInvalidPerms(t *testing.T) {
  153. u := getTestUser()
  154. u.Permissions = []string{"invalidPerm"}
  155. _, err := api.AddUser(u, http.StatusBadRequest)
  156. if err != nil {
  157. t.Errorf("unexpected error adding user with no perms: %v", err)
  158. }
  159. }
  160. func TestUserPublicKey(t *testing.T) {
  161. u := getTestUser()
  162. invalidPubKey := "invalid"
  163. validPubKey := "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC03jj0D+djk7pxIf/0OhrxrchJTRZklofJ1NoIu4752Sq02mdXmarMVsqJ1cAjV5LBVy3D1F5U6XW4rppkXeVtd04Pxb09ehtH0pRRPaoHHlALiJt8CoMpbKYMA8b3KXPPriGxgGomvtU2T2RMURSwOZbMtpsugfjYSWenyYX+VORYhylWnSXL961LTyC21ehd6d6QnW9G7E5hYMITMY9TuQZz3bROYzXiTsgN0+g6Hn7exFQp50p45StUMfV/SftCMdCxlxuyGny2CrN/vfjO7xxOo2uv7q1qm10Q46KPWJQv+pgZ/OfL+EDjy07n5QVSKHlbx+2nT4Q0EgOSQaCTYwn3YjtABfIxWwgAFdyj6YlPulCL22qU4MYhDcA6PSBwDdf8hvxBfvsiHdM+JcSHvv8/VeJhk6CmnZxGY0fxBupov27z3yEO8nAg8k+6PaUiW1MSUfuGMF/ktB8LOstXsEPXSszuyXiOv4DaryOXUiSn7bmRqKcEFlJusO6aZP0= nicola@p1"
  164. u.PublicKey = invalidPubKey
  165. _, err := api.AddUser(u, http.StatusBadRequest)
  166. if err != nil {
  167. t.Errorf("unexpected error adding user with invalid pub key: %v", err)
  168. }
  169. u.PublicKey = validPubKey
  170. user, err := api.AddUser(u, http.StatusOK)
  171. if err != nil {
  172. t.Errorf("unable to add user: %v", err)
  173. }
  174. user.PublicKey = validPubKey + "\n" + invalidPubKey
  175. _, err = api.UpdateUser(user, http.StatusBadRequest)
  176. if err != nil {
  177. t.Errorf("update user with invalid public key must fail: %v", err)
  178. }
  179. user.PublicKey = validPubKey + "\n" + validPubKey + "\n" + validPubKey
  180. _, err = api.UpdateUser(user, http.StatusOK)
  181. if err != nil {
  182. t.Errorf("unable to update user: %v", err)
  183. }
  184. err = api.RemoveUser(user, http.StatusOK)
  185. if err != nil {
  186. t.Errorf("unable to remove: %v", err)
  187. }
  188. }
  189. func TestUpdateUser(t *testing.T) {
  190. user, err := api.AddUser(getTestUser(), http.StatusOK)
  191. if err != nil {
  192. t.Errorf("unable to add user: %v", err)
  193. }
  194. user.HomeDir = filepath.Join(homeBasePath, "testmod")
  195. user.UID = 33
  196. user.GID = 101
  197. user.MaxSessions = 10
  198. user.QuotaSize = 4096
  199. user.QuotaFiles = 2
  200. user.Permissions = []string{dataprovider.PermCreateDirs, dataprovider.PermDelete, dataprovider.PermDownload}
  201. user.UploadBandwidth = 1024
  202. user.DownloadBandwidth = 512
  203. user, err = api.UpdateUser(user, http.StatusOK)
  204. if err != nil {
  205. t.Errorf("unable to update user: %v", err)
  206. }
  207. err = api.RemoveUser(user, http.StatusOK)
  208. if err != nil {
  209. t.Errorf("unable to remove: %v", err)
  210. }
  211. }
  212. func TestUpdateUserNoCredentials(t *testing.T) {
  213. user, err := api.AddUser(getTestUser(), http.StatusOK)
  214. if err != nil {
  215. t.Errorf("unable to add user: %v", err)
  216. }
  217. user.Password = ""
  218. user.PublicKey = ""
  219. // password and public key will be omitted from json serialization if empty and so they will remain unchanged
  220. // and no validation error will be raised
  221. _, err = api.UpdateUser(user, http.StatusOK)
  222. if err != nil {
  223. t.Errorf("unexpected error updating user with no credentials: %v", err)
  224. }
  225. err = api.RemoveUser(user, http.StatusOK)
  226. if err != nil {
  227. t.Errorf("unable to remove: %v", err)
  228. }
  229. }
  230. func TestUpdateUserEmptyHomeDir(t *testing.T) {
  231. user, err := api.AddUser(getTestUser(), http.StatusOK)
  232. if err != nil {
  233. t.Errorf("unable to add user: %v", err)
  234. }
  235. user.HomeDir = ""
  236. _, err = api.UpdateUser(user, http.StatusBadRequest)
  237. if err != nil {
  238. t.Errorf("unexpected error updating user with empty home dir: %v", err)
  239. }
  240. err = api.RemoveUser(user, http.StatusOK)
  241. if err != nil {
  242. t.Errorf("unable to remove: %v", err)
  243. }
  244. }
  245. func TestUpdateUserInvalidHomeDir(t *testing.T) {
  246. user, err := api.AddUser(getTestUser(), http.StatusOK)
  247. if err != nil {
  248. t.Errorf("unable to add user: %v", err)
  249. }
  250. user.HomeDir = "relative_path"
  251. _, err = api.UpdateUser(user, http.StatusBadRequest)
  252. if err != nil {
  253. t.Errorf("unexpected error updating user with empty home dir: %v", err)
  254. }
  255. err = api.RemoveUser(user, http.StatusOK)
  256. if err != nil {
  257. t.Errorf("unable to remove: %v", err)
  258. }
  259. }
  260. func TestUpdateNonExistentUser(t *testing.T) {
  261. _, err := api.UpdateUser(getTestUser(), http.StatusNotFound)
  262. if err != nil {
  263. t.Errorf("unable to update user: %v", err)
  264. }
  265. }
  266. func TestGetNonExistentUser(t *testing.T) {
  267. _, err := api.GetUserByID(0, http.StatusNotFound)
  268. if err != nil {
  269. t.Errorf("unable to get user: %v", err)
  270. }
  271. }
  272. func TestDeleteNonExistentUser(t *testing.T) {
  273. err := api.RemoveUser(getTestUser(), http.StatusNotFound)
  274. if err != nil {
  275. t.Errorf("unable to remove user: %v", err)
  276. }
  277. }
  278. func TestAddDuplicateUser(t *testing.T) {
  279. user, err := api.AddUser(getTestUser(), http.StatusOK)
  280. if err != nil {
  281. t.Errorf("unable to add user: %v", err)
  282. }
  283. _, err = api.AddUser(getTestUser(), http.StatusInternalServerError)
  284. if err != nil {
  285. t.Errorf("unable to add second user: %v", err)
  286. }
  287. err = api.RemoveUser(user, http.StatusOK)
  288. if err != nil {
  289. t.Errorf("unable to remove user: %v", err)
  290. }
  291. }
  292. func TestGetUsers(t *testing.T) {
  293. user1, err := api.AddUser(getTestUser(), http.StatusOK)
  294. if err != nil {
  295. t.Errorf("unable to add user: %v", err)
  296. }
  297. u := getTestUser()
  298. u.Username = defaultUsername + "1"
  299. user2, err := api.AddUser(u, http.StatusOK)
  300. if err != nil {
  301. t.Errorf("unable to add second user: %v", err)
  302. }
  303. users, err := api.GetUsers(0, 0, "", http.StatusOK)
  304. if err != nil {
  305. t.Errorf("unable to get users: %v", err)
  306. }
  307. if len(users) < 2 {
  308. t.Errorf("at least 2 users are expected")
  309. }
  310. users, err = api.GetUsers(1, 0, "", http.StatusOK)
  311. if err != nil {
  312. t.Errorf("unable to get users: %v", err)
  313. }
  314. if len(users) != 1 {
  315. t.Errorf("1 user is expected")
  316. }
  317. users, err = api.GetUsers(1, 1, "", http.StatusOK)
  318. if err != nil {
  319. t.Errorf("unable to get users: %v", err)
  320. }
  321. if len(users) != 1 {
  322. t.Errorf("1 user is expected")
  323. }
  324. err = api.RemoveUser(user1, http.StatusOK)
  325. if err != nil {
  326. t.Errorf("unable to remove user: %v", err)
  327. }
  328. err = api.RemoveUser(user2, http.StatusOK)
  329. if err != nil {
  330. t.Errorf("unable to remove user: %v", err)
  331. }
  332. }
  333. func TestGetQuotaScans(t *testing.T) {
  334. _, err := api.GetQuotaScans(http.StatusOK)
  335. if err != nil {
  336. t.Errorf("unable to get quota scans: %v", err)
  337. }
  338. }
  339. func TestStartQuotaScan(t *testing.T) {
  340. user, err := api.AddUser(getTestUser(), http.StatusOK)
  341. if err != nil {
  342. t.Errorf("unable to add user: %v", err)
  343. }
  344. err = api.StartQuotaScan(user, http.StatusCreated)
  345. if err != nil {
  346. t.Errorf("unable to start quota scan: %v", err)
  347. }
  348. err = api.RemoveUser(user, http.StatusOK)
  349. if err != nil {
  350. t.Errorf("unable to remove user: %v", err)
  351. }
  352. }
  353. // test using mock http server
  354. func TestBasicUserHandlingMock(t *testing.T) {
  355. user := getTestUser()
  356. userAsJSON := getUserAsJSON(t, user)
  357. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  358. rr := executeRequest(req)
  359. checkResponseCode(t, http.StatusOK, rr.Code)
  360. err := render.DecodeJSON(rr.Body, &user)
  361. if err != nil {
  362. t.Errorf("Error get user: %v", err)
  363. }
  364. req, _ = http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  365. rr = executeRequest(req)
  366. checkResponseCode(t, http.StatusInternalServerError, rr.Code)
  367. user.MaxSessions = 10
  368. user.UploadBandwidth = 128
  369. userAsJSON = getUserAsJSON(t, user)
  370. req, _ = http.NewRequest(http.MethodPut, userPath+"/"+strconv.FormatInt(user.ID, 10), bytes.NewBuffer(userAsJSON))
  371. rr = executeRequest(req)
  372. checkResponseCode(t, http.StatusOK, rr.Code)
  373. req, _ = http.NewRequest(http.MethodGet, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  374. rr = executeRequest(req)
  375. checkResponseCode(t, http.StatusOK, rr.Code)
  376. var updatedUser dataprovider.User
  377. err = render.DecodeJSON(rr.Body, &updatedUser)
  378. if err != nil {
  379. t.Errorf("Error decoding updated user: %v", err)
  380. }
  381. if user.MaxSessions != updatedUser.MaxSessions || user.UploadBandwidth != updatedUser.UploadBandwidth {
  382. t.Errorf("Error modifying user actual: %v, %v", updatedUser.MaxSessions, updatedUser.UploadBandwidth)
  383. }
  384. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  385. rr = executeRequest(req)
  386. checkResponseCode(t, http.StatusOK, rr.Code)
  387. }
  388. func TestGetUserByIdInvalidParamsMock(t *testing.T) {
  389. req, _ := http.NewRequest(http.MethodGet, userPath+"/0", nil)
  390. rr := executeRequest(req)
  391. checkResponseCode(t, http.StatusNotFound, rr.Code)
  392. req, _ = http.NewRequest(http.MethodGet, userPath+"/a", nil)
  393. rr = executeRequest(req)
  394. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  395. }
  396. func TestAddUserNoUsernameMock(t *testing.T) {
  397. user := getTestUser()
  398. user.Username = ""
  399. userAsJSON := getUserAsJSON(t, user)
  400. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  401. rr := executeRequest(req)
  402. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  403. }
  404. func TestAddUserInvalidHomeDirMock(t *testing.T) {
  405. user := getTestUser()
  406. user.HomeDir = "relative_path"
  407. userAsJSON := getUserAsJSON(t, user)
  408. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  409. rr := executeRequest(req)
  410. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  411. }
  412. func TestAddUserInvalidPermsMock(t *testing.T) {
  413. user := getTestUser()
  414. user.Permissions = []string{}
  415. userAsJSON := getUserAsJSON(t, user)
  416. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  417. rr := executeRequest(req)
  418. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  419. }
  420. func TestAddUserInvalidJsonMock(t *testing.T) {
  421. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer([]byte("invalid json")))
  422. rr := executeRequest(req)
  423. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  424. }
  425. func TestUpdateUserInvalidJsonMock(t *testing.T) {
  426. user := getTestUser()
  427. userAsJSON := getUserAsJSON(t, user)
  428. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  429. rr := executeRequest(req)
  430. checkResponseCode(t, http.StatusOK, rr.Code)
  431. err := render.DecodeJSON(rr.Body, &user)
  432. if err != nil {
  433. t.Errorf("Error get user: %v", err)
  434. }
  435. req, _ = http.NewRequest(http.MethodPut, userPath+"/"+strconv.FormatInt(user.ID, 10), bytes.NewBuffer([]byte("Invalid json")))
  436. rr = executeRequest(req)
  437. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  438. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  439. rr = executeRequest(req)
  440. checkResponseCode(t, http.StatusOK, rr.Code)
  441. }
  442. func TestUpdateUserInvalidParamsMock(t *testing.T) {
  443. user := getTestUser()
  444. userAsJSON := getUserAsJSON(t, user)
  445. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  446. rr := executeRequest(req)
  447. checkResponseCode(t, http.StatusOK, rr.Code)
  448. err := render.DecodeJSON(rr.Body, &user)
  449. if err != nil {
  450. t.Errorf("Error get user: %v", err)
  451. }
  452. user.HomeDir = ""
  453. userAsJSON = getUserAsJSON(t, user)
  454. req, _ = http.NewRequest(http.MethodPut, userPath+"/"+strconv.FormatInt(user.ID, 10), bytes.NewBuffer(userAsJSON))
  455. rr = executeRequest(req)
  456. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  457. userID := user.ID
  458. user.ID = 0
  459. userAsJSON = getUserAsJSON(t, user)
  460. req, _ = http.NewRequest(http.MethodPut, userPath+"/"+strconv.FormatInt(userID, 10), bytes.NewBuffer(userAsJSON))
  461. rr = executeRequest(req)
  462. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  463. user.ID = userID
  464. req, _ = http.NewRequest(http.MethodPut, userPath+"/0", bytes.NewBuffer(userAsJSON))
  465. rr = executeRequest(req)
  466. checkResponseCode(t, http.StatusNotFound, rr.Code)
  467. req, _ = http.NewRequest(http.MethodPut, userPath+"/a", bytes.NewBuffer(userAsJSON))
  468. rr = executeRequest(req)
  469. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  470. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  471. rr = executeRequest(req)
  472. checkResponseCode(t, http.StatusOK, rr.Code)
  473. }
  474. func TestGetUsersMock(t *testing.T) {
  475. user := getTestUser()
  476. userAsJSON := getUserAsJSON(t, user)
  477. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  478. rr := executeRequest(req)
  479. checkResponseCode(t, http.StatusOK, rr.Code)
  480. err := render.DecodeJSON(rr.Body, &user)
  481. if err != nil {
  482. t.Errorf("Error get user: %v", err)
  483. }
  484. req, _ = http.NewRequest(http.MethodGet, userPath+"?limit=510&offset=0&order=ASC&username="+defaultUsername, nil)
  485. rr = executeRequest(req)
  486. checkResponseCode(t, http.StatusOK, rr.Code)
  487. var users []dataprovider.User
  488. err = render.DecodeJSON(rr.Body, &users)
  489. if err != nil {
  490. t.Errorf("Error decoding users: %v", err)
  491. }
  492. if len(users) != 1 {
  493. t.Errorf("1 user is expected")
  494. }
  495. req, _ = http.NewRequest(http.MethodGet, userPath+"?limit=a&offset=0&order=ASC", nil)
  496. rr = executeRequest(req)
  497. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  498. req, _ = http.NewRequest(http.MethodGet, userPath+"?limit=1&offset=a&order=ASC", nil)
  499. rr = executeRequest(req)
  500. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  501. req, _ = http.NewRequest(http.MethodGet, userPath+"?limit=1&offset=0&order=ASCa", nil)
  502. rr = executeRequest(req)
  503. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  504. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  505. rr = executeRequest(req)
  506. checkResponseCode(t, http.StatusOK, rr.Code)
  507. }
  508. func TestDeleteUserInvalidParamsMock(t *testing.T) {
  509. req, _ := http.NewRequest(http.MethodDelete, userPath+"/0", nil)
  510. rr := executeRequest(req)
  511. checkResponseCode(t, http.StatusNotFound, rr.Code)
  512. req, _ = http.NewRequest(http.MethodDelete, userPath+"/a", nil)
  513. rr = executeRequest(req)
  514. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  515. }
  516. func TestGetQuotaScansMock(t *testing.T) {
  517. req, err := http.NewRequest("GET", quotaScanPath, nil)
  518. if err != nil {
  519. t.Errorf("error get quota scan: %v", err)
  520. }
  521. rr := executeRequest(req)
  522. checkResponseCode(t, http.StatusOK, rr.Code)
  523. }
  524. func TestStartQuotaScanMock(t *testing.T) {
  525. user := getTestUser()
  526. userAsJSON := getUserAsJSON(t, user)
  527. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  528. rr := executeRequest(req)
  529. checkResponseCode(t, http.StatusOK, rr.Code)
  530. err := render.DecodeJSON(rr.Body, &user)
  531. if err != nil {
  532. t.Errorf("Error get user: %v", err)
  533. }
  534. _, err = os.Stat(user.HomeDir)
  535. if err == nil {
  536. os.Remove(user.HomeDir)
  537. }
  538. userAsJSON = getUserAsJSON(t, user)
  539. req, _ = http.NewRequest(http.MethodPost, quotaScanPath, bytes.NewBuffer(userAsJSON))
  540. rr = executeRequest(req)
  541. checkResponseCode(t, http.StatusCreated, rr.Code)
  542. req, _ = http.NewRequest(http.MethodGet, quotaScanPath, nil)
  543. rr = executeRequest(req)
  544. checkResponseCode(t, http.StatusOK, rr.Code)
  545. var scans []sftpd.ActiveQuotaScan
  546. err = render.DecodeJSON(rr.Body, &scans)
  547. if err != nil {
  548. t.Errorf("Error get active scans: %v", err)
  549. }
  550. for len(scans) > 0 {
  551. req, _ = http.NewRequest(http.MethodGet, quotaScanPath, nil)
  552. rr = executeRequest(req)
  553. checkResponseCode(t, http.StatusOK, rr.Code)
  554. err = render.DecodeJSON(rr.Body, &scans)
  555. if err != nil {
  556. t.Errorf("Error get active scans: %v", err)
  557. break
  558. }
  559. }
  560. _, err = os.Stat(user.HomeDir)
  561. if err != nil && os.IsNotExist(err) {
  562. os.MkdirAll(user.HomeDir, 0777)
  563. }
  564. req, _ = http.NewRequest(http.MethodPost, quotaScanPath, bytes.NewBuffer(userAsJSON))
  565. rr = executeRequest(req)
  566. checkResponseCode(t, http.StatusCreated, rr.Code)
  567. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  568. rr = executeRequest(req)
  569. checkResponseCode(t, http.StatusOK, rr.Code)
  570. }
  571. func TestStartQuotaScanBadUserMock(t *testing.T) {
  572. user := getTestUser()
  573. userAsJSON := getUserAsJSON(t, user)
  574. req, _ := http.NewRequest(http.MethodPost, quotaScanPath, bytes.NewBuffer(userAsJSON))
  575. rr := executeRequest(req)
  576. checkResponseCode(t, http.StatusNotFound, rr.Code)
  577. }
  578. func TestStartQuotaScanNonExistentUserMock(t *testing.T) {
  579. req, _ := http.NewRequest(http.MethodPost, quotaScanPath, bytes.NewBuffer([]byte("invalid json")))
  580. rr := executeRequest(req)
  581. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  582. }
  583. func TestGetSFTPConnectionsMock(t *testing.T) {
  584. req, _ := http.NewRequest(http.MethodGet, activeConnectionsPath, nil)
  585. rr := executeRequest(req)
  586. checkResponseCode(t, http.StatusOK, rr.Code)
  587. }
  588. func TestDeleteActiveConnectionMock(t *testing.T) {
  589. req, _ := http.NewRequest(http.MethodDelete, activeConnectionsPath+"/connectionID", nil)
  590. rr := executeRequest(req)
  591. checkResponseCode(t, http.StatusNotFound, rr.Code)
  592. }
  593. func TestNotFoundMock(t *testing.T) {
  594. req, _ := http.NewRequest(http.MethodGet, "/non/existing/path", nil)
  595. rr := executeRequest(req)
  596. checkResponseCode(t, http.StatusNotFound, rr.Code)
  597. }
  598. func TestMethodNotAllowedMock(t *testing.T) {
  599. req, _ := http.NewRequest(http.MethodPost, activeConnectionsPath, nil)
  600. rr := executeRequest(req)
  601. checkResponseCode(t, http.StatusMethodNotAllowed, rr.Code)
  602. }
  603. func waitTCPListening(address string) {
  604. for {
  605. conn, err := net.Dial("tcp", address)
  606. if err != nil {
  607. logger.WarnToConsole("tcp server %v not listening: %v\n", address, err)
  608. time.Sleep(100 * time.Millisecond)
  609. continue
  610. }
  611. logger.InfoToConsole("tcp server %v now listening\n", address)
  612. defer conn.Close()
  613. break
  614. }
  615. }
  616. func getTestUser() dataprovider.User {
  617. return dataprovider.User{
  618. Username: defaultUsername,
  619. Password: defaultPassword,
  620. HomeDir: filepath.Join(homeBasePath, defaultUsername),
  621. Permissions: defaultPerms,
  622. }
  623. }
  624. func getUserAsJSON(t *testing.T, user dataprovider.User) []byte {
  625. json, err := json.Marshal(user)
  626. if err != nil {
  627. t.Errorf("error get user as json: %v", err)
  628. return []byte("{}")
  629. }
  630. return json
  631. }
  632. func executeRequest(req *http.Request) *httptest.ResponseRecorder {
  633. rr := httptest.NewRecorder()
  634. testServer.Config.Handler.ServeHTTP(rr, req)
  635. return rr
  636. }
  637. func checkResponseCode(t *testing.T, expected, actual int) {
  638. if expected != actual {
  639. t.Errorf("Expected response code %d. Got %d", expected, actual)
  640. }
  641. }