api_utils.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. package httpd
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "path"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/drakkan/sftpgo/dataprovider"
  17. "github.com/drakkan/sftpgo/sftpd"
  18. "github.com/drakkan/sftpgo/utils"
  19. "github.com/go-chi/render"
  20. )
  21. var (
  22. httpBaseURL = "http://127.0.0.1:8080"
  23. )
  24. // SetBaseURL sets the base url to use for HTTP requests, default is "http://127.0.0.1:8080"
  25. func SetBaseURL(url string) {
  26. httpBaseURL = url
  27. }
  28. // gets an HTTP Client with a timeout
  29. func getHTTPClient() *http.Client {
  30. return &http.Client{
  31. Timeout: 15 * time.Second,
  32. }
  33. }
  34. func buildURLRelativeToBase(paths ...string) string {
  35. // we need to use path.Join and not filepath.Join
  36. // since filepath.Join will use backslash separator on Windows
  37. p := path.Join(paths...)
  38. return fmt.Sprintf("%s/%s", strings.TrimRight(httpBaseURL, "/"), strings.TrimLeft(p, "/"))
  39. }
  40. func sendAPIResponse(w http.ResponseWriter, r *http.Request, err error, message string, code int) {
  41. var errorString string
  42. if err != nil {
  43. errorString = err.Error()
  44. }
  45. resp := apiResponse{
  46. Error: errorString,
  47. Message: message,
  48. HTTPStatus: code,
  49. }
  50. ctx := context.WithValue(r.Context(), render.StatusCtxKey, code)
  51. render.JSON(w, r.WithContext(ctx), resp)
  52. }
  53. func getRespStatus(err error) int {
  54. if _, ok := err.(*dataprovider.ValidationError); ok {
  55. return http.StatusBadRequest
  56. }
  57. if _, ok := err.(*dataprovider.MethodDisabledError); ok {
  58. return http.StatusForbidden
  59. }
  60. if os.IsNotExist(err) {
  61. return http.StatusBadRequest
  62. }
  63. return http.StatusInternalServerError
  64. }
  65. // AddUser adds a new user and checks the received HTTP Status code against expectedStatusCode.
  66. func AddUser(user dataprovider.User, expectedStatusCode int) (dataprovider.User, []byte, error) {
  67. var newUser dataprovider.User
  68. var body []byte
  69. userAsJSON, err := json.Marshal(user)
  70. if err != nil {
  71. return newUser, body, err
  72. }
  73. resp, err := getHTTPClient().Post(buildURLRelativeToBase(userPath), "application/json", bytes.NewBuffer(userAsJSON))
  74. if err != nil {
  75. return newUser, body, err
  76. }
  77. defer resp.Body.Close()
  78. err = checkResponse(resp.StatusCode, expectedStatusCode)
  79. if expectedStatusCode != http.StatusOK {
  80. body, _ = getResponseBody(resp)
  81. return newUser, body, err
  82. }
  83. if err == nil {
  84. err = render.DecodeJSON(resp.Body, &newUser)
  85. } else {
  86. body, _ = getResponseBody(resp)
  87. }
  88. if err == nil {
  89. err = checkUser(&user, &newUser)
  90. }
  91. return newUser, body, err
  92. }
  93. // UpdateUser updates an existing user and checks the received HTTP Status code against expectedStatusCode.
  94. func UpdateUser(user dataprovider.User, expectedStatusCode int) (dataprovider.User, []byte, error) {
  95. var newUser dataprovider.User
  96. var body []byte
  97. userAsJSON, err := json.Marshal(user)
  98. if err != nil {
  99. return user, body, err
  100. }
  101. req, err := http.NewRequest(http.MethodPut, buildURLRelativeToBase(userPath, strconv.FormatInt(user.ID, 10)),
  102. bytes.NewBuffer(userAsJSON))
  103. if err != nil {
  104. return user, body, err
  105. }
  106. resp, err := getHTTPClient().Do(req)
  107. if err != nil {
  108. return user, body, err
  109. }
  110. defer resp.Body.Close()
  111. body, _ = getResponseBody(resp)
  112. err = checkResponse(resp.StatusCode, expectedStatusCode)
  113. if expectedStatusCode != http.StatusOK {
  114. return newUser, body, err
  115. }
  116. if err == nil {
  117. newUser, body, err = GetUserByID(user.ID, expectedStatusCode)
  118. }
  119. if err == nil {
  120. err = checkUser(&user, &newUser)
  121. }
  122. return newUser, body, err
  123. }
  124. // RemoveUser removes an existing user and checks the received HTTP Status code against expectedStatusCode.
  125. func RemoveUser(user dataprovider.User, expectedStatusCode int) ([]byte, error) {
  126. var body []byte
  127. req, err := http.NewRequest(http.MethodDelete, buildURLRelativeToBase(userPath, strconv.FormatInt(user.ID, 10)), nil)
  128. if err != nil {
  129. return body, err
  130. }
  131. resp, err := getHTTPClient().Do(req)
  132. if err != nil {
  133. return body, err
  134. }
  135. defer resp.Body.Close()
  136. body, _ = getResponseBody(resp)
  137. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  138. }
  139. // GetUserByID gets an user by database id and checks the received HTTP Status code against expectedStatusCode.
  140. func GetUserByID(userID int64, expectedStatusCode int) (dataprovider.User, []byte, error) {
  141. var user dataprovider.User
  142. var body []byte
  143. resp, err := getHTTPClient().Get(buildURLRelativeToBase(userPath, strconv.FormatInt(userID, 10)))
  144. if err != nil {
  145. return user, body, err
  146. }
  147. defer resp.Body.Close()
  148. err = checkResponse(resp.StatusCode, expectedStatusCode)
  149. if err == nil && expectedStatusCode == http.StatusOK {
  150. err = render.DecodeJSON(resp.Body, &user)
  151. } else {
  152. body, _ = getResponseBody(resp)
  153. }
  154. return user, body, err
  155. }
  156. // GetUsers allows to get a list of users and checks the received HTTP Status code against expectedStatusCode.
  157. // The number of results can be limited specifying a limit.
  158. // Some results can be skipped specifying an offset.
  159. // The results can be filtered specifying an username, the username filter is an exact match
  160. func GetUsers(limit int64, offset int64, username string, expectedStatusCode int) ([]dataprovider.User, []byte, error) {
  161. var users []dataprovider.User
  162. var body []byte
  163. url, err := url.Parse(buildURLRelativeToBase(userPath))
  164. if err != nil {
  165. return users, body, err
  166. }
  167. q := url.Query()
  168. if limit > 0 {
  169. q.Add("limit", strconv.FormatInt(limit, 10))
  170. }
  171. if offset > 0 {
  172. q.Add("offset", strconv.FormatInt(offset, 10))
  173. }
  174. if len(username) > 0 {
  175. q.Add("username", username)
  176. }
  177. url.RawQuery = q.Encode()
  178. resp, err := getHTTPClient().Get(url.String())
  179. if err != nil {
  180. return users, body, err
  181. }
  182. defer resp.Body.Close()
  183. err = checkResponse(resp.StatusCode, expectedStatusCode)
  184. if err == nil && expectedStatusCode == http.StatusOK {
  185. err = render.DecodeJSON(resp.Body, &users)
  186. } else {
  187. body, _ = getResponseBody(resp)
  188. }
  189. return users, body, err
  190. }
  191. // GetQuotaScans gets active quota scans and checks the received HTTP Status code against expectedStatusCode.
  192. func GetQuotaScans(expectedStatusCode int) ([]sftpd.ActiveQuotaScan, []byte, error) {
  193. var quotaScans []sftpd.ActiveQuotaScan
  194. var body []byte
  195. resp, err := getHTTPClient().Get(buildURLRelativeToBase(quotaScanPath))
  196. if err != nil {
  197. return quotaScans, body, err
  198. }
  199. defer resp.Body.Close()
  200. err = checkResponse(resp.StatusCode, expectedStatusCode)
  201. if err == nil && expectedStatusCode == http.StatusOK {
  202. err = render.DecodeJSON(resp.Body, &quotaScans)
  203. } else {
  204. body, _ = getResponseBody(resp)
  205. }
  206. return quotaScans, body, err
  207. }
  208. // StartQuotaScan start a new quota scan for the given user and checks the received HTTP Status code against expectedStatusCode.
  209. func StartQuotaScan(user dataprovider.User, expectedStatusCode int) ([]byte, error) {
  210. var body []byte
  211. userAsJSON, err := json.Marshal(user)
  212. if err != nil {
  213. return body, err
  214. }
  215. resp, err := getHTTPClient().Post(buildURLRelativeToBase(quotaScanPath), "application/json", bytes.NewBuffer(userAsJSON))
  216. if err != nil {
  217. return body, err
  218. }
  219. defer resp.Body.Close()
  220. body, _ = getResponseBody(resp)
  221. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  222. }
  223. // GetConnections returns status and stats for active SFTP/SCP connections
  224. func GetConnections(expectedStatusCode int) ([]sftpd.ConnectionStatus, []byte, error) {
  225. var connections []sftpd.ConnectionStatus
  226. var body []byte
  227. resp, err := getHTTPClient().Get(buildURLRelativeToBase(activeConnectionsPath))
  228. if err != nil {
  229. return connections, body, err
  230. }
  231. defer resp.Body.Close()
  232. err = checkResponse(resp.StatusCode, expectedStatusCode)
  233. if err == nil && expectedStatusCode == http.StatusOK {
  234. err = render.DecodeJSON(resp.Body, &connections)
  235. } else {
  236. body, _ = getResponseBody(resp)
  237. }
  238. return connections, body, err
  239. }
  240. // CloseConnection closes an active connection identified by connectionID
  241. func CloseConnection(connectionID string, expectedStatusCode int) ([]byte, error) {
  242. var body []byte
  243. req, err := http.NewRequest(http.MethodDelete, buildURLRelativeToBase(activeConnectionsPath, connectionID), nil)
  244. if err != nil {
  245. return body, err
  246. }
  247. resp, err := getHTTPClient().Do(req)
  248. if err != nil {
  249. return body, err
  250. }
  251. defer resp.Body.Close()
  252. err = checkResponse(resp.StatusCode, expectedStatusCode)
  253. body, _ = getResponseBody(resp)
  254. return body, err
  255. }
  256. // GetVersion returns version details
  257. func GetVersion(expectedStatusCode int) (utils.VersionInfo, []byte, error) {
  258. var version utils.VersionInfo
  259. var body []byte
  260. resp, err := getHTTPClient().Get(buildURLRelativeToBase(versionPath))
  261. if err != nil {
  262. return version, body, err
  263. }
  264. defer resp.Body.Close()
  265. err = checkResponse(resp.StatusCode, expectedStatusCode)
  266. if err == nil && expectedStatusCode == http.StatusOK {
  267. err = render.DecodeJSON(resp.Body, &version)
  268. } else {
  269. body, _ = getResponseBody(resp)
  270. }
  271. return version, body, err
  272. }
  273. // GetProviderStatus returns provider status
  274. func GetProviderStatus(expectedStatusCode int) (map[string]interface{}, []byte, error) {
  275. var response map[string]interface{}
  276. var body []byte
  277. resp, err := getHTTPClient().Get(buildURLRelativeToBase(providerStatusPath))
  278. if err != nil {
  279. return response, body, err
  280. }
  281. defer resp.Body.Close()
  282. err = checkResponse(resp.StatusCode, expectedStatusCode)
  283. if err == nil && (expectedStatusCode == http.StatusOK || expectedStatusCode == http.StatusInternalServerError) {
  284. err = render.DecodeJSON(resp.Body, &response)
  285. } else {
  286. body, _ = getResponseBody(resp)
  287. }
  288. return response, body, err
  289. }
  290. // Dumpdata requests a backup to outputFile.
  291. // outputFile is relative to the configured backups_path
  292. func Dumpdata(outputFile string, expectedStatusCode int) (map[string]interface{}, []byte, error) {
  293. var response map[string]interface{}
  294. var body []byte
  295. url, err := url.Parse(buildURLRelativeToBase(dumpDataPath))
  296. if err != nil {
  297. return response, body, err
  298. }
  299. q := url.Query()
  300. q.Add("output_file", outputFile)
  301. url.RawQuery = q.Encode()
  302. resp, err := getHTTPClient().Get(url.String())
  303. if err != nil {
  304. return response, body, err
  305. }
  306. defer resp.Body.Close()
  307. err = checkResponse(resp.StatusCode, expectedStatusCode)
  308. if err == nil && expectedStatusCode == http.StatusOK {
  309. err = render.DecodeJSON(resp.Body, &response)
  310. } else {
  311. body, _ = getResponseBody(resp)
  312. }
  313. return response, body, err
  314. }
  315. // Loaddata restores a backup.
  316. // New users are added, existing users are updated. Users will be restored one by one and the restore is stopped if a
  317. // user cannot be added/updated, so it could happen a partial restore
  318. func Loaddata(inputFile, scanQuota, mode string, expectedStatusCode int) (map[string]interface{}, []byte, error) {
  319. var response map[string]interface{}
  320. var body []byte
  321. url, err := url.Parse(buildURLRelativeToBase(loadDataPath))
  322. if err != nil {
  323. return response, body, err
  324. }
  325. q := url.Query()
  326. q.Add("input_file", inputFile)
  327. if len(scanQuota) > 0 {
  328. q.Add("scan_quota", scanQuota)
  329. }
  330. if len(mode) > 0 {
  331. q.Add("mode", mode)
  332. }
  333. url.RawQuery = q.Encode()
  334. resp, err := getHTTPClient().Get(url.String())
  335. if err != nil {
  336. return response, body, err
  337. }
  338. defer resp.Body.Close()
  339. err = checkResponse(resp.StatusCode, expectedStatusCode)
  340. if err == nil && expectedStatusCode == http.StatusOK {
  341. err = render.DecodeJSON(resp.Body, &response)
  342. } else {
  343. body, _ = getResponseBody(resp)
  344. }
  345. return response, body, err
  346. }
  347. func checkResponse(actual int, expected int) error {
  348. if expected != actual {
  349. return fmt.Errorf("wrong status code: got %v want %v", actual, expected)
  350. }
  351. return nil
  352. }
  353. func getResponseBody(resp *http.Response) ([]byte, error) {
  354. return ioutil.ReadAll(resp.Body)
  355. }
  356. func checkUser(expected *dataprovider.User, actual *dataprovider.User) error {
  357. if len(actual.Password) > 0 {
  358. return errors.New("User password must not be visible")
  359. }
  360. if expected.ID <= 0 {
  361. if actual.ID <= 0 {
  362. return errors.New("actual user ID must be > 0")
  363. }
  364. } else {
  365. if actual.ID != expected.ID {
  366. return errors.New("user ID mismatch")
  367. }
  368. }
  369. if len(expected.Permissions) != len(actual.Permissions) {
  370. return errors.New("Permissions mismatch")
  371. }
  372. for dir, perms := range expected.Permissions {
  373. if actualPerms, ok := actual.Permissions[dir]; ok {
  374. for _, v := range actualPerms {
  375. if !utils.IsStringInSlice(v, perms) {
  376. return errors.New("Permissions contents mismatch")
  377. }
  378. }
  379. } else {
  380. return errors.New("Permissions directories mismatch")
  381. }
  382. }
  383. if err := compareUserFilters(expected, actual); err != nil {
  384. return err
  385. }
  386. if err := compareUserFsConfig(expected, actual); err != nil {
  387. return err
  388. }
  389. return compareEqualsUserFields(expected, actual)
  390. }
  391. func compareUserFsConfig(expected *dataprovider.User, actual *dataprovider.User) error {
  392. if expected.FsConfig.Provider != actual.FsConfig.Provider {
  393. return errors.New("Fs provider mismatch")
  394. }
  395. if expected.FsConfig.S3Config.Bucket != actual.FsConfig.S3Config.Bucket {
  396. return errors.New("S3 bucket mismatch")
  397. }
  398. if expected.FsConfig.S3Config.Region != actual.FsConfig.S3Config.Region {
  399. return errors.New("S3 region mismatch")
  400. }
  401. if expected.FsConfig.S3Config.AccessKey != actual.FsConfig.S3Config.AccessKey {
  402. return errors.New("S3 access key mismatch")
  403. }
  404. if err := checkS3AccessSecret(expected.FsConfig.S3Config.AccessSecret, actual.FsConfig.S3Config.AccessSecret); err != nil {
  405. return err
  406. }
  407. if expected.FsConfig.S3Config.Endpoint != actual.FsConfig.S3Config.Endpoint {
  408. return errors.New("S3 endpoint mismatch")
  409. }
  410. if expected.FsConfig.S3Config.StorageClass != actual.FsConfig.S3Config.StorageClass {
  411. return errors.New("S3 storage class mismatch")
  412. }
  413. if expected.FsConfig.S3Config.KeyPrefix != actual.FsConfig.S3Config.KeyPrefix &&
  414. expected.FsConfig.S3Config.KeyPrefix+"/" != actual.FsConfig.S3Config.KeyPrefix {
  415. return errors.New("S3 key prefix mismatch")
  416. }
  417. if expected.FsConfig.GCSConfig.Bucket != actual.FsConfig.GCSConfig.Bucket {
  418. return errors.New("GCS bucket mismatch")
  419. }
  420. if expected.FsConfig.GCSConfig.StorageClass != actual.FsConfig.GCSConfig.StorageClass {
  421. return errors.New("GCS storage class mismatch")
  422. }
  423. if expected.FsConfig.GCSConfig.KeyPrefix != actual.FsConfig.GCSConfig.KeyPrefix &&
  424. expected.FsConfig.GCSConfig.KeyPrefix+"/" != actual.FsConfig.GCSConfig.KeyPrefix {
  425. return errors.New("GCS key prefix mismatch")
  426. }
  427. return nil
  428. }
  429. func checkS3AccessSecret(expectedAccessSecret, actualAccessSecret string) error {
  430. if len(expectedAccessSecret) > 0 {
  431. vals := strings.Split(expectedAccessSecret, "$")
  432. if strings.HasPrefix(expectedAccessSecret, "$aes$") && len(vals) == 4 {
  433. expectedAccessSecret = utils.RemoveDecryptionKey(expectedAccessSecret)
  434. if expectedAccessSecret != actualAccessSecret {
  435. return fmt.Errorf("S3 access secret mismatch, expected: %v", expectedAccessSecret)
  436. }
  437. } else {
  438. // here we check that actualAccessSecret is aes encrypted without the nonce
  439. parts := strings.Split(actualAccessSecret, "$")
  440. if !strings.HasPrefix(actualAccessSecret, "$aes$") || len(parts) != 3 {
  441. return errors.New("Invalid S3 access secret")
  442. }
  443. if len(parts) == len(vals) {
  444. if expectedAccessSecret != actualAccessSecret {
  445. return errors.New("S3 encrypted access secret mismatch")
  446. }
  447. }
  448. }
  449. } else {
  450. if expectedAccessSecret != actualAccessSecret {
  451. return errors.New("S3 access secret mismatch")
  452. }
  453. }
  454. return nil
  455. }
  456. func compareUserFilters(expected *dataprovider.User, actual *dataprovider.User) error {
  457. if len(expected.Filters.AllowedIP) != len(actual.Filters.AllowedIP) {
  458. return errors.New("AllowedIP mismatch")
  459. }
  460. if len(expected.Filters.DeniedIP) != len(actual.Filters.DeniedIP) {
  461. return errors.New("DeniedIP mismatch")
  462. }
  463. for _, IPMask := range expected.Filters.AllowedIP {
  464. if !utils.IsStringInSlice(IPMask, actual.Filters.AllowedIP) {
  465. return errors.New("AllowedIP contents mismatch")
  466. }
  467. }
  468. for _, IPMask := range expected.Filters.DeniedIP {
  469. if !utils.IsStringInSlice(IPMask, actual.Filters.DeniedIP) {
  470. return errors.New("DeniedIP contents mismatch")
  471. }
  472. }
  473. return nil
  474. }
  475. func compareEqualsUserFields(expected *dataprovider.User, actual *dataprovider.User) error {
  476. if expected.Username != actual.Username {
  477. return errors.New("Username mismatch")
  478. }
  479. if expected.HomeDir != actual.HomeDir {
  480. return errors.New("HomeDir mismatch")
  481. }
  482. if expected.UID != actual.UID {
  483. return errors.New("UID mismatch")
  484. }
  485. if expected.GID != actual.GID {
  486. return errors.New("GID mismatch")
  487. }
  488. if expected.MaxSessions != actual.MaxSessions {
  489. return errors.New("MaxSessions mismatch")
  490. }
  491. if expected.QuotaSize != actual.QuotaSize {
  492. return errors.New("QuotaSize mismatch")
  493. }
  494. if expected.QuotaFiles != actual.QuotaFiles {
  495. return errors.New("QuotaFiles mismatch")
  496. }
  497. if len(expected.Permissions) != len(actual.Permissions) {
  498. return errors.New("Permissions mismatch")
  499. }
  500. if expected.UploadBandwidth != actual.UploadBandwidth {
  501. return errors.New("UploadBandwidth mismatch")
  502. }
  503. if expected.DownloadBandwidth != actual.DownloadBandwidth {
  504. return errors.New("DownloadBandwidth mismatch")
  505. }
  506. if expected.Status != actual.Status {
  507. return errors.New("Status mismatch")
  508. }
  509. if expected.ExpirationDate != actual.ExpirationDate {
  510. return errors.New("ExpirationDate mismatch")
  511. }
  512. return nil
  513. }