api_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  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 = []string{}
  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 = []string{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 = []string{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 = []string{validPubKey, 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 = []string{validPubKey, validPubKey, 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 = []string{}
  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. func TestGetSFTPConnections(t *testing.T) {
  354. _, err := api.GetSFTPConnections(http.StatusOK)
  355. if err != nil {
  356. t.Errorf("unable to get sftp connections: %v", err)
  357. }
  358. }
  359. func TestCloseActiveSFTPConnection(t *testing.T) {
  360. err := api.CloseSFTPConnection("non_existent_id", http.StatusNotFound)
  361. if err != nil {
  362. t.Errorf("unexpected error closing non existent sftp connection: %v", err)
  363. }
  364. }
  365. // test using mock http server
  366. func TestBasicUserHandlingMock(t *testing.T) {
  367. user := getTestUser()
  368. userAsJSON := getUserAsJSON(t, user)
  369. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  370. rr := executeRequest(req)
  371. checkResponseCode(t, http.StatusOK, rr.Code)
  372. err := render.DecodeJSON(rr.Body, &user)
  373. if err != nil {
  374. t.Errorf("Error get user: %v", err)
  375. }
  376. req, _ = http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  377. rr = executeRequest(req)
  378. checkResponseCode(t, http.StatusInternalServerError, rr.Code)
  379. user.MaxSessions = 10
  380. user.UploadBandwidth = 128
  381. userAsJSON = getUserAsJSON(t, user)
  382. req, _ = http.NewRequest(http.MethodPut, userPath+"/"+strconv.FormatInt(user.ID, 10), bytes.NewBuffer(userAsJSON))
  383. rr = executeRequest(req)
  384. checkResponseCode(t, http.StatusOK, rr.Code)
  385. req, _ = http.NewRequest(http.MethodGet, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  386. rr = executeRequest(req)
  387. checkResponseCode(t, http.StatusOK, rr.Code)
  388. var updatedUser dataprovider.User
  389. err = render.DecodeJSON(rr.Body, &updatedUser)
  390. if err != nil {
  391. t.Errorf("Error decoding updated user: %v", err)
  392. }
  393. if user.MaxSessions != updatedUser.MaxSessions || user.UploadBandwidth != updatedUser.UploadBandwidth {
  394. t.Errorf("Error modifying user actual: %v, %v", updatedUser.MaxSessions, updatedUser.UploadBandwidth)
  395. }
  396. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  397. rr = executeRequest(req)
  398. checkResponseCode(t, http.StatusOK, rr.Code)
  399. }
  400. func TestGetUserByIdInvalidParamsMock(t *testing.T) {
  401. req, _ := http.NewRequest(http.MethodGet, userPath+"/0", nil)
  402. rr := executeRequest(req)
  403. checkResponseCode(t, http.StatusNotFound, rr.Code)
  404. req, _ = http.NewRequest(http.MethodGet, userPath+"/a", nil)
  405. rr = executeRequest(req)
  406. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  407. }
  408. func TestAddUserNoUsernameMock(t *testing.T) {
  409. user := getTestUser()
  410. user.Username = ""
  411. userAsJSON := getUserAsJSON(t, user)
  412. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  413. rr := executeRequest(req)
  414. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  415. }
  416. func TestAddUserInvalidHomeDirMock(t *testing.T) {
  417. user := getTestUser()
  418. user.HomeDir = "relative_path"
  419. userAsJSON := getUserAsJSON(t, user)
  420. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  421. rr := executeRequest(req)
  422. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  423. }
  424. func TestAddUserInvalidPermsMock(t *testing.T) {
  425. user := getTestUser()
  426. user.Permissions = []string{}
  427. userAsJSON := getUserAsJSON(t, user)
  428. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  429. rr := executeRequest(req)
  430. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  431. }
  432. func TestAddUserInvalidJsonMock(t *testing.T) {
  433. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer([]byte("invalid json")))
  434. rr := executeRequest(req)
  435. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  436. }
  437. func TestUpdateUserInvalidJsonMock(t *testing.T) {
  438. user := getTestUser()
  439. userAsJSON := getUserAsJSON(t, user)
  440. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  441. rr := executeRequest(req)
  442. checkResponseCode(t, http.StatusOK, rr.Code)
  443. err := render.DecodeJSON(rr.Body, &user)
  444. if err != nil {
  445. t.Errorf("Error get user: %v", err)
  446. }
  447. req, _ = http.NewRequest(http.MethodPut, userPath+"/"+strconv.FormatInt(user.ID, 10), bytes.NewBuffer([]byte("Invalid json")))
  448. rr = executeRequest(req)
  449. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  450. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  451. rr = executeRequest(req)
  452. checkResponseCode(t, http.StatusOK, rr.Code)
  453. }
  454. func TestUpdateUserInvalidParamsMock(t *testing.T) {
  455. user := getTestUser()
  456. userAsJSON := getUserAsJSON(t, user)
  457. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  458. rr := executeRequest(req)
  459. checkResponseCode(t, http.StatusOK, rr.Code)
  460. err := render.DecodeJSON(rr.Body, &user)
  461. if err != nil {
  462. t.Errorf("Error get user: %v", err)
  463. }
  464. user.HomeDir = ""
  465. userAsJSON = getUserAsJSON(t, user)
  466. req, _ = http.NewRequest(http.MethodPut, userPath+"/"+strconv.FormatInt(user.ID, 10), bytes.NewBuffer(userAsJSON))
  467. rr = executeRequest(req)
  468. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  469. userID := user.ID
  470. user.ID = 0
  471. userAsJSON = getUserAsJSON(t, user)
  472. req, _ = http.NewRequest(http.MethodPut, userPath+"/"+strconv.FormatInt(userID, 10), bytes.NewBuffer(userAsJSON))
  473. rr = executeRequest(req)
  474. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  475. user.ID = userID
  476. req, _ = http.NewRequest(http.MethodPut, userPath+"/0", bytes.NewBuffer(userAsJSON))
  477. rr = executeRequest(req)
  478. checkResponseCode(t, http.StatusNotFound, rr.Code)
  479. req, _ = http.NewRequest(http.MethodPut, userPath+"/a", bytes.NewBuffer(userAsJSON))
  480. rr = executeRequest(req)
  481. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  482. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  483. rr = executeRequest(req)
  484. checkResponseCode(t, http.StatusOK, rr.Code)
  485. }
  486. func TestGetUsersMock(t *testing.T) {
  487. user := getTestUser()
  488. userAsJSON := getUserAsJSON(t, user)
  489. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  490. rr := executeRequest(req)
  491. checkResponseCode(t, http.StatusOK, rr.Code)
  492. err := render.DecodeJSON(rr.Body, &user)
  493. if err != nil {
  494. t.Errorf("Error get user: %v", err)
  495. }
  496. req, _ = http.NewRequest(http.MethodGet, userPath+"?limit=510&offset=0&order=ASC&username="+defaultUsername, nil)
  497. rr = executeRequest(req)
  498. checkResponseCode(t, http.StatusOK, rr.Code)
  499. var users []dataprovider.User
  500. err = render.DecodeJSON(rr.Body, &users)
  501. if err != nil {
  502. t.Errorf("Error decoding users: %v", err)
  503. }
  504. if len(users) != 1 {
  505. t.Errorf("1 user is expected")
  506. }
  507. req, _ = http.NewRequest(http.MethodGet, userPath+"?limit=a&offset=0&order=ASC", nil)
  508. rr = executeRequest(req)
  509. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  510. req, _ = http.NewRequest(http.MethodGet, userPath+"?limit=1&offset=a&order=ASC", nil)
  511. rr = executeRequest(req)
  512. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  513. req, _ = http.NewRequest(http.MethodGet, userPath+"?limit=1&offset=0&order=ASCa", nil)
  514. rr = executeRequest(req)
  515. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  516. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  517. rr = executeRequest(req)
  518. checkResponseCode(t, http.StatusOK, rr.Code)
  519. }
  520. func TestDeleteUserInvalidParamsMock(t *testing.T) {
  521. req, _ := http.NewRequest(http.MethodDelete, userPath+"/0", nil)
  522. rr := executeRequest(req)
  523. checkResponseCode(t, http.StatusNotFound, rr.Code)
  524. req, _ = http.NewRequest(http.MethodDelete, userPath+"/a", nil)
  525. rr = executeRequest(req)
  526. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  527. }
  528. func TestGetQuotaScansMock(t *testing.T) {
  529. req, err := http.NewRequest("GET", quotaScanPath, nil)
  530. if err != nil {
  531. t.Errorf("error get quota scan: %v", err)
  532. }
  533. rr := executeRequest(req)
  534. checkResponseCode(t, http.StatusOK, rr.Code)
  535. }
  536. func TestStartQuotaScanMock(t *testing.T) {
  537. user := getTestUser()
  538. userAsJSON := getUserAsJSON(t, user)
  539. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  540. rr := executeRequest(req)
  541. checkResponseCode(t, http.StatusOK, rr.Code)
  542. err := render.DecodeJSON(rr.Body, &user)
  543. if err != nil {
  544. t.Errorf("Error get user: %v", err)
  545. }
  546. _, err = os.Stat(user.HomeDir)
  547. if err == nil {
  548. os.Remove(user.HomeDir)
  549. }
  550. userAsJSON = getUserAsJSON(t, user)
  551. req, _ = http.NewRequest(http.MethodPost, quotaScanPath, bytes.NewBuffer(userAsJSON))
  552. rr = executeRequest(req)
  553. checkResponseCode(t, http.StatusCreated, rr.Code)
  554. req, _ = http.NewRequest(http.MethodGet, quotaScanPath, nil)
  555. rr = executeRequest(req)
  556. checkResponseCode(t, http.StatusOK, rr.Code)
  557. var scans []sftpd.ActiveQuotaScan
  558. err = render.DecodeJSON(rr.Body, &scans)
  559. if err != nil {
  560. t.Errorf("Error get active scans: %v", err)
  561. }
  562. for len(scans) > 0 {
  563. req, _ = http.NewRequest(http.MethodGet, quotaScanPath, nil)
  564. rr = executeRequest(req)
  565. checkResponseCode(t, http.StatusOK, rr.Code)
  566. err = render.DecodeJSON(rr.Body, &scans)
  567. if err != nil {
  568. t.Errorf("Error get active scans: %v", err)
  569. break
  570. }
  571. }
  572. _, err = os.Stat(user.HomeDir)
  573. if err != nil && os.IsNotExist(err) {
  574. os.MkdirAll(user.HomeDir, 0777)
  575. }
  576. req, _ = http.NewRequest(http.MethodPost, quotaScanPath, bytes.NewBuffer(userAsJSON))
  577. rr = executeRequest(req)
  578. checkResponseCode(t, http.StatusCreated, rr.Code)
  579. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  580. rr = executeRequest(req)
  581. checkResponseCode(t, http.StatusOK, rr.Code)
  582. }
  583. func TestStartQuotaScanBadUserMock(t *testing.T) {
  584. user := getTestUser()
  585. userAsJSON := getUserAsJSON(t, user)
  586. req, _ := http.NewRequest(http.MethodPost, quotaScanPath, bytes.NewBuffer(userAsJSON))
  587. rr := executeRequest(req)
  588. checkResponseCode(t, http.StatusNotFound, rr.Code)
  589. }
  590. func TestStartQuotaScanNonExistentUserMock(t *testing.T) {
  591. req, _ := http.NewRequest(http.MethodPost, quotaScanPath, bytes.NewBuffer([]byte("invalid json")))
  592. rr := executeRequest(req)
  593. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  594. }
  595. func TestGetSFTPConnectionsMock(t *testing.T) {
  596. req, _ := http.NewRequest(http.MethodGet, activeConnectionsPath, nil)
  597. rr := executeRequest(req)
  598. checkResponseCode(t, http.StatusOK, rr.Code)
  599. }
  600. func TestDeleteActiveConnectionMock(t *testing.T) {
  601. req, _ := http.NewRequest(http.MethodDelete, activeConnectionsPath+"/connectionID", nil)
  602. rr := executeRequest(req)
  603. checkResponseCode(t, http.StatusNotFound, rr.Code)
  604. }
  605. func TestNotFoundMock(t *testing.T) {
  606. req, _ := http.NewRequest(http.MethodGet, "/non/existing/path", nil)
  607. rr := executeRequest(req)
  608. checkResponseCode(t, http.StatusNotFound, rr.Code)
  609. }
  610. func TestMethodNotAllowedMock(t *testing.T) {
  611. req, _ := http.NewRequest(http.MethodPost, activeConnectionsPath, nil)
  612. rr := executeRequest(req)
  613. checkResponseCode(t, http.StatusMethodNotAllowed, rr.Code)
  614. }
  615. func waitTCPListening(address string) {
  616. for {
  617. conn, err := net.Dial("tcp", address)
  618. if err != nil {
  619. logger.WarnToConsole("tcp server %v not listening: %v\n", address, err)
  620. time.Sleep(100 * time.Millisecond)
  621. continue
  622. }
  623. logger.InfoToConsole("tcp server %v now listening\n", address)
  624. defer conn.Close()
  625. break
  626. }
  627. }
  628. func getTestUser() dataprovider.User {
  629. return dataprovider.User{
  630. Username: defaultUsername,
  631. Password: defaultPassword,
  632. HomeDir: filepath.Join(homeBasePath, defaultUsername),
  633. Permissions: defaultPerms,
  634. }
  635. }
  636. func getUserAsJSON(t *testing.T, user dataprovider.User) []byte {
  637. json, err := json.Marshal(user)
  638. if err != nil {
  639. t.Errorf("error get user as json: %v", err)
  640. return []byte("{}")
  641. }
  642. return json
  643. }
  644. func executeRequest(req *http.Request) *httptest.ResponseRecorder {
  645. rr := httptest.NewRecorder()
  646. testServer.Config.Handler.ServeHTTP(rr, req)
  647. return rr
  648. }
  649. func checkResponseCode(t *testing.T, expected, actual int) {
  650. if expected != actual {
  651. t.Errorf("Expected response code %d. Got %d", expected, actual)
  652. }
  653. }