api_utils.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. package api
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "net/url"
  10. "strconv"
  11. "time"
  12. "github.com/drakkan/sftpgo/dataprovider"
  13. "github.com/drakkan/sftpgo/sftpd"
  14. "github.com/drakkan/sftpgo/utils"
  15. "github.com/go-chi/render"
  16. )
  17. var (
  18. defaultPerms = []string{dataprovider.PermAny}
  19. httpBaseURL = "http://127.0.0.1:8080"
  20. )
  21. // SetBaseURL sets the base url to use for HTTP requests, default is "http://127.0.0.1:8080"
  22. func SetBaseURL(url string) {
  23. httpBaseURL = url
  24. }
  25. // gets an HTTP Client with a timeout
  26. func getHTTPClient() *http.Client {
  27. return &http.Client{
  28. Timeout: 15 * time.Second,
  29. }
  30. }
  31. // AddUser adds a new user and checks the received HTTP Status code against expectedStatusCode.
  32. func AddUser(user dataprovider.User, expectedStatusCode int) (dataprovider.User, error) {
  33. var newUser dataprovider.User
  34. userAsJSON, err := json.Marshal(user)
  35. if err != nil {
  36. return newUser, err
  37. }
  38. resp, err := getHTTPClient().Post(httpBaseURL+userPath, "application/json", bytes.NewBuffer(userAsJSON))
  39. if err != nil {
  40. return newUser, err
  41. }
  42. defer resp.Body.Close()
  43. err = checkResponse(resp.StatusCode, expectedStatusCode, resp)
  44. if expectedStatusCode != http.StatusOK {
  45. return newUser, err
  46. }
  47. if err == nil {
  48. err = render.DecodeJSON(resp.Body, &newUser)
  49. }
  50. if err == nil {
  51. err = checkUser(user, newUser)
  52. }
  53. return newUser, err
  54. }
  55. // UpdateUser updates an existing user and checks the received HTTP Status code against expectedStatusCode.
  56. func UpdateUser(user dataprovider.User, expectedStatusCode int) (dataprovider.User, error) {
  57. var newUser dataprovider.User
  58. userAsJSON, err := json.Marshal(user)
  59. if err != nil {
  60. return user, err
  61. }
  62. req, err := http.NewRequest(http.MethodPut, httpBaseURL+userPath+"/"+strconv.FormatInt(user.ID, 10), bytes.NewBuffer(userAsJSON))
  63. if err != nil {
  64. return user, err
  65. }
  66. resp, err := getHTTPClient().Do(req)
  67. if err != nil {
  68. return user, err
  69. }
  70. defer resp.Body.Close()
  71. err = checkResponse(resp.StatusCode, expectedStatusCode, resp)
  72. if expectedStatusCode != http.StatusOK {
  73. return newUser, err
  74. }
  75. if err == nil {
  76. newUser, err = GetUserByID(user.ID, expectedStatusCode)
  77. }
  78. if err == nil {
  79. err = checkUser(user, newUser)
  80. }
  81. return newUser, err
  82. }
  83. // RemoveUser removes an existing user and checks the received HTTP Status code against expectedStatusCode.
  84. func RemoveUser(user dataprovider.User, expectedStatusCode int) error {
  85. req, err := http.NewRequest(http.MethodDelete, httpBaseURL+userPath+"/"+strconv.FormatInt(user.ID, 10), nil)
  86. if err != nil {
  87. return err
  88. }
  89. resp, err := getHTTPClient().Do(req)
  90. if err != nil {
  91. return err
  92. }
  93. defer resp.Body.Close()
  94. return checkResponse(resp.StatusCode, expectedStatusCode, resp)
  95. }
  96. // GetUserByID gets an user by database id and checks the received HTTP Status code against expectedStatusCode.
  97. func GetUserByID(userID int64, expectedStatusCode int) (dataprovider.User, error) {
  98. var user dataprovider.User
  99. resp, err := getHTTPClient().Get(httpBaseURL + userPath + "/" + strconv.FormatInt(userID, 10))
  100. if err != nil {
  101. return user, err
  102. }
  103. defer resp.Body.Close()
  104. err = checkResponse(resp.StatusCode, expectedStatusCode, resp)
  105. if err == nil && expectedStatusCode == http.StatusOK {
  106. err = render.DecodeJSON(resp.Body, &user)
  107. }
  108. return user, err
  109. }
  110. // GetUsers allows to get a list of users and checks the received HTTP Status code against expectedStatusCode.
  111. // The number of results can be limited specifying a limit.
  112. // Some results can be skipped specifying an offset.
  113. // The results can be filtered specifying an username, the username filter is an exact match
  114. func GetUsers(limit int64, offset int64, username string, expectedStatusCode int) ([]dataprovider.User, error) {
  115. var users []dataprovider.User
  116. url, err := url.Parse(httpBaseURL + userPath)
  117. if err != nil {
  118. return users, err
  119. }
  120. q := url.Query()
  121. if limit > 0 {
  122. q.Add("limit", strconv.FormatInt(limit, 10))
  123. }
  124. if offset > 0 {
  125. q.Add("offset", strconv.FormatInt(offset, 10))
  126. }
  127. if len(username) > 0 {
  128. q.Add("username", username)
  129. }
  130. url.RawQuery = q.Encode()
  131. resp, err := getHTTPClient().Get(url.String())
  132. if err != nil {
  133. return users, err
  134. }
  135. defer resp.Body.Close()
  136. err = checkResponse(resp.StatusCode, expectedStatusCode, resp)
  137. if err == nil && expectedStatusCode == http.StatusOK {
  138. err = render.DecodeJSON(resp.Body, &users)
  139. }
  140. return users, err
  141. }
  142. // GetQuotaScans gets active quota scans and checks the received HTTP Status code against expectedStatusCode.
  143. func GetQuotaScans(expectedStatusCode int) ([]sftpd.ActiveQuotaScan, error) {
  144. var quotaScans []sftpd.ActiveQuotaScan
  145. resp, err := getHTTPClient().Get(httpBaseURL + quotaScanPath)
  146. if err != nil {
  147. return quotaScans, err
  148. }
  149. defer resp.Body.Close()
  150. err = checkResponse(resp.StatusCode, expectedStatusCode, resp)
  151. if err == nil && expectedStatusCode == http.StatusOK {
  152. err = render.DecodeJSON(resp.Body, &quotaScans)
  153. }
  154. return quotaScans, err
  155. }
  156. // StartQuotaScan start a new quota scan for the given user and checks the received HTTP Status code against expectedStatusCode.
  157. func StartQuotaScan(user dataprovider.User, expectedStatusCode int) error {
  158. userAsJSON, err := json.Marshal(user)
  159. if err != nil {
  160. return err
  161. }
  162. resp, err := getHTTPClient().Post(httpBaseURL+quotaScanPath, "application/json", bytes.NewBuffer(userAsJSON))
  163. if err != nil {
  164. return err
  165. }
  166. defer resp.Body.Close()
  167. return checkResponse(resp.StatusCode, expectedStatusCode, resp)
  168. }
  169. func checkResponse(actual int, expected int, resp *http.Response) error {
  170. if expected != actual {
  171. return fmt.Errorf("wrong status code: got %v want %v", actual, expected)
  172. }
  173. if expected != http.StatusOK && resp != nil {
  174. b, err := ioutil.ReadAll(resp.Body)
  175. if err == nil {
  176. fmt.Printf("request: %v, response body: %v", resp.Request.URL, string(b))
  177. }
  178. }
  179. return nil
  180. }
  181. func checkUser(expected dataprovider.User, actual dataprovider.User) error {
  182. if len(actual.Password) > 0 {
  183. return errors.New("User password must not be visible")
  184. }
  185. if len(actual.PublicKey) > 0 {
  186. return errors.New("User public key must not be visible")
  187. }
  188. if expected.ID <= 0 {
  189. if actual.ID <= 0 {
  190. return errors.New("actual user ID must be > 0")
  191. }
  192. } else {
  193. if actual.ID != expected.ID {
  194. return errors.New("user ID mismatch")
  195. }
  196. }
  197. for _, v := range expected.Permissions {
  198. if !utils.IsStringInSlice(v, actual.Permissions) {
  199. return errors.New("Permissions contents mismatch")
  200. }
  201. }
  202. return compareEqualsUserFields(expected, actual)
  203. }
  204. func compareEqualsUserFields(expected dataprovider.User, actual dataprovider.User) error {
  205. if expected.Username != actual.Username {
  206. return errors.New("Username mismatch")
  207. }
  208. if expected.HomeDir != actual.HomeDir {
  209. return errors.New("HomeDir mismatch")
  210. }
  211. if expected.UID != actual.UID {
  212. return errors.New("UID mismatch")
  213. }
  214. if expected.GID != actual.GID {
  215. return errors.New("GID mismatch")
  216. }
  217. if expected.MaxSessions != actual.MaxSessions {
  218. return errors.New("MaxSessions mismatch")
  219. }
  220. if expected.QuotaSize != actual.QuotaSize {
  221. return errors.New("QuotaSize mismatch")
  222. }
  223. if expected.QuotaFiles != actual.QuotaFiles {
  224. return errors.New("QuotaFiles mismatch")
  225. }
  226. if len(expected.Permissions) != len(actual.Permissions) {
  227. return errors.New("Permissions mismatch")
  228. }
  229. if expected.UploadBandwidth != actual.UploadBandwidth {
  230. return errors.New("UploadBandwidth mismatch")
  231. }
  232. if expected.DownloadBandwidth != actual.DownloadBandwidth {
  233. return errors.New("DownloadBandwidth mismatch")
  234. }
  235. return nil
  236. }