api_utils.go 8.9 KB

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