api_utils.go 8.4 KB

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