api_utils.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. package api
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "net/url"
  10. "path"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/drakkan/sftpgo/dataprovider"
  15. "github.com/drakkan/sftpgo/sftpd"
  16. "github.com/drakkan/sftpgo/utils"
  17. "github.com/go-chi/render"
  18. )
  19. var (
  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. func buildURLRelativeToBase(paths ...string) string {
  33. // we need to use path.Join and not filepath.Join
  34. // since filepath.Join will use backslash separator on Windows
  35. p := path.Join(paths...)
  36. return fmt.Sprintf("%s/%s", strings.TrimRight(httpBaseURL, "/"), strings.TrimLeft(p, "/"))
  37. }
  38. // AddUser adds a new user and checks the received HTTP Status code against expectedStatusCode.
  39. func AddUser(user dataprovider.User, expectedStatusCode int) (dataprovider.User, []byte, error) {
  40. var newUser dataprovider.User
  41. var body []byte
  42. userAsJSON, err := json.Marshal(user)
  43. if err != nil {
  44. return newUser, body, err
  45. }
  46. resp, err := getHTTPClient().Post(buildURLRelativeToBase(userPath), "application/json", bytes.NewBuffer(userAsJSON))
  47. if err != nil {
  48. return newUser, body, err
  49. }
  50. defer resp.Body.Close()
  51. err = checkResponse(resp.StatusCode, expectedStatusCode)
  52. if expectedStatusCode != http.StatusOK {
  53. body, _ = getResponseBody(resp)
  54. return newUser, body, err
  55. }
  56. if err == nil {
  57. err = render.DecodeJSON(resp.Body, &newUser)
  58. } else {
  59. body, _ = getResponseBody(resp)
  60. }
  61. if err == nil {
  62. err = checkUser(user, newUser)
  63. }
  64. return newUser, body, err
  65. }
  66. // UpdateUser updates an existing user and checks the received HTTP Status code against expectedStatusCode.
  67. func UpdateUser(user dataprovider.User, expectedStatusCode int) (dataprovider.User, []byte, error) {
  68. var newUser dataprovider.User
  69. var body []byte
  70. userAsJSON, err := json.Marshal(user)
  71. if err != nil {
  72. return user, body, err
  73. }
  74. req, err := http.NewRequest(http.MethodPut, buildURLRelativeToBase(userPath, strconv.FormatInt(user.ID, 10)),
  75. bytes.NewBuffer(userAsJSON))
  76. if err != nil {
  77. return user, body, err
  78. }
  79. resp, err := getHTTPClient().Do(req)
  80. if err != nil {
  81. return user, body, err
  82. }
  83. defer resp.Body.Close()
  84. body, _ = getResponseBody(resp)
  85. err = checkResponse(resp.StatusCode, expectedStatusCode)
  86. if expectedStatusCode != http.StatusOK {
  87. return newUser, body, err
  88. }
  89. if err == nil {
  90. newUser, body, err = GetUserByID(user.ID, expectedStatusCode)
  91. }
  92. if err == nil {
  93. err = checkUser(user, newUser)
  94. }
  95. return newUser, body, err
  96. }
  97. // RemoveUser removes an existing user and checks the received HTTP Status code against expectedStatusCode.
  98. func RemoveUser(user dataprovider.User, expectedStatusCode int) ([]byte, error) {
  99. var body []byte
  100. req, err := http.NewRequest(http.MethodDelete, buildURLRelativeToBase(userPath, strconv.FormatInt(user.ID, 10)), nil)
  101. if err != nil {
  102. return body, err
  103. }
  104. resp, err := getHTTPClient().Do(req)
  105. if err != nil {
  106. return body, err
  107. }
  108. defer resp.Body.Close()
  109. body, _ = getResponseBody(resp)
  110. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  111. }
  112. // GetUserByID gets an user by database id and checks the received HTTP Status code against expectedStatusCode.
  113. func GetUserByID(userID int64, expectedStatusCode int) (dataprovider.User, []byte, error) {
  114. var user dataprovider.User
  115. var body []byte
  116. resp, err := getHTTPClient().Get(buildURLRelativeToBase(userPath, strconv.FormatInt(userID, 10)))
  117. if err != nil {
  118. return user, body, err
  119. }
  120. defer resp.Body.Close()
  121. err = checkResponse(resp.StatusCode, expectedStatusCode)
  122. if err == nil && expectedStatusCode == http.StatusOK {
  123. err = render.DecodeJSON(resp.Body, &user)
  124. } else {
  125. body, _ = getResponseBody(resp)
  126. }
  127. return user, body, err
  128. }
  129. // GetUsers allows to get a list of users and checks the received HTTP Status code against expectedStatusCode.
  130. // The number of results can be limited specifying a limit.
  131. // Some results can be skipped specifying an offset.
  132. // The results can be filtered specifying an username, the username filter is an exact match
  133. func GetUsers(limit int64, offset int64, username string, expectedStatusCode int) ([]dataprovider.User, []byte, error) {
  134. var users []dataprovider.User
  135. var body []byte
  136. url, err := url.Parse(buildURLRelativeToBase(userPath))
  137. if err != nil {
  138. return users, body, err
  139. }
  140. q := url.Query()
  141. if limit > 0 {
  142. q.Add("limit", strconv.FormatInt(limit, 10))
  143. }
  144. if offset > 0 {
  145. q.Add("offset", strconv.FormatInt(offset, 10))
  146. }
  147. if len(username) > 0 {
  148. q.Add("username", username)
  149. }
  150. url.RawQuery = q.Encode()
  151. resp, err := getHTTPClient().Get(url.String())
  152. if err != nil {
  153. return users, body, err
  154. }
  155. defer resp.Body.Close()
  156. err = checkResponse(resp.StatusCode, expectedStatusCode)
  157. if err == nil && expectedStatusCode == http.StatusOK {
  158. err = render.DecodeJSON(resp.Body, &users)
  159. } else {
  160. body, _ = getResponseBody(resp)
  161. }
  162. return users, body, err
  163. }
  164. // GetQuotaScans gets active quota scans and checks the received HTTP Status code against expectedStatusCode.
  165. func GetQuotaScans(expectedStatusCode int) ([]sftpd.ActiveQuotaScan, []byte, error) {
  166. var quotaScans []sftpd.ActiveQuotaScan
  167. var body []byte
  168. resp, err := getHTTPClient().Get(buildURLRelativeToBase(quotaScanPath))
  169. if err != nil {
  170. return quotaScans, body, err
  171. }
  172. defer resp.Body.Close()
  173. err = checkResponse(resp.StatusCode, expectedStatusCode)
  174. if err == nil && expectedStatusCode == http.StatusOK {
  175. err = render.DecodeJSON(resp.Body, &quotaScans)
  176. } else {
  177. body, _ = getResponseBody(resp)
  178. }
  179. return quotaScans, body, err
  180. }
  181. // StartQuotaScan start a new quota scan for the given user and checks the received HTTP Status code against expectedStatusCode.
  182. func StartQuotaScan(user dataprovider.User, expectedStatusCode int) ([]byte, error) {
  183. var body []byte
  184. userAsJSON, err := json.Marshal(user)
  185. if err != nil {
  186. return body, err
  187. }
  188. resp, err := getHTTPClient().Post(buildURLRelativeToBase(quotaScanPath), "application/json", bytes.NewBuffer(userAsJSON))
  189. if err != nil {
  190. return body, err
  191. }
  192. defer resp.Body.Close()
  193. body, _ = getResponseBody(resp)
  194. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  195. }
  196. // GetConnections returns status and stats for active SFTP/SCP connections
  197. func GetConnections(expectedStatusCode int) ([]sftpd.ConnectionStatus, []byte, error) {
  198. var connections []sftpd.ConnectionStatus
  199. var body []byte
  200. resp, err := getHTTPClient().Get(buildURLRelativeToBase(activeConnectionsPath))
  201. if err != nil {
  202. return connections, body, err
  203. }
  204. defer resp.Body.Close()
  205. err = checkResponse(resp.StatusCode, expectedStatusCode)
  206. if err == nil && expectedStatusCode == http.StatusOK {
  207. err = render.DecodeJSON(resp.Body, &connections)
  208. } else {
  209. body, _ = getResponseBody(resp)
  210. }
  211. return connections, body, err
  212. }
  213. // CloseConnection closes an active connection identified by connectionID
  214. func CloseConnection(connectionID string, expectedStatusCode int) ([]byte, error) {
  215. var body []byte
  216. req, err := http.NewRequest(http.MethodDelete, buildURLRelativeToBase(activeConnectionsPath, connectionID), nil)
  217. if err != nil {
  218. return body, err
  219. }
  220. resp, err := getHTTPClient().Do(req)
  221. if err != nil {
  222. return body, err
  223. }
  224. defer resp.Body.Close()
  225. err = checkResponse(resp.StatusCode, expectedStatusCode)
  226. body, _ = getResponseBody(resp)
  227. return body, err
  228. }
  229. // GetVersion returns version details
  230. func GetVersion(expectedStatusCode int) (utils.VersionInfo, []byte, error) {
  231. var version utils.VersionInfo
  232. var body []byte
  233. resp, err := getHTTPClient().Get(buildURLRelativeToBase(versionPath))
  234. if err != nil {
  235. return version, body, err
  236. }
  237. defer resp.Body.Close()
  238. err = checkResponse(resp.StatusCode, expectedStatusCode)
  239. if err == nil && expectedStatusCode == http.StatusOK {
  240. err = render.DecodeJSON(resp.Body, &version)
  241. } else {
  242. body, _ = getResponseBody(resp)
  243. }
  244. return version, body, err
  245. }
  246. func checkResponse(actual int, expected int) error {
  247. if expected != actual {
  248. return fmt.Errorf("wrong status code: got %v want %v", actual, expected)
  249. }
  250. return nil
  251. }
  252. func getResponseBody(resp *http.Response) ([]byte, error) {
  253. return ioutil.ReadAll(resp.Body)
  254. }
  255. func checkUser(expected dataprovider.User, actual dataprovider.User) error {
  256. if len(actual.Password) > 0 {
  257. return errors.New("User password must not be visible")
  258. }
  259. if len(actual.PublicKeys) > 0 {
  260. return errors.New("User public keys must not be visible")
  261. }
  262. if expected.ID <= 0 {
  263. if actual.ID <= 0 {
  264. return errors.New("actual user ID must be > 0")
  265. }
  266. } else {
  267. if actual.ID != expected.ID {
  268. return errors.New("user ID mismatch")
  269. }
  270. }
  271. for _, v := range expected.Permissions {
  272. if !utils.IsStringInSlice(v, actual.Permissions) {
  273. return errors.New("Permissions contents mismatch")
  274. }
  275. }
  276. return compareEqualsUserFields(expected, actual)
  277. }
  278. func compareEqualsUserFields(expected dataprovider.User, actual dataprovider.User) error {
  279. if expected.Username != actual.Username {
  280. return errors.New("Username mismatch")
  281. }
  282. if expected.HomeDir != actual.HomeDir {
  283. return errors.New("HomeDir mismatch")
  284. }
  285. if expected.UID != actual.UID {
  286. return errors.New("UID mismatch")
  287. }
  288. if expected.GID != actual.GID {
  289. return errors.New("GID mismatch")
  290. }
  291. if expected.MaxSessions != actual.MaxSessions {
  292. return errors.New("MaxSessions mismatch")
  293. }
  294. if expected.QuotaSize != actual.QuotaSize {
  295. return errors.New("QuotaSize mismatch")
  296. }
  297. if expected.QuotaFiles != actual.QuotaFiles {
  298. return errors.New("QuotaFiles mismatch")
  299. }
  300. if len(expected.Permissions) != len(actual.Permissions) {
  301. return errors.New("Permissions mismatch")
  302. }
  303. if expected.UploadBandwidth != actual.UploadBandwidth {
  304. return errors.New("UploadBandwidth mismatch")
  305. }
  306. if expected.DownloadBandwidth != actual.DownloadBandwidth {
  307. return errors.New("DownloadBandwidth mismatch")
  308. }
  309. return nil
  310. }