httpd_test.go 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  1. package httpd_test
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "encoding/json"
  6. "fmt"
  7. "io/ioutil"
  8. "net"
  9. "net/http"
  10. "net/http/httptest"
  11. "net/url"
  12. "os"
  13. "path/filepath"
  14. "runtime"
  15. "strconv"
  16. "strings"
  17. "testing"
  18. "time"
  19. "github.com/go-chi/render"
  20. _ "github.com/go-sql-driver/mysql"
  21. _ "github.com/lib/pq"
  22. _ "github.com/mattn/go-sqlite3"
  23. "github.com/rs/zerolog"
  24. "github.com/drakkan/sftpgo/config"
  25. "github.com/drakkan/sftpgo/dataprovider"
  26. "github.com/drakkan/sftpgo/httpd"
  27. "github.com/drakkan/sftpgo/logger"
  28. "github.com/drakkan/sftpgo/sftpd"
  29. "github.com/drakkan/sftpgo/utils"
  30. )
  31. const (
  32. defaultUsername = "test_user"
  33. defaultPassword = "test_password"
  34. testPubKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC03jj0D+djk7pxIf/0OhrxrchJTRZklofJ1NoIu4752Sq02mdXmarMVsqJ1cAjV5LBVy3D1F5U6XW4rppkXeVtd04Pxb09ehtH0pRRPaoHHlALiJt8CoMpbKYMA8b3KXPPriGxgGomvtU2T2RMURSwOZbMtpsugfjYSWenyYX+VORYhylWnSXL961LTyC21ehd6d6QnW9G7E5hYMITMY9TuQZz3bROYzXiTsgN0+g6Hn7exFQp50p45StUMfV/SftCMdCxlxuyGny2CrN/vfjO7xxOo2uv7q1qm10Q46KPWJQv+pgZ/OfL+EDjy07n5QVSKHlbx+2nT4Q0EgOSQaCTYwn3YjtABfIxWwgAFdyj6YlPulCL22qU4MYhDcA6PSBwDdf8hvxBfvsiHdM+JcSHvv8/VeJhk6CmnZxGY0fxBupov27z3yEO8nAg8k+6PaUiW1MSUfuGMF/ktB8LOstXsEPXSszuyXiOv4DaryOXUiSn7bmRqKcEFlJusO6aZP0= nicola@p1"
  35. logSender = "APITesting"
  36. userPath = "/api/v1/user"
  37. activeConnectionsPath = "/api/v1/connection"
  38. quotaScanPath = "/api/v1/quota_scan"
  39. versionPath = "/api/v1/version"
  40. providerStatusPath = "/api/v1/providerstatus"
  41. dumpDataPath = "/api/v1/dumpdata"
  42. loadDataPath = "/api/v1/loaddata"
  43. metricsPath = "/metrics"
  44. webBasePath = "/web"
  45. webUsersPath = "/web/users"
  46. webUserPath = "/web/user"
  47. webConnectionsPath = "/web/connections"
  48. configDir = ".."
  49. )
  50. var (
  51. defaultPerms = []string{dataprovider.PermAny}
  52. homeBasePath string
  53. backupsPath string
  54. testServer *httptest.Server
  55. providerDriverName string
  56. )
  57. func TestMain(m *testing.M) {
  58. homeBasePath = os.TempDir()
  59. logfilePath := filepath.Join(configDir, "sftpgo_api_test.log")
  60. logger.InitLogger(logfilePath, 5, 1, 28, false, zerolog.DebugLevel)
  61. config.LoadConfig(configDir, "")
  62. providerConf := config.GetProviderConf()
  63. providerDriverName = providerConf.Driver
  64. err := dataprovider.Initialize(providerConf, configDir)
  65. if err != nil {
  66. logger.Warn(logSender, "", "error initializing data provider: %v", err)
  67. os.Exit(1)
  68. }
  69. dataProvider := dataprovider.GetProvider()
  70. httpdConf := config.GetHTTPDConfig()
  71. httpdConf.BindPort = 8081
  72. httpd.SetBaseURL("http://127.0.0.1:8081")
  73. httpdConf.BackupsPath = "test_backups"
  74. currentPath, _ := os.Getwd()
  75. backupsPath = filepath.Join(currentPath, "..", httpdConf.BackupsPath)
  76. os.MkdirAll(backupsPath, 0777)
  77. sftpd.SetDataProvider(dataProvider)
  78. httpd.SetDataProvider(dataProvider)
  79. go func() {
  80. go func() {
  81. if err := httpdConf.Initialize(configDir); err != nil {
  82. logger.Error(logSender, "", "could not start HTTP server: %v", err)
  83. }
  84. }()
  85. }()
  86. waitTCPListening(fmt.Sprintf("%s:%d", httpdConf.BindAddress, httpdConf.BindPort))
  87. testServer = httptest.NewServer(httpd.GetHTTPRouter())
  88. defer testServer.Close()
  89. exitCode := m.Run()
  90. os.Remove(logfilePath)
  91. os.RemoveAll(backupsPath)
  92. os.Exit(exitCode)
  93. }
  94. func TestBasicUserHandling(t *testing.T) {
  95. user, _, err := httpd.AddUser(getTestUser(), http.StatusOK)
  96. if err != nil {
  97. t.Errorf("unable to add user: %v", err)
  98. }
  99. user.MaxSessions = 10
  100. user.QuotaSize = 4096
  101. user.QuotaFiles = 2
  102. user.UploadBandwidth = 128
  103. user.DownloadBandwidth = 64
  104. user.ExpirationDate = utils.GetTimeAsMsSinceEpoch(time.Now())
  105. user, _, err = httpd.UpdateUser(user, http.StatusOK)
  106. if err != nil {
  107. t.Errorf("unable to update user: %v", err)
  108. }
  109. users, _, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK)
  110. if err != nil {
  111. t.Errorf("unable to get users: %v", err)
  112. }
  113. if len(users) != 1 {
  114. t.Errorf("number of users mismatch, expected: 1, actual: %v", len(users))
  115. }
  116. _, err = httpd.RemoveUser(user, http.StatusOK)
  117. if err != nil {
  118. t.Errorf("unable to remove: %v", err)
  119. }
  120. }
  121. func TestUserStatus(t *testing.T) {
  122. u := getTestUser()
  123. u.Status = 3
  124. _, _, err := httpd.AddUser(u, http.StatusBadRequest)
  125. if err != nil {
  126. t.Errorf("unexpected error adding user with bad status: %v", err)
  127. }
  128. u.Status = 0
  129. user, _, err := httpd.AddUser(u, http.StatusOK)
  130. if err != nil {
  131. t.Errorf("unable to add user: %v", err)
  132. }
  133. user.Status = 2
  134. _, _, err = httpd.UpdateUser(user, http.StatusBadRequest)
  135. if err != nil {
  136. t.Errorf("unexpected error updating user with bad status: %v", err)
  137. }
  138. user.Status = 1
  139. user, _, err = httpd.UpdateUser(user, http.StatusOK)
  140. if err != nil {
  141. t.Errorf("unable to update user: %v", err)
  142. }
  143. _, err = httpd.RemoveUser(user, http.StatusOK)
  144. if err != nil {
  145. t.Errorf("unable to remove: %v", err)
  146. }
  147. }
  148. func TestAddUserNoCredentials(t *testing.T) {
  149. u := getTestUser()
  150. u.Password = ""
  151. u.PublicKeys = []string{}
  152. _, _, err := httpd.AddUser(u, http.StatusBadRequest)
  153. if err != nil {
  154. t.Errorf("unexpected error adding user with no credentials: %v", err)
  155. }
  156. }
  157. func TestAddUserNoUsername(t *testing.T) {
  158. u := getTestUser()
  159. u.Username = ""
  160. _, _, err := httpd.AddUser(u, http.StatusBadRequest)
  161. if err != nil {
  162. t.Errorf("unexpected error adding user with no home dir: %v", err)
  163. }
  164. }
  165. func TestAddUserNoHomeDir(t *testing.T) {
  166. u := getTestUser()
  167. u.HomeDir = ""
  168. _, _, err := httpd.AddUser(u, http.StatusBadRequest)
  169. if err != nil {
  170. t.Errorf("unexpected error adding user with no home dir: %v", err)
  171. }
  172. }
  173. func TestAddUserInvalidHomeDir(t *testing.T) {
  174. u := getTestUser()
  175. u.HomeDir = "relative_path"
  176. _, _, err := httpd.AddUser(u, http.StatusBadRequest)
  177. if err != nil {
  178. t.Errorf("unexpected error adding user with invalid home dir: %v", err)
  179. }
  180. }
  181. func TestAddUserNoPerms(t *testing.T) {
  182. u := getTestUser()
  183. u.Permissions = make(map[string][]string)
  184. _, _, err := httpd.AddUser(u, http.StatusBadRequest)
  185. if err != nil {
  186. t.Errorf("unexpected error adding user with no perms: %v", err)
  187. }
  188. u.Permissions["/"] = []string{}
  189. _, _, err = httpd.AddUser(u, http.StatusBadRequest)
  190. if err != nil {
  191. t.Errorf("unexpected error adding user with no perms: %v", err)
  192. }
  193. }
  194. func TestAddUserInvalidPerms(t *testing.T) {
  195. u := getTestUser()
  196. u.Permissions["/"] = []string{"invalidPerm"}
  197. _, _, err := httpd.AddUser(u, http.StatusBadRequest)
  198. if err != nil {
  199. t.Errorf("unexpected error adding user with invalid perms: %v", err)
  200. }
  201. // permissions for root dir are mandatory
  202. u.Permissions["/somedir"] = []string{dataprovider.PermAny}
  203. _, _, err = httpd.AddUser(u, http.StatusBadRequest)
  204. if err != nil {
  205. t.Errorf("unexpected error adding user with no root dir perms: %v", err)
  206. }
  207. }
  208. func TestAddUserInvalidFilters(t *testing.T) {
  209. u := getTestUser()
  210. u.Filters.AllowedIP = []string{"192.168.1.0/24", "192.168.2.0"}
  211. _, _, err := httpd.AddUser(u, http.StatusBadRequest)
  212. if err != nil {
  213. t.Errorf("unexpected error adding user with invalid filters: %v", err)
  214. }
  215. u.Filters.AllowedIP = []string{}
  216. u.Filters.DeniedIP = []string{"192.168.3.0/16", "invalid"}
  217. _, _, err = httpd.AddUser(u, http.StatusBadRequest)
  218. if err != nil {
  219. t.Errorf("unexpected error adding user with invalid filters: %v", err)
  220. }
  221. }
  222. func TestUserPublicKey(t *testing.T) {
  223. u := getTestUser()
  224. invalidPubKey := "invalid"
  225. validPubKey := "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC03jj0D+djk7pxIf/0OhrxrchJTRZklofJ1NoIu4752Sq02mdXmarMVsqJ1cAjV5LBVy3D1F5U6XW4rppkXeVtd04Pxb09ehtH0pRRPaoHHlALiJt8CoMpbKYMA8b3KXPPriGxgGomvtU2T2RMURSwOZbMtpsugfjYSWenyYX+VORYhylWnSXL961LTyC21ehd6d6QnW9G7E5hYMITMY9TuQZz3bROYzXiTsgN0+g6Hn7exFQp50p45StUMfV/SftCMdCxlxuyGny2CrN/vfjO7xxOo2uv7q1qm10Q46KPWJQv+pgZ/OfL+EDjy07n5QVSKHlbx+2nT4Q0EgOSQaCTYwn3YjtABfIxWwgAFdyj6YlPulCL22qU4MYhDcA6PSBwDdf8hvxBfvsiHdM+JcSHvv8/VeJhk6CmnZxGY0fxBupov27z3yEO8nAg8k+6PaUiW1MSUfuGMF/ktB8LOstXsEPXSszuyXiOv4DaryOXUiSn7bmRqKcEFlJusO6aZP0= nicola@p1"
  226. u.PublicKeys = []string{invalidPubKey}
  227. _, _, err := httpd.AddUser(u, http.StatusBadRequest)
  228. if err != nil {
  229. t.Errorf("unexpected error adding user with invalid pub key: %v", err)
  230. }
  231. u.PublicKeys = []string{validPubKey}
  232. user, _, err := httpd.AddUser(u, http.StatusOK)
  233. if err != nil {
  234. t.Errorf("unable to add user: %v", err)
  235. }
  236. user.PublicKeys = []string{validPubKey, invalidPubKey}
  237. _, _, err = httpd.UpdateUser(user, http.StatusBadRequest)
  238. if err != nil {
  239. t.Errorf("update user with invalid public key must fail: %v", err)
  240. }
  241. user.PublicKeys = []string{validPubKey, validPubKey, validPubKey}
  242. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  243. if err != nil {
  244. t.Errorf("unable to update user: %v", err)
  245. }
  246. _, err = httpd.RemoveUser(user, http.StatusOK)
  247. if err != nil {
  248. t.Errorf("unable to remove: %v", err)
  249. }
  250. }
  251. func TestUpdateUser(t *testing.T) {
  252. user, _, err := httpd.AddUser(getTestUser(), http.StatusOK)
  253. if err != nil {
  254. t.Errorf("unable to add user: %v", err)
  255. }
  256. user.HomeDir = filepath.Join(homeBasePath, "testmod")
  257. user.UID = 33
  258. user.GID = 101
  259. user.MaxSessions = 10
  260. user.QuotaSize = 4096
  261. user.QuotaFiles = 2
  262. user.Permissions["/"] = []string{dataprovider.PermCreateDirs, dataprovider.PermDelete, dataprovider.PermDownload}
  263. user.Permissions["/subdir"] = []string{dataprovider.PermListItems, dataprovider.PermUpload}
  264. user.Filters.AllowedIP = []string{"192.168.1.0/24", "192.168.2.0/24"}
  265. user.Filters.DeniedIP = []string{"192.168.3.0/24", "192.168.4.0/24"}
  266. user.UploadBandwidth = 1024
  267. user.DownloadBandwidth = 512
  268. user, _, err = httpd.UpdateUser(user, http.StatusOK)
  269. if err != nil {
  270. t.Errorf("unable to update user: %v", err)
  271. }
  272. _, err = httpd.RemoveUser(user, http.StatusOK)
  273. if err != nil {
  274. t.Errorf("unable to remove: %v", err)
  275. }
  276. }
  277. func TestUpdateUserNoCredentials(t *testing.T) {
  278. user, _, err := httpd.AddUser(getTestUser(), http.StatusOK)
  279. if err != nil {
  280. t.Errorf("unable to add user: %v", err)
  281. }
  282. user.Password = ""
  283. user.PublicKeys = []string{}
  284. // password and public key will be omitted from json serialization if empty and so they will remain unchanged
  285. // and no validation error will be raised
  286. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  287. if err != nil {
  288. t.Errorf("unexpected error updating user with no credentials: %v", err)
  289. }
  290. _, err = httpd.RemoveUser(user, http.StatusOK)
  291. if err != nil {
  292. t.Errorf("unable to remove: %v", err)
  293. }
  294. }
  295. func TestUpdateUserEmptyHomeDir(t *testing.T) {
  296. user, _, err := httpd.AddUser(getTestUser(), http.StatusOK)
  297. if err != nil {
  298. t.Errorf("unable to add user: %v", err)
  299. }
  300. user.HomeDir = ""
  301. _, _, err = httpd.UpdateUser(user, http.StatusBadRequest)
  302. if err != nil {
  303. t.Errorf("unexpected error updating user with empty home dir: %v", err)
  304. }
  305. _, err = httpd.RemoveUser(user, http.StatusOK)
  306. if err != nil {
  307. t.Errorf("unable to remove: %v", err)
  308. }
  309. }
  310. func TestUpdateUserInvalidHomeDir(t *testing.T) {
  311. user, _, err := httpd.AddUser(getTestUser(), http.StatusOK)
  312. if err != nil {
  313. t.Errorf("unable to add user: %v", err)
  314. }
  315. user.HomeDir = "relative_path"
  316. _, _, err = httpd.UpdateUser(user, http.StatusBadRequest)
  317. if err != nil {
  318. t.Errorf("unexpected error updating user with empty home dir: %v", err)
  319. }
  320. _, err = httpd.RemoveUser(user, http.StatusOK)
  321. if err != nil {
  322. t.Errorf("unable to remove: %v", err)
  323. }
  324. }
  325. func TestUpdateNonExistentUser(t *testing.T) {
  326. _, _, err := httpd.UpdateUser(getTestUser(), http.StatusNotFound)
  327. if err != nil {
  328. t.Errorf("unable to update user: %v", err)
  329. }
  330. }
  331. func TestGetNonExistentUser(t *testing.T) {
  332. _, _, err := httpd.GetUserByID(0, http.StatusNotFound)
  333. if err != nil {
  334. t.Errorf("unable to get user: %v", err)
  335. }
  336. }
  337. func TestDeleteNonExistentUser(t *testing.T) {
  338. _, err := httpd.RemoveUser(getTestUser(), http.StatusNotFound)
  339. if err != nil {
  340. t.Errorf("unable to remove user: %v", err)
  341. }
  342. }
  343. func TestAddDuplicateUser(t *testing.T) {
  344. user, _, err := httpd.AddUser(getTestUser(), http.StatusOK)
  345. if err != nil {
  346. t.Errorf("unable to add user: %v", err)
  347. }
  348. _, _, err = httpd.AddUser(getTestUser(), http.StatusInternalServerError)
  349. if err != nil {
  350. t.Errorf("unable to add second user: %v", err)
  351. }
  352. _, _, err = httpd.AddUser(getTestUser(), http.StatusOK)
  353. if err == nil {
  354. t.Errorf("adding a duplicate user must fail")
  355. }
  356. _, err = httpd.RemoveUser(user, http.StatusOK)
  357. if err != nil {
  358. t.Errorf("unable to remove user: %v", err)
  359. }
  360. }
  361. func TestGetUsers(t *testing.T) {
  362. user1, _, err := httpd.AddUser(getTestUser(), http.StatusOK)
  363. if err != nil {
  364. t.Errorf("unable to add user: %v", err)
  365. }
  366. u := getTestUser()
  367. u.Username = defaultUsername + "1"
  368. user2, _, err := httpd.AddUser(u, http.StatusOK)
  369. if err != nil {
  370. t.Errorf("unable to add second user: %v", err)
  371. }
  372. users, _, err := httpd.GetUsers(0, 0, "", http.StatusOK)
  373. if err != nil {
  374. t.Errorf("unable to get users: %v", err)
  375. }
  376. if len(users) < 2 {
  377. t.Errorf("at least 2 users are expected")
  378. }
  379. users, _, err = httpd.GetUsers(1, 0, "", http.StatusOK)
  380. if err != nil {
  381. t.Errorf("unable to get users: %v", err)
  382. }
  383. if len(users) != 1 {
  384. t.Errorf("1 user is expected")
  385. }
  386. users, _, err = httpd.GetUsers(1, 1, "", http.StatusOK)
  387. if err != nil {
  388. t.Errorf("unable to get users: %v", err)
  389. }
  390. if len(users) != 1 {
  391. t.Errorf("1 user is expected")
  392. }
  393. _, _, err = httpd.GetUsers(1, 1, "", http.StatusInternalServerError)
  394. if err == nil {
  395. t.Errorf("get users must succeed, we requested a fail for a good request")
  396. }
  397. _, err = httpd.RemoveUser(user1, http.StatusOK)
  398. if err != nil {
  399. t.Errorf("unable to remove user: %v", err)
  400. }
  401. _, err = httpd.RemoveUser(user2, http.StatusOK)
  402. if err != nil {
  403. t.Errorf("unable to remove user: %v", err)
  404. }
  405. }
  406. func TestGetQuotaScans(t *testing.T) {
  407. _, _, err := httpd.GetQuotaScans(http.StatusOK)
  408. if err != nil {
  409. t.Errorf("unable to get quota scans: %v", err)
  410. }
  411. _, _, err = httpd.GetQuotaScans(http.StatusInternalServerError)
  412. if err == nil {
  413. t.Errorf("quota scan request must succeed, we requested to check a wrong status code")
  414. }
  415. }
  416. func TestStartQuotaScan(t *testing.T) {
  417. user, _, err := httpd.AddUser(getTestUser(), http.StatusOK)
  418. if err != nil {
  419. t.Errorf("unable to add user: %v", err)
  420. }
  421. _, err = httpd.StartQuotaScan(user, http.StatusCreated)
  422. if err != nil {
  423. t.Errorf("unable to start quota scan: %v", err)
  424. }
  425. _, err = httpd.RemoveUser(user, http.StatusOK)
  426. if err != nil {
  427. t.Errorf("unable to remove user: %v", err)
  428. }
  429. }
  430. func TestGetVersion(t *testing.T) {
  431. _, _, err := httpd.GetVersion(http.StatusOK)
  432. if err != nil {
  433. t.Errorf("unable to get version: %v", err)
  434. }
  435. _, _, err = httpd.GetVersion(http.StatusInternalServerError)
  436. if err == nil {
  437. t.Errorf("get version request must succeed, we requested to check a wrong status code")
  438. }
  439. }
  440. func TestGetProviderStatus(t *testing.T) {
  441. _, _, err := httpd.GetProviderStatus(http.StatusOK)
  442. if err != nil {
  443. t.Errorf("unable to get provider status: %v", err)
  444. }
  445. _, _, err = httpd.GetProviderStatus(http.StatusBadRequest)
  446. if err == nil {
  447. t.Errorf("get provider status request must succeed, we requested to check a wrong status code")
  448. }
  449. }
  450. func TestGetConnections(t *testing.T) {
  451. _, _, err := httpd.GetConnections(http.StatusOK)
  452. if err != nil {
  453. t.Errorf("unable to get sftp connections: %v", err)
  454. }
  455. _, _, err = httpd.GetConnections(http.StatusInternalServerError)
  456. if err == nil {
  457. t.Errorf("get sftp connections request must succeed, we requested to check a wrong status code")
  458. }
  459. }
  460. func TestCloseActiveConnection(t *testing.T) {
  461. _, err := httpd.CloseConnection("non_existent_id", http.StatusNotFound)
  462. if err != nil {
  463. t.Errorf("unexpected error closing non existent sftp connection: %v", err)
  464. }
  465. }
  466. func TestUserBaseDir(t *testing.T) {
  467. dataProvider := dataprovider.GetProvider()
  468. dataprovider.Close(dataProvider)
  469. config.LoadConfig(configDir, "")
  470. providerConf := config.GetProviderConf()
  471. providerConf.UsersBaseDir = homeBasePath
  472. err := dataprovider.Initialize(providerConf, configDir)
  473. if err != nil {
  474. t.Errorf("error initializing data provider with users base dir")
  475. }
  476. httpd.SetDataProvider(dataprovider.GetProvider())
  477. u := getTestUser()
  478. u.HomeDir = ""
  479. user, _, err := httpd.AddUser(getTestUser(), http.StatusOK)
  480. if err != nil {
  481. t.Errorf("unable to add user: %v", err)
  482. }
  483. if user.HomeDir != filepath.Join(providerConf.UsersBaseDir, u.Username) {
  484. t.Errorf("invalid home dir: %v", user.HomeDir)
  485. }
  486. _, err = httpd.RemoveUser(user, http.StatusOK)
  487. if err != nil {
  488. t.Errorf("unable to remove: %v", err)
  489. }
  490. dataProvider = dataprovider.GetProvider()
  491. dataprovider.Close(dataProvider)
  492. config.LoadConfig(configDir, "")
  493. providerConf = config.GetProviderConf()
  494. err = dataprovider.Initialize(providerConf, configDir)
  495. if err != nil {
  496. t.Errorf("error initializing data provider")
  497. }
  498. httpd.SetDataProvider(dataprovider.GetProvider())
  499. sftpd.SetDataProvider(dataprovider.GetProvider())
  500. }
  501. func TestProviderErrors(t *testing.T) {
  502. if providerDriverName == dataprovider.BoltDataProviderName {
  503. t.Skip("skipping test provider errors for bolt provider")
  504. }
  505. dataProvider := dataprovider.GetProvider()
  506. dataprovider.Close(dataProvider)
  507. _, _, err := httpd.GetUserByID(0, http.StatusInternalServerError)
  508. if err != nil {
  509. t.Errorf("get user with provider closed must fail: %v", err)
  510. }
  511. _, _, err = httpd.GetUsers(1, 0, defaultUsername, http.StatusInternalServerError)
  512. if err != nil {
  513. t.Errorf("get users with provider closed must fail: %v", err)
  514. }
  515. _, _, err = httpd.UpdateUser(dataprovider.User{}, http.StatusInternalServerError)
  516. if err != nil {
  517. t.Errorf("update user with provider closed must fail: %v", err)
  518. }
  519. _, err = httpd.RemoveUser(dataprovider.User{}, http.StatusInternalServerError)
  520. if err != nil {
  521. t.Errorf("delete user with provider closed must fail: %v", err)
  522. }
  523. _, _, err = httpd.GetProviderStatus(http.StatusInternalServerError)
  524. if err != nil {
  525. t.Errorf("get provider status with provider closed must fail: %v", err)
  526. }
  527. _, _, err = httpd.Dumpdata("backup.json", http.StatusInternalServerError)
  528. if err != nil {
  529. t.Errorf("get provider status with provider closed must fail: %v", err)
  530. }
  531. user := getTestUser()
  532. user.ID = 1
  533. backupData := httpd.BackupData{}
  534. backupData.Users = append(backupData.Users, user)
  535. backupContent, _ := json.Marshal(backupData)
  536. backupFilePath := filepath.Join(backupsPath, "backup.json")
  537. ioutil.WriteFile(backupFilePath, backupContent, 0666)
  538. _, _, err = httpd.Loaddata(backupFilePath, "", http.StatusInternalServerError)
  539. if err != nil {
  540. t.Errorf("get provider status with provider closed must fail: %v", err)
  541. }
  542. os.Remove(backupFilePath)
  543. config.LoadConfig(configDir, "")
  544. providerConf := config.GetProviderConf()
  545. err = dataprovider.Initialize(providerConf, configDir)
  546. if err != nil {
  547. t.Errorf("error initializing data provider")
  548. }
  549. httpd.SetDataProvider(dataprovider.GetProvider())
  550. sftpd.SetDataProvider(dataprovider.GetProvider())
  551. }
  552. func TestDumpdata(t *testing.T) {
  553. _, _, err := httpd.Dumpdata("", http.StatusBadRequest)
  554. if err != nil {
  555. t.Errorf("unexpected error: %v", err)
  556. }
  557. _, _, err = httpd.Dumpdata(filepath.Join(backupsPath, "backup.json"), http.StatusBadRequest)
  558. if err != nil {
  559. t.Errorf("unexpected error: %v", err)
  560. }
  561. _, _, err = httpd.Dumpdata("../backup.json", http.StatusBadRequest)
  562. if err != nil {
  563. t.Errorf("unexpected error: %v", err)
  564. }
  565. _, _, err = httpd.Dumpdata("backup.json", http.StatusOK)
  566. if err != nil {
  567. t.Errorf("unexpected error: %v", err)
  568. }
  569. os.Remove(filepath.Join(backupsPath, "backup.json"))
  570. if runtime.GOOS != "windows" {
  571. os.Chmod(backupsPath, 0001)
  572. _, _, err = httpd.Dumpdata("bck.json", http.StatusInternalServerError)
  573. if err != nil {
  574. t.Errorf("unexpected error: %v", err)
  575. }
  576. os.Chmod(backupsPath, 0755)
  577. }
  578. }
  579. func TestLoaddata(t *testing.T) {
  580. user := getTestUser()
  581. user.ID = 1
  582. user.Username = "test_user_restore"
  583. backupData := httpd.BackupData{}
  584. backupData.Users = append(backupData.Users, user)
  585. backupContent, _ := json.Marshal(backupData)
  586. backupFilePath := filepath.Join(backupsPath, "backup.json")
  587. ioutil.WriteFile(backupFilePath, backupContent, 0666)
  588. _, _, err := httpd.Loaddata(backupFilePath, "a", http.StatusBadRequest)
  589. if err != nil {
  590. t.Errorf("unexpected error: %v", err)
  591. }
  592. _, _, err = httpd.Loaddata("backup.json", "1", http.StatusBadRequest)
  593. if err != nil {
  594. t.Errorf("unexpected error: %v", err)
  595. }
  596. _, _, err = httpd.Loaddata(backupFilePath+"a", "1", http.StatusBadRequest)
  597. if err != nil {
  598. t.Errorf("unexpected error: %v", err)
  599. }
  600. if runtime.GOOS != "windows" {
  601. os.Chmod(backupFilePath, 0111)
  602. _, _, err = httpd.Loaddata(backupFilePath, "1", http.StatusInternalServerError)
  603. if err != nil {
  604. t.Errorf("unexpected error: %v", err)
  605. }
  606. os.Chmod(backupFilePath, 0644)
  607. }
  608. // add user from backup
  609. _, _, err = httpd.Loaddata(backupFilePath, "1", http.StatusOK)
  610. if err != nil {
  611. t.Errorf("unexpected error: %v", err)
  612. }
  613. // update user from backup
  614. _, _, err = httpd.Loaddata(backupFilePath, "2", http.StatusOK)
  615. if err != nil {
  616. t.Errorf("unexpected error: %v", err)
  617. }
  618. users, _, err := httpd.GetUsers(1, 0, user.Username, http.StatusOK)
  619. if err != nil {
  620. t.Errorf("unable to get users: %v", err)
  621. }
  622. if len(users) != 1 {
  623. t.Error("Unable to get restored user")
  624. }
  625. user = users[0]
  626. _, err = httpd.RemoveUser(user, http.StatusOK)
  627. if err != nil {
  628. t.Errorf("unable to remove user: %v", err)
  629. }
  630. os.Remove(backupFilePath)
  631. createTestFile(backupFilePath, 10485761)
  632. _, _, err = httpd.Loaddata(backupFilePath, "1", http.StatusBadRequest)
  633. if err != nil {
  634. t.Errorf("unexpected error: %v", err)
  635. }
  636. os.Remove(backupFilePath)
  637. createTestFile(backupFilePath, 65535)
  638. _, _, err = httpd.Loaddata(backupFilePath, "1", http.StatusBadRequest)
  639. if err != nil {
  640. t.Errorf("unexpected error: %v", err)
  641. }
  642. os.Remove(backupFilePath)
  643. }
  644. // test using mock http server
  645. func TestBasicUserHandlingMock(t *testing.T) {
  646. user := getTestUser()
  647. userAsJSON := getUserAsJSON(t, user)
  648. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  649. rr := executeRequest(req)
  650. checkResponseCode(t, http.StatusOK, rr.Code)
  651. err := render.DecodeJSON(rr.Body, &user)
  652. if err != nil {
  653. t.Errorf("Error get user: %v", err)
  654. }
  655. req, _ = http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  656. rr = executeRequest(req)
  657. checkResponseCode(t, http.StatusInternalServerError, rr.Code)
  658. user.MaxSessions = 10
  659. user.UploadBandwidth = 128
  660. user.Permissions["/"] = []string{dataprovider.PermAny, dataprovider.PermDelete, dataprovider.PermDownload}
  661. userAsJSON = getUserAsJSON(t, user)
  662. req, _ = http.NewRequest(http.MethodPut, userPath+"/"+strconv.FormatInt(user.ID, 10), bytes.NewBuffer(userAsJSON))
  663. rr = executeRequest(req)
  664. checkResponseCode(t, http.StatusOK, rr.Code)
  665. req, _ = http.NewRequest(http.MethodGet, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  666. rr = executeRequest(req)
  667. checkResponseCode(t, http.StatusOK, rr.Code)
  668. var updatedUser dataprovider.User
  669. err = render.DecodeJSON(rr.Body, &updatedUser)
  670. if err != nil {
  671. t.Errorf("Error decoding updated user: %v", err)
  672. }
  673. if user.MaxSessions != updatedUser.MaxSessions || user.UploadBandwidth != updatedUser.UploadBandwidth {
  674. t.Errorf("Error modifying user actual: %v, %v", updatedUser.MaxSessions, updatedUser.UploadBandwidth)
  675. }
  676. if len(updatedUser.Permissions["/"]) != 1 {
  677. t.Errorf("permissions other than any should be removed")
  678. }
  679. if !utils.IsStringInSlice(dataprovider.PermAny, updatedUser.Permissions["/"]) {
  680. t.Errorf("permissions mismatch")
  681. }
  682. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  683. rr = executeRequest(req)
  684. checkResponseCode(t, http.StatusOK, rr.Code)
  685. }
  686. func TestGetUserByIdInvalidParamsMock(t *testing.T) {
  687. req, _ := http.NewRequest(http.MethodGet, userPath+"/0", nil)
  688. rr := executeRequest(req)
  689. checkResponseCode(t, http.StatusNotFound, rr.Code)
  690. req, _ = http.NewRequest(http.MethodGet, userPath+"/a", nil)
  691. rr = executeRequest(req)
  692. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  693. }
  694. func TestAddUserNoUsernameMock(t *testing.T) {
  695. user := getTestUser()
  696. user.Username = ""
  697. userAsJSON := getUserAsJSON(t, user)
  698. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  699. rr := executeRequest(req)
  700. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  701. }
  702. func TestAddUserInvalidHomeDirMock(t *testing.T) {
  703. user := getTestUser()
  704. user.HomeDir = "relative_path"
  705. userAsJSON := getUserAsJSON(t, user)
  706. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  707. rr := executeRequest(req)
  708. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  709. }
  710. func TestAddUserInvalidPermsMock(t *testing.T) {
  711. user := getTestUser()
  712. user.Permissions["/"] = []string{}
  713. userAsJSON := getUserAsJSON(t, user)
  714. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  715. rr := executeRequest(req)
  716. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  717. }
  718. func TestAddUserInvalidJsonMock(t *testing.T) {
  719. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer([]byte("invalid json")))
  720. rr := executeRequest(req)
  721. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  722. }
  723. func TestUpdateUserMock(t *testing.T) {
  724. user := getTestUser()
  725. userAsJSON := getUserAsJSON(t, user)
  726. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  727. rr := executeRequest(req)
  728. checkResponseCode(t, http.StatusOK, rr.Code)
  729. err := render.DecodeJSON(rr.Body, &user)
  730. if err != nil {
  731. t.Errorf("Error get user: %v", err)
  732. }
  733. // permissions should not change if empty or nil
  734. permissions := user.Permissions
  735. user.Permissions = make(map[string][]string)
  736. userAsJSON = getUserAsJSON(t, user)
  737. req, _ = http.NewRequest(http.MethodPut, userPath+"/"+strconv.FormatInt(user.ID, 10), bytes.NewBuffer(userAsJSON))
  738. rr = executeRequest(req)
  739. checkResponseCode(t, http.StatusOK, rr.Code)
  740. req, _ = http.NewRequest(http.MethodGet, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  741. rr = executeRequest(req)
  742. checkResponseCode(t, http.StatusOK, rr.Code)
  743. var updatedUser dataprovider.User
  744. err = render.DecodeJSON(rr.Body, &updatedUser)
  745. if err != nil {
  746. t.Errorf("Error decoding updated user: %v", err)
  747. }
  748. for dir, perms := range permissions {
  749. if actualPerms, ok := updatedUser.Permissions[dir]; ok {
  750. for _, v := range actualPerms {
  751. if !utils.IsStringInSlice(v, perms) {
  752. t.Error("Permissions contents mismatch")
  753. }
  754. }
  755. } else {
  756. t.Error("Permissions directories mismatch")
  757. }
  758. }
  759. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  760. rr = executeRequest(req)
  761. checkResponseCode(t, http.StatusOK, rr.Code)
  762. }
  763. func TestUserPermissionsMock(t *testing.T) {
  764. user := getTestUser()
  765. user.Permissions = make(map[string][]string)
  766. user.Permissions["/somedir"] = []string{dataprovider.PermAny}
  767. userAsJSON := getUserAsJSON(t, user)
  768. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  769. rr := executeRequest(req)
  770. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  771. user.Permissions = make(map[string][]string)
  772. user.Permissions["/"] = []string{dataprovider.PermAny}
  773. user.Permissions[".."] = []string{dataprovider.PermAny}
  774. userAsJSON = getUserAsJSON(t, user)
  775. req, _ = http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  776. rr = executeRequest(req)
  777. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  778. user.Permissions = make(map[string][]string)
  779. user.Permissions["/"] = []string{dataprovider.PermAny}
  780. userAsJSON = getUserAsJSON(t, user)
  781. req, _ = http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  782. rr = executeRequest(req)
  783. checkResponseCode(t, http.StatusOK, rr.Code)
  784. err := render.DecodeJSON(rr.Body, &user)
  785. if err != nil {
  786. t.Errorf("Error get user: %v", err)
  787. }
  788. user.Permissions["/somedir"] = []string{}
  789. userAsJSON = getUserAsJSON(t, user)
  790. req, _ = http.NewRequest(http.MethodPut, userPath+"/"+strconv.FormatInt(user.ID, 10), bytes.NewBuffer(userAsJSON))
  791. rr = executeRequest(req)
  792. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  793. delete(user.Permissions, "/somedir")
  794. user.Permissions["not_abs_path"] = []string{dataprovider.PermAny}
  795. userAsJSON = getUserAsJSON(t, user)
  796. req, _ = http.NewRequest(http.MethodPut, userPath+"/"+strconv.FormatInt(user.ID, 10), bytes.NewBuffer(userAsJSON))
  797. rr = executeRequest(req)
  798. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  799. delete(user.Permissions, "not_abs_path")
  800. user.Permissions["/somedir/../otherdir/"] = []string{dataprovider.PermListItems}
  801. userAsJSON = getUserAsJSON(t, user)
  802. req, _ = http.NewRequest(http.MethodPut, userPath+"/"+strconv.FormatInt(user.ID, 10), bytes.NewBuffer(userAsJSON))
  803. rr = executeRequest(req)
  804. checkResponseCode(t, http.StatusOK, rr.Code)
  805. req, _ = http.NewRequest(http.MethodGet, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  806. rr = executeRequest(req)
  807. checkResponseCode(t, http.StatusOK, rr.Code)
  808. var updatedUser dataprovider.User
  809. err = render.DecodeJSON(rr.Body, &updatedUser)
  810. if err != nil {
  811. t.Errorf("Error decoding updated user: %v", err)
  812. }
  813. if val, ok := updatedUser.Permissions["/otherdir"]; ok {
  814. if !utils.IsStringInSlice(dataprovider.PermListItems, val) {
  815. t.Error("expected permission list not found")
  816. }
  817. if len(val) != 1 {
  818. t.Errorf("Unexpected number of permissions, expected 1, actual: %v", len(val))
  819. }
  820. } else {
  821. t.Errorf("expected dir not found in permissions")
  822. }
  823. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  824. rr = executeRequest(req)
  825. checkResponseCode(t, http.StatusOK, rr.Code)
  826. }
  827. func TestUpdateUserInvalidJsonMock(t *testing.T) {
  828. user := getTestUser()
  829. userAsJSON := getUserAsJSON(t, user)
  830. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  831. rr := executeRequest(req)
  832. checkResponseCode(t, http.StatusOK, rr.Code)
  833. err := render.DecodeJSON(rr.Body, &user)
  834. if err != nil {
  835. t.Errorf("Error get user: %v", err)
  836. }
  837. req, _ = http.NewRequest(http.MethodPut, userPath+"/"+strconv.FormatInt(user.ID, 10), bytes.NewBuffer([]byte("Invalid json")))
  838. rr = executeRequest(req)
  839. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  840. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  841. rr = executeRequest(req)
  842. checkResponseCode(t, http.StatusOK, rr.Code)
  843. }
  844. func TestUpdateUserInvalidParamsMock(t *testing.T) {
  845. user := getTestUser()
  846. userAsJSON := getUserAsJSON(t, user)
  847. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  848. rr := executeRequest(req)
  849. checkResponseCode(t, http.StatusOK, rr.Code)
  850. err := render.DecodeJSON(rr.Body, &user)
  851. if err != nil {
  852. t.Errorf("Error get user: %v", err)
  853. }
  854. user.HomeDir = ""
  855. userAsJSON = getUserAsJSON(t, user)
  856. req, _ = http.NewRequest(http.MethodPut, userPath+"/"+strconv.FormatInt(user.ID, 10), bytes.NewBuffer(userAsJSON))
  857. rr = executeRequest(req)
  858. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  859. userID := user.ID
  860. user.ID = 0
  861. userAsJSON = getUserAsJSON(t, user)
  862. req, _ = http.NewRequest(http.MethodPut, userPath+"/"+strconv.FormatInt(userID, 10), bytes.NewBuffer(userAsJSON))
  863. rr = executeRequest(req)
  864. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  865. user.ID = userID
  866. req, _ = http.NewRequest(http.MethodPut, userPath+"/0", bytes.NewBuffer(userAsJSON))
  867. rr = executeRequest(req)
  868. checkResponseCode(t, http.StatusNotFound, rr.Code)
  869. req, _ = http.NewRequest(http.MethodPut, userPath+"/a", bytes.NewBuffer(userAsJSON))
  870. rr = executeRequest(req)
  871. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  872. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  873. rr = executeRequest(req)
  874. checkResponseCode(t, http.StatusOK, rr.Code)
  875. }
  876. func TestGetUsersMock(t *testing.T) {
  877. user := getTestUser()
  878. userAsJSON := getUserAsJSON(t, user)
  879. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  880. rr := executeRequest(req)
  881. checkResponseCode(t, http.StatusOK, rr.Code)
  882. err := render.DecodeJSON(rr.Body, &user)
  883. if err != nil {
  884. t.Errorf("Error get user: %v", err)
  885. }
  886. req, _ = http.NewRequest(http.MethodGet, userPath+"?limit=510&offset=0&order=ASC&username="+defaultUsername, nil)
  887. rr = executeRequest(req)
  888. checkResponseCode(t, http.StatusOK, rr.Code)
  889. var users []dataprovider.User
  890. err = render.DecodeJSON(rr.Body, &users)
  891. if err != nil {
  892. t.Errorf("Error decoding users: %v", err)
  893. }
  894. if len(users) != 1 {
  895. t.Errorf("1 user is expected")
  896. }
  897. req, _ = http.NewRequest(http.MethodGet, userPath+"?limit=a&offset=0&order=ASC", nil)
  898. rr = executeRequest(req)
  899. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  900. req, _ = http.NewRequest(http.MethodGet, userPath+"?limit=1&offset=a&order=ASC", nil)
  901. rr = executeRequest(req)
  902. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  903. req, _ = http.NewRequest(http.MethodGet, userPath+"?limit=1&offset=0&order=ASCa", nil)
  904. rr = executeRequest(req)
  905. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  906. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  907. rr = executeRequest(req)
  908. checkResponseCode(t, http.StatusOK, rr.Code)
  909. }
  910. func TestDeleteUserInvalidParamsMock(t *testing.T) {
  911. req, _ := http.NewRequest(http.MethodDelete, userPath+"/0", nil)
  912. rr := executeRequest(req)
  913. checkResponseCode(t, http.StatusNotFound, rr.Code)
  914. req, _ = http.NewRequest(http.MethodDelete, userPath+"/a", nil)
  915. rr = executeRequest(req)
  916. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  917. }
  918. func TestGetQuotaScansMock(t *testing.T) {
  919. req, err := http.NewRequest("GET", quotaScanPath, nil)
  920. if err != nil {
  921. t.Errorf("error get quota scan: %v", err)
  922. }
  923. rr := executeRequest(req)
  924. checkResponseCode(t, http.StatusOK, rr.Code)
  925. }
  926. func TestStartQuotaScanMock(t *testing.T) {
  927. user := getTestUser()
  928. userAsJSON := getUserAsJSON(t, user)
  929. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  930. rr := executeRequest(req)
  931. checkResponseCode(t, http.StatusOK, rr.Code)
  932. err := render.DecodeJSON(rr.Body, &user)
  933. if err != nil {
  934. t.Errorf("Error get user: %v", err)
  935. }
  936. _, err = os.Stat(user.HomeDir)
  937. if err == nil {
  938. os.Remove(user.HomeDir)
  939. }
  940. // simulate a duplicate quota scan
  941. userAsJSON = getUserAsJSON(t, user)
  942. sftpd.AddQuotaScan(user.Username)
  943. req, _ = http.NewRequest(http.MethodPost, quotaScanPath, bytes.NewBuffer(userAsJSON))
  944. rr = executeRequest(req)
  945. checkResponseCode(t, http.StatusConflict, rr.Code)
  946. sftpd.RemoveQuotaScan(user.Username)
  947. userAsJSON = getUserAsJSON(t, user)
  948. req, _ = http.NewRequest(http.MethodPost, quotaScanPath, bytes.NewBuffer(userAsJSON))
  949. rr = executeRequest(req)
  950. checkResponseCode(t, http.StatusCreated, rr.Code)
  951. req, _ = http.NewRequest(http.MethodGet, quotaScanPath, nil)
  952. rr = executeRequest(req)
  953. checkResponseCode(t, http.StatusOK, rr.Code)
  954. var scans []sftpd.ActiveQuotaScan
  955. err = render.DecodeJSON(rr.Body, &scans)
  956. if err != nil {
  957. t.Errorf("Error get active scans: %v", err)
  958. }
  959. for len(scans) > 0 {
  960. req, _ = http.NewRequest(http.MethodGet, quotaScanPath, nil)
  961. rr = executeRequest(req)
  962. checkResponseCode(t, http.StatusOK, rr.Code)
  963. err = render.DecodeJSON(rr.Body, &scans)
  964. if err != nil {
  965. t.Errorf("Error get active scans: %v", err)
  966. break
  967. }
  968. time.Sleep(100 * time.Millisecond)
  969. }
  970. _, err = os.Stat(user.HomeDir)
  971. if err != nil && os.IsNotExist(err) {
  972. os.MkdirAll(user.HomeDir, 0777)
  973. }
  974. req, _ = http.NewRequest(http.MethodPost, quotaScanPath, bytes.NewBuffer(userAsJSON))
  975. rr = executeRequest(req)
  976. checkResponseCode(t, http.StatusCreated, rr.Code)
  977. req, _ = http.NewRequest(http.MethodGet, quotaScanPath, nil)
  978. rr = executeRequest(req)
  979. checkResponseCode(t, http.StatusOK, rr.Code)
  980. err = render.DecodeJSON(rr.Body, &scans)
  981. if err != nil {
  982. t.Errorf("Error get active scans: %v", err)
  983. }
  984. for len(scans) > 0 {
  985. req, _ = http.NewRequest(http.MethodGet, quotaScanPath, nil)
  986. rr = executeRequest(req)
  987. checkResponseCode(t, http.StatusOK, rr.Code)
  988. err = render.DecodeJSON(rr.Body, &scans)
  989. if err != nil {
  990. t.Errorf("Error get active scans: %v", err)
  991. break
  992. }
  993. time.Sleep(100 * time.Millisecond)
  994. }
  995. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  996. rr = executeRequest(req)
  997. checkResponseCode(t, http.StatusOK, rr.Code)
  998. os.RemoveAll(user.GetHomeDir())
  999. }
  1000. func TestStartQuotaScanBadUserMock(t *testing.T) {
  1001. user := getTestUser()
  1002. userAsJSON := getUserAsJSON(t, user)
  1003. req, _ := http.NewRequest(http.MethodPost, quotaScanPath, bytes.NewBuffer(userAsJSON))
  1004. rr := executeRequest(req)
  1005. checkResponseCode(t, http.StatusNotFound, rr.Code)
  1006. }
  1007. func TestStartQuotaScanNonExistentUserMock(t *testing.T) {
  1008. req, _ := http.NewRequest(http.MethodPost, quotaScanPath, bytes.NewBuffer([]byte("invalid json")))
  1009. rr := executeRequest(req)
  1010. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  1011. }
  1012. func TestGetVersionMock(t *testing.T) {
  1013. req, _ := http.NewRequest(http.MethodGet, versionPath, nil)
  1014. rr := executeRequest(req)
  1015. checkResponseCode(t, http.StatusOK, rr.Code)
  1016. }
  1017. func TestGetConnectionsMock(t *testing.T) {
  1018. req, _ := http.NewRequest(http.MethodGet, activeConnectionsPath, nil)
  1019. rr := executeRequest(req)
  1020. checkResponseCode(t, http.StatusOK, rr.Code)
  1021. }
  1022. func TestDeleteActiveConnectionMock(t *testing.T) {
  1023. req, _ := http.NewRequest(http.MethodDelete, activeConnectionsPath+"/connectionID", nil)
  1024. rr := executeRequest(req)
  1025. checkResponseCode(t, http.StatusNotFound, rr.Code)
  1026. }
  1027. func TestNotFoundMock(t *testing.T) {
  1028. req, _ := http.NewRequest(http.MethodGet, "/non/existing/path", nil)
  1029. rr := executeRequest(req)
  1030. checkResponseCode(t, http.StatusNotFound, rr.Code)
  1031. }
  1032. func TestMethodNotAllowedMock(t *testing.T) {
  1033. req, _ := http.NewRequest(http.MethodPost, activeConnectionsPath, nil)
  1034. rr := executeRequest(req)
  1035. checkResponseCode(t, http.StatusMethodNotAllowed, rr.Code)
  1036. }
  1037. func TestMetricsMock(t *testing.T) {
  1038. req, _ := http.NewRequest(http.MethodGet, metricsPath, nil)
  1039. rr := executeRequest(req)
  1040. checkResponseCode(t, http.StatusOK, rr.Code)
  1041. }
  1042. func TestGetWebRootMock(t *testing.T) {
  1043. req, _ := http.NewRequest(http.MethodGet, "/", nil)
  1044. rr := executeRequest(req)
  1045. checkResponseCode(t, http.StatusMovedPermanently, rr.Code)
  1046. req, _ = http.NewRequest(http.MethodGet, webBasePath, nil)
  1047. rr = executeRequest(req)
  1048. checkResponseCode(t, http.StatusMovedPermanently, rr.Code)
  1049. }
  1050. func TestBasicWebUsersMock(t *testing.T) {
  1051. user := getTestUser()
  1052. userAsJSON := getUserAsJSON(t, user)
  1053. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  1054. rr := executeRequest(req)
  1055. checkResponseCode(t, http.StatusOK, rr.Code)
  1056. err := render.DecodeJSON(rr.Body, &user)
  1057. if err != nil {
  1058. t.Errorf("Error get user: %v", err)
  1059. }
  1060. user1 := getTestUser()
  1061. user1.Username += "1"
  1062. user1AsJSON := getUserAsJSON(t, user1)
  1063. req, _ = http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(user1AsJSON))
  1064. rr = executeRequest(req)
  1065. checkResponseCode(t, http.StatusOK, rr.Code)
  1066. err = render.DecodeJSON(rr.Body, &user1)
  1067. if err != nil {
  1068. t.Errorf("Error get user1: %v", err)
  1069. }
  1070. req, _ = http.NewRequest(http.MethodGet, webUsersPath, nil)
  1071. rr = executeRequest(req)
  1072. checkResponseCode(t, http.StatusOK, rr.Code)
  1073. req, _ = http.NewRequest(http.MethodGet, webUsersPath+"?qlimit=a", nil)
  1074. rr = executeRequest(req)
  1075. checkResponseCode(t, http.StatusOK, rr.Code)
  1076. req, _ = http.NewRequest(http.MethodGet, webUsersPath+"?qlimit=1", nil)
  1077. rr = executeRequest(req)
  1078. checkResponseCode(t, http.StatusOK, rr.Code)
  1079. req, _ = http.NewRequest(http.MethodGet, webUserPath, nil)
  1080. rr = executeRequest(req)
  1081. checkResponseCode(t, http.StatusOK, rr.Code)
  1082. req, _ = http.NewRequest(http.MethodGet, webUserPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  1083. rr = executeRequest(req)
  1084. checkResponseCode(t, http.StatusOK, rr.Code)
  1085. req, _ = http.NewRequest(http.MethodGet, webUserPath+"/0", nil)
  1086. rr = executeRequest(req)
  1087. checkResponseCode(t, http.StatusNotFound, rr.Code)
  1088. req, _ = http.NewRequest(http.MethodGet, webUserPath+"/a", nil)
  1089. rr = executeRequest(req)
  1090. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  1091. form := make(url.Values)
  1092. form.Set("username", user.Username)
  1093. req, _ = http.NewRequest(http.MethodPost, webUserPath, strings.NewReader(form.Encode()))
  1094. rr = executeRequest(req)
  1095. checkResponseCode(t, http.StatusOK, rr.Code)
  1096. req, _ = http.NewRequest(http.MethodPost, webUserPath+"/"+strconv.FormatInt(user.ID, 10), strings.NewReader(form.Encode()))
  1097. rr = executeRequest(req)
  1098. checkResponseCode(t, http.StatusOK, rr.Code)
  1099. req, _ = http.NewRequest(http.MethodPost, webUserPath+"/0", strings.NewReader(form.Encode()))
  1100. rr = executeRequest(req)
  1101. checkResponseCode(t, http.StatusNotFound, rr.Code)
  1102. req, _ = http.NewRequest(http.MethodPost, webUserPath+"/a", strings.NewReader(form.Encode()))
  1103. rr = executeRequest(req)
  1104. checkResponseCode(t, http.StatusBadRequest, rr.Code)
  1105. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  1106. rr = executeRequest(req)
  1107. checkResponseCode(t, http.StatusOK, rr.Code)
  1108. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user1.ID, 10), nil)
  1109. rr = executeRequest(req)
  1110. checkResponseCode(t, http.StatusOK, rr.Code)
  1111. }
  1112. func TestWebUserAddMock(t *testing.T) {
  1113. user := getTestUser()
  1114. user.UploadBandwidth = 32
  1115. user.DownloadBandwidth = 64
  1116. user.UID = 1000
  1117. form := make(url.Values)
  1118. form.Set("username", user.Username)
  1119. form.Set("home_dir", user.HomeDir)
  1120. form.Set("password", user.Password)
  1121. form.Set("status", strconv.Itoa(user.Status))
  1122. form.Set("expiration_date", "")
  1123. form.Set("permissions", "*")
  1124. form.Set("sub_dirs_permissions", " /subdir:list ,download ")
  1125. // test invalid url escape
  1126. req, _ := http.NewRequest(http.MethodPost, webUserPath+"?a=%2", strings.NewReader(form.Encode()))
  1127. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1128. rr := executeRequest(req)
  1129. checkResponseCode(t, http.StatusOK, rr.Code)
  1130. form.Set("public_keys", testPubKey)
  1131. form.Set("uid", strconv.FormatInt(int64(user.UID), 10))
  1132. form.Set("gid", "a")
  1133. // test invalid gid
  1134. req, _ = http.NewRequest(http.MethodPost, webUserPath, strings.NewReader(form.Encode()))
  1135. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1136. rr = executeRequest(req)
  1137. checkResponseCode(t, http.StatusOK, rr.Code)
  1138. form.Set("gid", "0")
  1139. form.Set("max_sessions", "a")
  1140. // test invalid max sessions
  1141. req, _ = http.NewRequest(http.MethodPost, webUserPath, strings.NewReader(form.Encode()))
  1142. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1143. rr = executeRequest(req)
  1144. checkResponseCode(t, http.StatusOK, rr.Code)
  1145. form.Set("max_sessions", "0")
  1146. form.Set("quota_size", "a")
  1147. // test invalid quota size
  1148. req, _ = http.NewRequest(http.MethodPost, webUserPath, strings.NewReader(form.Encode()))
  1149. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1150. rr = executeRequest(req)
  1151. checkResponseCode(t, http.StatusOK, rr.Code)
  1152. form.Set("quota_size", "0")
  1153. form.Set("quota_files", "a")
  1154. // test invalid quota files
  1155. req, _ = http.NewRequest(http.MethodPost, webUserPath, strings.NewReader(form.Encode()))
  1156. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1157. rr = executeRequest(req)
  1158. checkResponseCode(t, http.StatusOK, rr.Code)
  1159. form.Set("quota_files", "0")
  1160. form.Set("upload_bandwidth", "a")
  1161. // test invalid upload bandwidth
  1162. req, _ = http.NewRequest(http.MethodPost, webUserPath, strings.NewReader(form.Encode()))
  1163. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1164. rr = executeRequest(req)
  1165. checkResponseCode(t, http.StatusOK, rr.Code)
  1166. form.Set("upload_bandwidth", strconv.FormatInt(user.UploadBandwidth, 10))
  1167. form.Set("download_bandwidth", "a")
  1168. // test invalid download bandwidth
  1169. req, _ = http.NewRequest(http.MethodPost, webUserPath, strings.NewReader(form.Encode()))
  1170. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1171. rr = executeRequest(req)
  1172. checkResponseCode(t, http.StatusOK, rr.Code)
  1173. form.Set("download_bandwidth", strconv.FormatInt(user.DownloadBandwidth, 10))
  1174. form.Set("status", "a")
  1175. // test invalid status
  1176. req, _ = http.NewRequest(http.MethodPost, webUserPath, strings.NewReader(form.Encode()))
  1177. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1178. rr = executeRequest(req)
  1179. checkResponseCode(t, http.StatusOK, rr.Code)
  1180. form.Set("status", strconv.Itoa(user.Status))
  1181. form.Set("expiration_date", "123")
  1182. // test invalid expiration date
  1183. req, _ = http.NewRequest(http.MethodPost, webUserPath, strings.NewReader(form.Encode()))
  1184. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1185. rr = executeRequest(req)
  1186. checkResponseCode(t, http.StatusOK, rr.Code)
  1187. form.Set("expiration_date", "")
  1188. form.Set("allowed_ip", "invalid,ip")
  1189. // test invalid allowed_ip
  1190. req, _ = http.NewRequest(http.MethodPost, webUserPath, strings.NewReader(form.Encode()))
  1191. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1192. rr = executeRequest(req)
  1193. checkResponseCode(t, http.StatusOK, rr.Code)
  1194. form.Set("allowed_ip", "")
  1195. form.Set("denied_ip", "192.168.1.2") // it should be 192.168.1.2/32
  1196. // test invalid denied_ip
  1197. req, _ = http.NewRequest(http.MethodPost, webUserPath, strings.NewReader(form.Encode()))
  1198. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1199. rr = executeRequest(req)
  1200. checkResponseCode(t, http.StatusOK, rr.Code)
  1201. form.Set("denied_ip", "")
  1202. req, _ = http.NewRequest(http.MethodPost, webUserPath, strings.NewReader(form.Encode()))
  1203. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1204. rr = executeRequest(req)
  1205. checkResponseCode(t, http.StatusSeeOther, rr.Code)
  1206. // the user already exists, was created with the above request
  1207. req, _ = http.NewRequest(http.MethodPost, webUserPath, strings.NewReader(form.Encode()))
  1208. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1209. rr = executeRequest(req)
  1210. checkResponseCode(t, http.StatusOK, rr.Code)
  1211. req, _ = http.NewRequest(http.MethodGet, userPath+"?limit=1&offset=0&order=ASC&username="+user.Username, nil)
  1212. rr = executeRequest(req)
  1213. checkResponseCode(t, http.StatusOK, rr.Code)
  1214. var users []dataprovider.User
  1215. err := render.DecodeJSON(rr.Body, &users)
  1216. if err != nil {
  1217. t.Errorf("Error decoding users: %v", err)
  1218. }
  1219. if len(users) != 1 {
  1220. t.Errorf("1 user is expected")
  1221. }
  1222. newUser := users[0]
  1223. if newUser.UID != user.UID {
  1224. t.Errorf("uid does not match")
  1225. }
  1226. if newUser.UploadBandwidth != user.UploadBandwidth {
  1227. t.Errorf("upload_bandwidth does not match")
  1228. }
  1229. if newUser.DownloadBandwidth != user.DownloadBandwidth {
  1230. t.Errorf("download_bandwidth does not match")
  1231. }
  1232. if !utils.IsStringInSlice(testPubKey, newUser.PublicKeys) {
  1233. t.Errorf("public_keys does not match")
  1234. }
  1235. if val, ok := newUser.Permissions["/subdir"]; ok {
  1236. if !utils.IsStringInSlice(dataprovider.PermListItems, val) || !utils.IsStringInSlice(dataprovider.PermDownload, val) {
  1237. t.Error("permssions for /subdir does not match")
  1238. }
  1239. } else {
  1240. t.Errorf("user permissions must contains /somedir, actual: %v", newUser.Permissions)
  1241. }
  1242. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(newUser.ID, 10), nil)
  1243. rr = executeRequest(req)
  1244. checkResponseCode(t, http.StatusOK, rr.Code)
  1245. }
  1246. func TestWebUserUpdateMock(t *testing.T) {
  1247. user := getTestUser()
  1248. userAsJSON := getUserAsJSON(t, user)
  1249. req, _ := http.NewRequest(http.MethodPost, userPath, bytes.NewBuffer(userAsJSON))
  1250. rr := executeRequest(req)
  1251. checkResponseCode(t, http.StatusOK, rr.Code)
  1252. err := render.DecodeJSON(rr.Body, &user)
  1253. if err != nil {
  1254. t.Errorf("Error get user: %v", err)
  1255. }
  1256. user.MaxSessions = 1
  1257. user.QuotaFiles = 2
  1258. user.QuotaSize = 3
  1259. user.GID = 1000
  1260. form := make(url.Values)
  1261. form.Set("username", user.Username)
  1262. form.Set("home_dir", user.HomeDir)
  1263. form.Set("uid", "0")
  1264. form.Set("gid", strconv.FormatInt(int64(user.GID), 10))
  1265. form.Set("max_sessions", strconv.FormatInt(int64(user.MaxSessions), 10))
  1266. form.Set("quota_size", strconv.FormatInt(user.QuotaSize, 10))
  1267. form.Set("quota_files", strconv.FormatInt(int64(user.QuotaFiles), 10))
  1268. form.Set("upload_bandwidth", "0")
  1269. form.Set("download_bandwidth", "0")
  1270. form.Set("permissions", "*")
  1271. form.Set("sub_dirs_permissions", "/otherdir : list ,upload ")
  1272. form.Set("status", strconv.Itoa(user.Status))
  1273. form.Set("expiration_date", "2020-01-01 00:00:00")
  1274. form.Set("allowed_ip", " 192.168.1.3/32, 192.168.2.0/24 ")
  1275. form.Set("denied_ip", " 10.0.0.2/32 ")
  1276. req, _ = http.NewRequest(http.MethodPost, webUserPath+"/"+strconv.FormatInt(user.ID, 10), strings.NewReader(form.Encode()))
  1277. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1278. rr = executeRequest(req)
  1279. checkResponseCode(t, http.StatusSeeOther, rr.Code)
  1280. req, _ = http.NewRequest(http.MethodGet, userPath+"?limit=1&offset=0&order=ASC&username="+user.Username, nil)
  1281. rr = executeRequest(req)
  1282. checkResponseCode(t, http.StatusOK, rr.Code)
  1283. var users []dataprovider.User
  1284. err = render.DecodeJSON(rr.Body, &users)
  1285. if err != nil {
  1286. t.Errorf("Error decoding users: %v", err)
  1287. }
  1288. if len(users) != 1 {
  1289. t.Errorf("1 user is expected")
  1290. }
  1291. updateUser := users[0]
  1292. if user.HomeDir != updateUser.HomeDir {
  1293. t.Errorf("home dir does not match")
  1294. }
  1295. if user.MaxSessions != updateUser.MaxSessions {
  1296. t.Errorf("max_sessions does not match")
  1297. }
  1298. if user.QuotaFiles != updateUser.QuotaFiles {
  1299. t.Errorf("quota_files does not match")
  1300. }
  1301. if user.QuotaSize != updateUser.QuotaSize {
  1302. t.Errorf("quota_size does not match")
  1303. }
  1304. if user.GID != updateUser.GID {
  1305. t.Errorf("gid does not match")
  1306. }
  1307. if val, ok := updateUser.Permissions["/otherdir"]; ok {
  1308. if !utils.IsStringInSlice(dataprovider.PermListItems, val) || !utils.IsStringInSlice(dataprovider.PermUpload, val) {
  1309. t.Error("permssions for /otherdir does not match")
  1310. }
  1311. } else {
  1312. t.Errorf("user permissions must contains /otherdir, actual: %v", updateUser.Permissions)
  1313. }
  1314. if !utils.IsStringInSlice("192.168.1.3/32", updateUser.Filters.AllowedIP) {
  1315. t.Errorf("Allowed IP/Mask does not match: %v", updateUser.Filters.AllowedIP)
  1316. }
  1317. if !utils.IsStringInSlice("10.0.0.2/32", updateUser.Filters.DeniedIP) {
  1318. t.Errorf("Denied IP/Mask does not match: %v", updateUser.Filters.DeniedIP)
  1319. }
  1320. req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  1321. rr = executeRequest(req)
  1322. checkResponseCode(t, http.StatusOK, rr.Code)
  1323. }
  1324. func TestProviderClosedMock(t *testing.T) {
  1325. if providerDriverName == dataprovider.BoltDataProviderName {
  1326. t.Skip("skipping test provider errors for bolt provider")
  1327. }
  1328. dataProvider := dataprovider.GetProvider()
  1329. dataprovider.Close(dataProvider)
  1330. req, _ := http.NewRequest(http.MethodGet, webUsersPath, nil)
  1331. rr := executeRequest(req)
  1332. checkResponseCode(t, http.StatusInternalServerError, rr.Code)
  1333. req, _ = http.NewRequest(http.MethodGet, webUserPath+"/0", nil)
  1334. rr = executeRequest(req)
  1335. checkResponseCode(t, http.StatusInternalServerError, rr.Code)
  1336. form := make(url.Values)
  1337. form.Set("username", "test")
  1338. req, _ = http.NewRequest(http.MethodPost, webUserPath+"/0", strings.NewReader(form.Encode()))
  1339. rr = executeRequest(req)
  1340. checkResponseCode(t, http.StatusInternalServerError, rr.Code)
  1341. config.LoadConfig(configDir, "")
  1342. providerConf := config.GetProviderConf()
  1343. err := dataprovider.Initialize(providerConf, configDir)
  1344. if err != nil {
  1345. t.Errorf("error initializing data provider")
  1346. }
  1347. httpd.SetDataProvider(dataprovider.GetProvider())
  1348. sftpd.SetDataProvider(dataprovider.GetProvider())
  1349. }
  1350. func TestGetWebConnectionsMock(t *testing.T) {
  1351. req, _ := http.NewRequest(http.MethodGet, webConnectionsPath, nil)
  1352. rr := executeRequest(req)
  1353. checkResponseCode(t, http.StatusOK, rr.Code)
  1354. }
  1355. func TestStaticFilesMock(t *testing.T) {
  1356. req, _ := http.NewRequest(http.MethodGet, "/static/favicon.ico", nil)
  1357. rr := executeRequest(req)
  1358. checkResponseCode(t, http.StatusOK, rr.Code)
  1359. }
  1360. func waitTCPListening(address string) {
  1361. for {
  1362. conn, err := net.Dial("tcp", address)
  1363. if err != nil {
  1364. logger.WarnToConsole("tcp server %v not listening: %v\n", address, err)
  1365. time.Sleep(100 * time.Millisecond)
  1366. continue
  1367. }
  1368. logger.InfoToConsole("tcp server %v now listening\n", address)
  1369. defer conn.Close()
  1370. break
  1371. }
  1372. }
  1373. func getTestUser() dataprovider.User {
  1374. user := dataprovider.User{
  1375. Username: defaultUsername,
  1376. Password: defaultPassword,
  1377. HomeDir: filepath.Join(homeBasePath, defaultUsername),
  1378. Status: 1,
  1379. }
  1380. user.Permissions = make(map[string][]string)
  1381. user.Permissions["/"] = defaultPerms
  1382. return user
  1383. }
  1384. func getUserAsJSON(t *testing.T, user dataprovider.User) []byte {
  1385. json, err := json.Marshal(user)
  1386. if err != nil {
  1387. t.Errorf("error get user as json: %v", err)
  1388. return []byte("{}")
  1389. }
  1390. return json
  1391. }
  1392. func executeRequest(req *http.Request) *httptest.ResponseRecorder {
  1393. rr := httptest.NewRecorder()
  1394. testServer.Config.Handler.ServeHTTP(rr, req)
  1395. return rr
  1396. }
  1397. func checkResponseCode(t *testing.T, expected, actual int) {
  1398. if expected != actual {
  1399. t.Errorf("Expected response code %d. Got %d", expected, actual)
  1400. }
  1401. }
  1402. func createTestFile(path string, size int64) error {
  1403. baseDir := filepath.Dir(path)
  1404. if _, err := os.Stat(baseDir); os.IsNotExist(err) {
  1405. os.MkdirAll(baseDir, 0777)
  1406. }
  1407. content := make([]byte, size)
  1408. _, err := rand.Read(content)
  1409. if err != nil {
  1410. return err
  1411. }
  1412. return ioutil.WriteFile(path, content, 0666)
  1413. }