api_utils.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. package httpd
  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. func sendAPIResponse(w http.ResponseWriter, r *http.Request, err error, message string, code int) {
  39. var errorString string
  40. if err != nil {
  41. errorString = err.Error()
  42. }
  43. resp := apiResponse{
  44. Error: errorString,
  45. Message: message,
  46. HTTPStatus: code,
  47. }
  48. if code != http.StatusOK {
  49. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  50. w.WriteHeader(code)
  51. }
  52. render.JSON(w, r, resp)
  53. }
  54. func getRespStatus(err error) int {
  55. if _, ok := err.(*dataprovider.ValidationError); ok {
  56. return http.StatusBadRequest
  57. }
  58. if _, ok := err.(*dataprovider.MethodDisabledError); ok {
  59. return http.StatusForbidden
  60. }
  61. return http.StatusInternalServerError
  62. }
  63. // AddUser adds a new user and checks the received HTTP Status code against expectedStatusCode.
  64. func AddUser(user dataprovider.User, expectedStatusCode int) (dataprovider.User, []byte, error) {
  65. var newUser dataprovider.User
  66. var body []byte
  67. userAsJSON, err := json.Marshal(user)
  68. if err != nil {
  69. return newUser, body, err
  70. }
  71. resp, err := getHTTPClient().Post(buildURLRelativeToBase(userPath), "application/json", bytes.NewBuffer(userAsJSON))
  72. if err != nil {
  73. return newUser, body, err
  74. }
  75. defer resp.Body.Close()
  76. err = checkResponse(resp.StatusCode, expectedStatusCode)
  77. if expectedStatusCode != http.StatusOK {
  78. body, _ = getResponseBody(resp)
  79. return newUser, body, err
  80. }
  81. if err == nil {
  82. err = render.DecodeJSON(resp.Body, &newUser)
  83. } else {
  84. body, _ = getResponseBody(resp)
  85. }
  86. if err == nil {
  87. err = checkUser(user, newUser)
  88. }
  89. return newUser, body, err
  90. }
  91. // UpdateUser updates an existing user and checks the received HTTP Status code against expectedStatusCode.
  92. func UpdateUser(user dataprovider.User, expectedStatusCode int) (dataprovider.User, []byte, error) {
  93. var newUser dataprovider.User
  94. var body []byte
  95. userAsJSON, err := json.Marshal(user)
  96. if err != nil {
  97. return user, body, err
  98. }
  99. req, err := http.NewRequest(http.MethodPut, buildURLRelativeToBase(userPath, strconv.FormatInt(user.ID, 10)),
  100. bytes.NewBuffer(userAsJSON))
  101. if err != nil {
  102. return user, body, err
  103. }
  104. resp, err := getHTTPClient().Do(req)
  105. if err != nil {
  106. return user, body, err
  107. }
  108. defer resp.Body.Close()
  109. body, _ = getResponseBody(resp)
  110. err = checkResponse(resp.StatusCode, expectedStatusCode)
  111. if expectedStatusCode != http.StatusOK {
  112. return newUser, body, err
  113. }
  114. if err == nil {
  115. newUser, body, err = GetUserByID(user.ID, expectedStatusCode)
  116. }
  117. if err == nil {
  118. err = checkUser(user, newUser)
  119. }
  120. return newUser, body, err
  121. }
  122. // RemoveUser removes an existing user and checks the received HTTP Status code against expectedStatusCode.
  123. func RemoveUser(user dataprovider.User, expectedStatusCode int) ([]byte, error) {
  124. var body []byte
  125. req, err := http.NewRequest(http.MethodDelete, buildURLRelativeToBase(userPath, strconv.FormatInt(user.ID, 10)), nil)
  126. if err != nil {
  127. return body, err
  128. }
  129. resp, err := getHTTPClient().Do(req)
  130. if err != nil {
  131. return body, err
  132. }
  133. defer resp.Body.Close()
  134. body, _ = getResponseBody(resp)
  135. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  136. }
  137. // GetUserByID gets an user by database id and checks the received HTTP Status code against expectedStatusCode.
  138. func GetUserByID(userID int64, expectedStatusCode int) (dataprovider.User, []byte, error) {
  139. var user dataprovider.User
  140. var body []byte
  141. resp, err := getHTTPClient().Get(buildURLRelativeToBase(userPath, strconv.FormatInt(userID, 10)))
  142. if err != nil {
  143. return user, body, err
  144. }
  145. defer resp.Body.Close()
  146. err = checkResponse(resp.StatusCode, expectedStatusCode)
  147. if err == nil && expectedStatusCode == http.StatusOK {
  148. err = render.DecodeJSON(resp.Body, &user)
  149. } else {
  150. body, _ = getResponseBody(resp)
  151. }
  152. return user, body, err
  153. }
  154. // GetUsers allows to get a list of users and checks the received HTTP Status code against expectedStatusCode.
  155. // The number of results can be limited specifying a limit.
  156. // Some results can be skipped specifying an offset.
  157. // The results can be filtered specifying an username, the username filter is an exact match
  158. func GetUsers(limit int64, offset int64, username string, expectedStatusCode int) ([]dataprovider.User, []byte, error) {
  159. var users []dataprovider.User
  160. var body []byte
  161. url, err := url.Parse(buildURLRelativeToBase(userPath))
  162. if err != nil {
  163. return users, body, err
  164. }
  165. q := url.Query()
  166. if limit > 0 {
  167. q.Add("limit", strconv.FormatInt(limit, 10))
  168. }
  169. if offset > 0 {
  170. q.Add("offset", strconv.FormatInt(offset, 10))
  171. }
  172. if len(username) > 0 {
  173. q.Add("username", username)
  174. }
  175. url.RawQuery = q.Encode()
  176. resp, err := getHTTPClient().Get(url.String())
  177. if err != nil {
  178. return users, body, err
  179. }
  180. defer resp.Body.Close()
  181. err = checkResponse(resp.StatusCode, expectedStatusCode)
  182. if err == nil && expectedStatusCode == http.StatusOK {
  183. err = render.DecodeJSON(resp.Body, &users)
  184. } else {
  185. body, _ = getResponseBody(resp)
  186. }
  187. return users, body, err
  188. }
  189. // GetQuotaScans gets active quota scans and checks the received HTTP Status code against expectedStatusCode.
  190. func GetQuotaScans(expectedStatusCode int) ([]sftpd.ActiveQuotaScan, []byte, error) {
  191. var quotaScans []sftpd.ActiveQuotaScan
  192. var body []byte
  193. resp, err := getHTTPClient().Get(buildURLRelativeToBase(quotaScanPath))
  194. if err != nil {
  195. return quotaScans, body, err
  196. }
  197. defer resp.Body.Close()
  198. err = checkResponse(resp.StatusCode, expectedStatusCode)
  199. if err == nil && expectedStatusCode == http.StatusOK {
  200. err = render.DecodeJSON(resp.Body, &quotaScans)
  201. } else {
  202. body, _ = getResponseBody(resp)
  203. }
  204. return quotaScans, body, err
  205. }
  206. // StartQuotaScan start a new quota scan for the given user and checks the received HTTP Status code against expectedStatusCode.
  207. func StartQuotaScan(user dataprovider.User, expectedStatusCode int) ([]byte, error) {
  208. var body []byte
  209. userAsJSON, err := json.Marshal(user)
  210. if err != nil {
  211. return body, err
  212. }
  213. resp, err := getHTTPClient().Post(buildURLRelativeToBase(quotaScanPath), "application/json", bytes.NewBuffer(userAsJSON))
  214. if err != nil {
  215. return body, err
  216. }
  217. defer resp.Body.Close()
  218. body, _ = getResponseBody(resp)
  219. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  220. }
  221. // GetConnections returns status and stats for active SFTP/SCP connections
  222. func GetConnections(expectedStatusCode int) ([]sftpd.ConnectionStatus, []byte, error) {
  223. var connections []sftpd.ConnectionStatus
  224. var body []byte
  225. resp, err := getHTTPClient().Get(buildURLRelativeToBase(activeConnectionsPath))
  226. if err != nil {
  227. return connections, body, err
  228. }
  229. defer resp.Body.Close()
  230. err = checkResponse(resp.StatusCode, expectedStatusCode)
  231. if err == nil && expectedStatusCode == http.StatusOK {
  232. err = render.DecodeJSON(resp.Body, &connections)
  233. } else {
  234. body, _ = getResponseBody(resp)
  235. }
  236. return connections, body, err
  237. }
  238. // CloseConnection closes an active connection identified by connectionID
  239. func CloseConnection(connectionID string, expectedStatusCode int) ([]byte, error) {
  240. var body []byte
  241. req, err := http.NewRequest(http.MethodDelete, buildURLRelativeToBase(activeConnectionsPath, connectionID), nil)
  242. if err != nil {
  243. return body, err
  244. }
  245. resp, err := getHTTPClient().Do(req)
  246. if err != nil {
  247. return body, err
  248. }
  249. defer resp.Body.Close()
  250. err = checkResponse(resp.StatusCode, expectedStatusCode)
  251. body, _ = getResponseBody(resp)
  252. return body, err
  253. }
  254. // GetVersion returns version details
  255. func GetVersion(expectedStatusCode int) (utils.VersionInfo, []byte, error) {
  256. var version utils.VersionInfo
  257. var body []byte
  258. resp, err := getHTTPClient().Get(buildURLRelativeToBase(versionPath))
  259. if err != nil {
  260. return version, body, err
  261. }
  262. defer resp.Body.Close()
  263. err = checkResponse(resp.StatusCode, expectedStatusCode)
  264. if err == nil && expectedStatusCode == http.StatusOK {
  265. err = render.DecodeJSON(resp.Body, &version)
  266. } else {
  267. body, _ = getResponseBody(resp)
  268. }
  269. return version, body, err
  270. }
  271. // GetProviderStatus returns provider status
  272. func GetProviderStatus(expectedStatusCode int) (map[string]interface{}, []byte, error) {
  273. var response map[string]interface{}
  274. var body []byte
  275. resp, err := getHTTPClient().Get(buildURLRelativeToBase(providerStatusPath))
  276. if err != nil {
  277. return response, body, err
  278. }
  279. defer resp.Body.Close()
  280. err = checkResponse(resp.StatusCode, expectedStatusCode)
  281. if err == nil && (expectedStatusCode == http.StatusOK || expectedStatusCode == http.StatusInternalServerError) {
  282. err = render.DecodeJSON(resp.Body, &response)
  283. } else {
  284. body, _ = getResponseBody(resp)
  285. }
  286. return response, body, err
  287. }
  288. func checkResponse(actual int, expected int) error {
  289. if expected != actual {
  290. return fmt.Errorf("wrong status code: got %v want %v", actual, expected)
  291. }
  292. return nil
  293. }
  294. func getResponseBody(resp *http.Response) ([]byte, error) {
  295. return ioutil.ReadAll(resp.Body)
  296. }
  297. func checkUser(expected dataprovider.User, actual dataprovider.User) error {
  298. if len(actual.Password) > 0 {
  299. return errors.New("User password must not be visible")
  300. }
  301. if expected.ID <= 0 {
  302. if actual.ID <= 0 {
  303. return errors.New("actual user ID must be > 0")
  304. }
  305. } else {
  306. if actual.ID != expected.ID {
  307. return errors.New("user ID mismatch")
  308. }
  309. }
  310. for _, v := range expected.Permissions {
  311. if !utils.IsStringInSlice(v, actual.Permissions) {
  312. return errors.New("Permissions contents mismatch")
  313. }
  314. }
  315. return compareEqualsUserFields(expected, actual)
  316. }
  317. func compareEqualsUserFields(expected dataprovider.User, actual dataprovider.User) error {
  318. if expected.Username != actual.Username {
  319. return errors.New("Username mismatch")
  320. }
  321. if expected.HomeDir != actual.HomeDir {
  322. return errors.New("HomeDir mismatch")
  323. }
  324. if expected.UID != actual.UID {
  325. return errors.New("UID mismatch")
  326. }
  327. if expected.GID != actual.GID {
  328. return errors.New("GID mismatch")
  329. }
  330. if expected.MaxSessions != actual.MaxSessions {
  331. return errors.New("MaxSessions mismatch")
  332. }
  333. if expected.QuotaSize != actual.QuotaSize {
  334. return errors.New("QuotaSize mismatch")
  335. }
  336. if expected.QuotaFiles != actual.QuotaFiles {
  337. return errors.New("QuotaFiles mismatch")
  338. }
  339. if len(expected.Permissions) != len(actual.Permissions) {
  340. return errors.New("Permissions mismatch")
  341. }
  342. if expected.UploadBandwidth != actual.UploadBandwidth {
  343. return errors.New("UploadBandwidth mismatch")
  344. }
  345. if expected.DownloadBandwidth != actual.DownloadBandwidth {
  346. return errors.New("DownloadBandwidth mismatch")
  347. }
  348. if expected.Status != actual.Status {
  349. return errors.New("Status mismatch")
  350. }
  351. if expected.ExpirationDate != actual.ExpirationDate {
  352. return errors.New("ExpirationDate mismatch")
  353. }
  354. return nil
  355. }