api_utils.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. package httpd
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "path"
  14. "path/filepath"
  15. "strconv"
  16. "strings"
  17. "github.com/go-chi/render"
  18. "github.com/drakkan/sftpgo/common"
  19. "github.com/drakkan/sftpgo/dataprovider"
  20. "github.com/drakkan/sftpgo/httpclient"
  21. "github.com/drakkan/sftpgo/utils"
  22. "github.com/drakkan/sftpgo/version"
  23. "github.com/drakkan/sftpgo/vfs"
  24. )
  25. var (
  26. httpBaseURL = "http://127.0.0.1:8080"
  27. authUsername = ""
  28. authPassword = ""
  29. )
  30. // SetBaseURLAndCredentials sets the base url and the optional credentials to use for HTTP requests.
  31. // Default URL is "http://127.0.0.1:8080" with empty credentials
  32. func SetBaseURLAndCredentials(url, username, password string) {
  33. httpBaseURL = url
  34. authUsername = username
  35. authPassword = password
  36. }
  37. func sendHTTPRequest(method, url string, body io.Reader, contentType string) (*http.Response, error) {
  38. req, err := http.NewRequest(method, url, body)
  39. if err != nil {
  40. return nil, err
  41. }
  42. if len(contentType) > 0 {
  43. req.Header.Set("Content-Type", "application/json")
  44. }
  45. if len(authUsername) > 0 || len(authPassword) > 0 {
  46. req.SetBasicAuth(authUsername, authPassword)
  47. }
  48. return httpclient.GetHTTPClient().Do(req)
  49. }
  50. func buildURLRelativeToBase(paths ...string) string {
  51. // we need to use path.Join and not filepath.Join
  52. // since filepath.Join will use backslash separator on Windows
  53. p := path.Join(paths...)
  54. return fmt.Sprintf("%s/%s", strings.TrimRight(httpBaseURL, "/"), strings.TrimLeft(p, "/"))
  55. }
  56. func sendAPIResponse(w http.ResponseWriter, r *http.Request, err error, message string, code int) {
  57. var errorString string
  58. if err != nil {
  59. errorString = err.Error()
  60. }
  61. resp := apiResponse{
  62. Error: errorString,
  63. Message: message,
  64. HTTPStatus: code,
  65. }
  66. ctx := context.WithValue(r.Context(), render.StatusCtxKey, code)
  67. render.JSON(w, r.WithContext(ctx), resp)
  68. }
  69. func getRespStatus(err error) int {
  70. if _, ok := err.(*dataprovider.ValidationError); ok {
  71. return http.StatusBadRequest
  72. }
  73. if _, ok := err.(*dataprovider.MethodDisabledError); ok {
  74. return http.StatusForbidden
  75. }
  76. if _, ok := err.(*dataprovider.RecordNotFoundError); ok {
  77. return http.StatusNotFound
  78. }
  79. if os.IsNotExist(err) {
  80. return http.StatusBadRequest
  81. }
  82. return http.StatusInternalServerError
  83. }
  84. // AddUser adds a new user and checks the received HTTP Status code against expectedStatusCode.
  85. func AddUser(user dataprovider.User, expectedStatusCode int) (dataprovider.User, []byte, error) {
  86. var newUser dataprovider.User
  87. var body []byte
  88. userAsJSON, _ := json.Marshal(user)
  89. resp, err := sendHTTPRequest(http.MethodPost, buildURLRelativeToBase(userPath), bytes.NewBuffer(userAsJSON),
  90. "application/json")
  91. if err != nil {
  92. return newUser, body, err
  93. }
  94. defer resp.Body.Close()
  95. err = checkResponse(resp.StatusCode, expectedStatusCode)
  96. if expectedStatusCode != http.StatusOK {
  97. body, _ = getResponseBody(resp)
  98. return newUser, body, err
  99. }
  100. if err == nil {
  101. err = render.DecodeJSON(resp.Body, &newUser)
  102. } else {
  103. body, _ = getResponseBody(resp)
  104. }
  105. if err == nil {
  106. err = checkUser(&user, &newUser)
  107. }
  108. return newUser, body, err
  109. }
  110. // UpdateUser updates an existing user and checks the received HTTP Status code against expectedStatusCode.
  111. func UpdateUser(user dataprovider.User, expectedStatusCode int) (dataprovider.User, []byte, error) {
  112. var newUser dataprovider.User
  113. var body []byte
  114. userAsJSON, _ := json.Marshal(user)
  115. resp, err := sendHTTPRequest(http.MethodPut, buildURLRelativeToBase(userPath, strconv.FormatInt(user.ID, 10)),
  116. bytes.NewBuffer(userAsJSON), "application/json")
  117. if err != nil {
  118. return user, body, err
  119. }
  120. defer resp.Body.Close()
  121. body, _ = getResponseBody(resp)
  122. err = checkResponse(resp.StatusCode, expectedStatusCode)
  123. if expectedStatusCode != http.StatusOK {
  124. return newUser, body, err
  125. }
  126. if err == nil {
  127. newUser, body, err = GetUserByID(user.ID, expectedStatusCode)
  128. }
  129. if err == nil {
  130. err = checkUser(&user, &newUser)
  131. }
  132. return newUser, body, err
  133. }
  134. // RemoveUser removes an existing user and checks the received HTTP Status code against expectedStatusCode.
  135. func RemoveUser(user dataprovider.User, expectedStatusCode int) ([]byte, error) {
  136. var body []byte
  137. resp, err := sendHTTPRequest(http.MethodDelete, buildURLRelativeToBase(userPath, strconv.FormatInt(user.ID, 10)), nil, "")
  138. if err != nil {
  139. return body, err
  140. }
  141. defer resp.Body.Close()
  142. body, _ = getResponseBody(resp)
  143. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  144. }
  145. // GetUserByID gets a user by database id and checks the received HTTP Status code against expectedStatusCode.
  146. func GetUserByID(userID int64, expectedStatusCode int) (dataprovider.User, []byte, error) {
  147. var user dataprovider.User
  148. var body []byte
  149. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(userPath, strconv.FormatInt(userID, 10)), nil, "")
  150. if err != nil {
  151. return user, body, err
  152. }
  153. defer resp.Body.Close()
  154. err = checkResponse(resp.StatusCode, expectedStatusCode)
  155. if err == nil && expectedStatusCode == http.StatusOK {
  156. err = render.DecodeJSON(resp.Body, &user)
  157. } else {
  158. body, _ = getResponseBody(resp)
  159. }
  160. return user, body, err
  161. }
  162. // GetUsers returns a list of users and checks the received HTTP Status code against expectedStatusCode.
  163. // The number of results can be limited specifying a limit.
  164. // Some results can be skipped specifying an offset.
  165. // The results can be filtered specifying a username, the username filter is an exact match
  166. func GetUsers(limit, offset int64, username string, expectedStatusCode int) ([]dataprovider.User, []byte, error) {
  167. var users []dataprovider.User
  168. var body []byte
  169. url, err := addLimitAndOffsetQueryParams(buildURLRelativeToBase(userPath), limit, offset)
  170. if err != nil {
  171. return users, body, err
  172. }
  173. if len(username) > 0 {
  174. q := url.Query()
  175. q.Add("username", username)
  176. url.RawQuery = q.Encode()
  177. }
  178. resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "")
  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 for users and checks the received HTTP Status code against expectedStatusCode.
  192. func GetQuotaScans(expectedStatusCode int) ([]common.ActiveQuotaScan, []byte, error) {
  193. var quotaScans []common.ActiveQuotaScan
  194. var body []byte
  195. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(quotaScanPath), nil, "")
  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 starts 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, _ := json.Marshal(user)
  212. resp, err := sendHTTPRequest(http.MethodPost, buildURLRelativeToBase(quotaScanPath), bytes.NewBuffer(userAsJSON), "")
  213. if err != nil {
  214. return body, err
  215. }
  216. defer resp.Body.Close()
  217. body, _ = getResponseBody(resp)
  218. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  219. }
  220. // UpdateQuotaUsage updates the user used quota limits and checks the received HTTP Status code against expectedStatusCode.
  221. func UpdateQuotaUsage(user dataprovider.User, mode string, expectedStatusCode int) ([]byte, error) {
  222. var body []byte
  223. userAsJSON, _ := json.Marshal(user)
  224. url, err := addModeQueryParam(buildURLRelativeToBase(updateUsedQuotaPath), mode)
  225. if err != nil {
  226. return body, err
  227. }
  228. resp, err := sendHTTPRequest(http.MethodPut, url.String(), bytes.NewBuffer(userAsJSON), "")
  229. if err != nil {
  230. return body, err
  231. }
  232. defer resp.Body.Close()
  233. body, _ = getResponseBody(resp)
  234. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  235. }
  236. // GetConnections returns status and stats for active SFTP/SCP connections
  237. func GetConnections(expectedStatusCode int) ([]common.ConnectionStatus, []byte, error) {
  238. var connections []common.ConnectionStatus
  239. var body []byte
  240. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(activeConnectionsPath), nil, "")
  241. if err != nil {
  242. return connections, body, err
  243. }
  244. defer resp.Body.Close()
  245. err = checkResponse(resp.StatusCode, expectedStatusCode)
  246. if err == nil && expectedStatusCode == http.StatusOK {
  247. err = render.DecodeJSON(resp.Body, &connections)
  248. } else {
  249. body, _ = getResponseBody(resp)
  250. }
  251. return connections, body, err
  252. }
  253. // CloseConnection closes an active connection identified by connectionID
  254. func CloseConnection(connectionID string, expectedStatusCode int) ([]byte, error) {
  255. var body []byte
  256. resp, err := sendHTTPRequest(http.MethodDelete, buildURLRelativeToBase(activeConnectionsPath, connectionID), nil, "")
  257. if err != nil {
  258. return body, err
  259. }
  260. defer resp.Body.Close()
  261. err = checkResponse(resp.StatusCode, expectedStatusCode)
  262. body, _ = getResponseBody(resp)
  263. return body, err
  264. }
  265. // AddFolder adds a new folder and checks the received HTTP Status code against expectedStatusCode
  266. func AddFolder(folder vfs.BaseVirtualFolder, expectedStatusCode int) (vfs.BaseVirtualFolder, []byte, error) {
  267. var newFolder vfs.BaseVirtualFolder
  268. var body []byte
  269. folderAsJSON, _ := json.Marshal(folder)
  270. resp, err := sendHTTPRequest(http.MethodPost, buildURLRelativeToBase(folderPath), bytes.NewBuffer(folderAsJSON),
  271. "application/json")
  272. if err != nil {
  273. return newFolder, body, err
  274. }
  275. defer resp.Body.Close()
  276. err = checkResponse(resp.StatusCode, expectedStatusCode)
  277. if expectedStatusCode != http.StatusOK {
  278. body, _ = getResponseBody(resp)
  279. return newFolder, body, err
  280. }
  281. if err == nil {
  282. err = render.DecodeJSON(resp.Body, &newFolder)
  283. } else {
  284. body, _ = getResponseBody(resp)
  285. }
  286. if err == nil {
  287. err = checkFolder(&folder, &newFolder)
  288. }
  289. return newFolder, body, err
  290. }
  291. // RemoveFolder removes an existing user and checks the received HTTP Status code against expectedStatusCode.
  292. func RemoveFolder(folder vfs.BaseVirtualFolder, expectedStatusCode int) ([]byte, error) {
  293. var body []byte
  294. baseURL := buildURLRelativeToBase(folderPath)
  295. url, err := url.Parse(baseURL)
  296. if err != nil {
  297. return body, err
  298. }
  299. q := url.Query()
  300. q.Add("folder_path", folder.MappedPath)
  301. url.RawQuery = q.Encode()
  302. resp, err := sendHTTPRequest(http.MethodDelete, url.String(), nil, "")
  303. if err != nil {
  304. return body, err
  305. }
  306. defer resp.Body.Close()
  307. body, _ = getResponseBody(resp)
  308. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  309. }
  310. // GetFolders returns a list of folders and checks the received HTTP Status code against expectedStatusCode.
  311. // The number of results can be limited specifying a limit.
  312. // Some results can be skipped specifying an offset.
  313. // The results can be filtered specifying a folder path, the folder path filter is an exact match
  314. func GetFolders(limit int64, offset int64, mappedPath string, expectedStatusCode int) ([]vfs.BaseVirtualFolder, []byte, error) {
  315. var folders []vfs.BaseVirtualFolder
  316. var body []byte
  317. url, err := addLimitAndOffsetQueryParams(buildURLRelativeToBase(folderPath), limit, offset)
  318. if err != nil {
  319. return folders, body, err
  320. }
  321. if len(mappedPath) > 0 {
  322. q := url.Query()
  323. q.Add("folder_path", mappedPath)
  324. url.RawQuery = q.Encode()
  325. }
  326. resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "")
  327. if err != nil {
  328. return folders, body, err
  329. }
  330. defer resp.Body.Close()
  331. err = checkResponse(resp.StatusCode, expectedStatusCode)
  332. if err == nil && expectedStatusCode == http.StatusOK {
  333. err = render.DecodeJSON(resp.Body, &folders)
  334. } else {
  335. body, _ = getResponseBody(resp)
  336. }
  337. return folders, body, err
  338. }
  339. // GetFoldersQuotaScans gets active quota scans for folders and checks the received HTTP Status code against expectedStatusCode.
  340. func GetFoldersQuotaScans(expectedStatusCode int) ([]common.ActiveVirtualFolderQuotaScan, []byte, error) {
  341. var quotaScans []common.ActiveVirtualFolderQuotaScan
  342. var body []byte
  343. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(quotaScanVFolderPath), nil, "")
  344. if err != nil {
  345. return quotaScans, body, err
  346. }
  347. defer resp.Body.Close()
  348. err = checkResponse(resp.StatusCode, expectedStatusCode)
  349. if err == nil && expectedStatusCode == http.StatusOK {
  350. err = render.DecodeJSON(resp.Body, &quotaScans)
  351. } else {
  352. body, _ = getResponseBody(resp)
  353. }
  354. return quotaScans, body, err
  355. }
  356. // StartFolderQuotaScan start a new quota scan for the given folder and checks the received HTTP Status code against expectedStatusCode.
  357. func StartFolderQuotaScan(folder vfs.BaseVirtualFolder, expectedStatusCode int) ([]byte, error) {
  358. var body []byte
  359. folderAsJSON, _ := json.Marshal(folder)
  360. resp, err := sendHTTPRequest(http.MethodPost, buildURLRelativeToBase(quotaScanVFolderPath), bytes.NewBuffer(folderAsJSON), "")
  361. if err != nil {
  362. return body, err
  363. }
  364. defer resp.Body.Close()
  365. body, _ = getResponseBody(resp)
  366. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  367. }
  368. // UpdateFolderQuotaUsage updates the folder used quota limits and checks the received HTTP Status code against expectedStatusCode.
  369. func UpdateFolderQuotaUsage(folder vfs.BaseVirtualFolder, mode string, expectedStatusCode int) ([]byte, error) {
  370. var body []byte
  371. folderAsJSON, _ := json.Marshal(folder)
  372. url, err := addModeQueryParam(buildURLRelativeToBase(updateFolderUsedQuotaPath), mode)
  373. if err != nil {
  374. return body, err
  375. }
  376. resp, err := sendHTTPRequest(http.MethodPut, url.String(), bytes.NewBuffer(folderAsJSON), "")
  377. if err != nil {
  378. return body, err
  379. }
  380. defer resp.Body.Close()
  381. body, _ = getResponseBody(resp)
  382. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  383. }
  384. // GetVersion returns version details
  385. func GetVersion(expectedStatusCode int) (version.Info, []byte, error) {
  386. var appVersion version.Info
  387. var body []byte
  388. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(versionPath), nil, "")
  389. if err != nil {
  390. return appVersion, body, err
  391. }
  392. defer resp.Body.Close()
  393. err = checkResponse(resp.StatusCode, expectedStatusCode)
  394. if err == nil && expectedStatusCode == http.StatusOK {
  395. err = render.DecodeJSON(resp.Body, &appVersion)
  396. } else {
  397. body, _ = getResponseBody(resp)
  398. }
  399. return appVersion, body, err
  400. }
  401. // GetProviderStatus returns provider status
  402. func GetProviderStatus(expectedStatusCode int) (map[string]interface{}, []byte, error) {
  403. var response map[string]interface{}
  404. var body []byte
  405. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(providerStatusPath), nil, "")
  406. if err != nil {
  407. return response, body, err
  408. }
  409. defer resp.Body.Close()
  410. err = checkResponse(resp.StatusCode, expectedStatusCode)
  411. if err == nil && (expectedStatusCode == http.StatusOK || expectedStatusCode == http.StatusInternalServerError) {
  412. err = render.DecodeJSON(resp.Body, &response)
  413. } else {
  414. body, _ = getResponseBody(resp)
  415. }
  416. return response, body, err
  417. }
  418. // Dumpdata requests a backup to outputFile.
  419. // outputFile is relative to the configured backups_path
  420. func Dumpdata(outputFile, indent string, expectedStatusCode int) (map[string]interface{}, []byte, error) {
  421. var response map[string]interface{}
  422. var body []byte
  423. url, err := url.Parse(buildURLRelativeToBase(dumpDataPath))
  424. if err != nil {
  425. return response, body, err
  426. }
  427. q := url.Query()
  428. q.Add("output_file", outputFile)
  429. if len(indent) > 0 {
  430. q.Add("indent", indent)
  431. }
  432. url.RawQuery = q.Encode()
  433. resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "")
  434. if err != nil {
  435. return response, body, err
  436. }
  437. defer resp.Body.Close()
  438. err = checkResponse(resp.StatusCode, expectedStatusCode)
  439. if err == nil && expectedStatusCode == http.StatusOK {
  440. err = render.DecodeJSON(resp.Body, &response)
  441. } else {
  442. body, _ = getResponseBody(resp)
  443. }
  444. return response, body, err
  445. }
  446. // Loaddata restores a backup.
  447. // New users are added, existing users are updated. Users will be restored one by one and the restore is stopped if a
  448. // user cannot be added/updated, so it could happen a partial restore
  449. func Loaddata(inputFile, scanQuota, mode string, expectedStatusCode int) (map[string]interface{}, []byte, error) {
  450. var response map[string]interface{}
  451. var body []byte
  452. url, err := url.Parse(buildURLRelativeToBase(loadDataPath))
  453. if err != nil {
  454. return response, body, err
  455. }
  456. q := url.Query()
  457. q.Add("input_file", inputFile)
  458. if len(scanQuota) > 0 {
  459. q.Add("scan_quota", scanQuota)
  460. }
  461. if len(mode) > 0 {
  462. q.Add("mode", mode)
  463. }
  464. url.RawQuery = q.Encode()
  465. resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "")
  466. if err != nil {
  467. return response, body, err
  468. }
  469. defer resp.Body.Close()
  470. err = checkResponse(resp.StatusCode, expectedStatusCode)
  471. if err == nil && expectedStatusCode == http.StatusOK {
  472. err = render.DecodeJSON(resp.Body, &response)
  473. } else {
  474. body, _ = getResponseBody(resp)
  475. }
  476. return response, body, err
  477. }
  478. func checkResponse(actual int, expected int) error {
  479. if expected != actual {
  480. return fmt.Errorf("wrong status code: got %v want %v", actual, expected)
  481. }
  482. return nil
  483. }
  484. func getResponseBody(resp *http.Response) ([]byte, error) {
  485. return ioutil.ReadAll(resp.Body)
  486. }
  487. func checkFolder(expected *vfs.BaseVirtualFolder, actual *vfs.BaseVirtualFolder) error {
  488. if expected.ID <= 0 {
  489. if actual.ID <= 0 {
  490. return errors.New("actual folder ID must be > 0")
  491. }
  492. } else {
  493. if actual.ID != expected.ID {
  494. return errors.New("folder ID mismatch")
  495. }
  496. }
  497. if expected.MappedPath != actual.MappedPath {
  498. return errors.New("mapped path mismatch")
  499. }
  500. if expected.LastQuotaUpdate != actual.LastQuotaUpdate {
  501. return errors.New("last quota update mismatch")
  502. }
  503. if expected.UsedQuotaSize != actual.UsedQuotaSize {
  504. return errors.New("used quota size mismatch")
  505. }
  506. if expected.UsedQuotaFiles != actual.UsedQuotaFiles {
  507. return errors.New("used quota files mismatch")
  508. }
  509. if len(expected.Users) != len(actual.Users) {
  510. return errors.New("folder users mismatch")
  511. }
  512. for _, u := range actual.Users {
  513. if !utils.IsStringInSlice(u, expected.Users) {
  514. return errors.New("folder users mismatch")
  515. }
  516. }
  517. return nil
  518. }
  519. func checkUser(expected *dataprovider.User, actual *dataprovider.User) error {
  520. if len(actual.Password) > 0 {
  521. return errors.New("User password must not be visible")
  522. }
  523. if expected.ID <= 0 {
  524. if actual.ID <= 0 {
  525. return errors.New("actual user ID must be > 0")
  526. }
  527. } else {
  528. if actual.ID != expected.ID {
  529. return errors.New("user ID mismatch")
  530. }
  531. }
  532. if len(expected.Permissions) != len(actual.Permissions) {
  533. return errors.New("Permissions mismatch")
  534. }
  535. for dir, perms := range expected.Permissions {
  536. if actualPerms, ok := actual.Permissions[dir]; ok {
  537. for _, v := range actualPerms {
  538. if !utils.IsStringInSlice(v, perms) {
  539. return errors.New("Permissions contents mismatch")
  540. }
  541. }
  542. } else {
  543. return errors.New("Permissions directories mismatch")
  544. }
  545. }
  546. if err := compareUserFilters(expected, actual); err != nil {
  547. return err
  548. }
  549. if err := compareUserFsConfig(expected, actual); err != nil {
  550. return err
  551. }
  552. if err := compareUserVirtualFolders(expected, actual); err != nil {
  553. return err
  554. }
  555. return compareEqualsUserFields(expected, actual)
  556. }
  557. func compareUserVirtualFolders(expected *dataprovider.User, actual *dataprovider.User) error {
  558. if len(actual.VirtualFolders) != len(expected.VirtualFolders) {
  559. return errors.New("Virtual folders mismatch")
  560. }
  561. for _, v := range actual.VirtualFolders {
  562. found := false
  563. for _, v1 := range expected.VirtualFolders {
  564. if path.Clean(v.VirtualPath) == path.Clean(v1.VirtualPath) &&
  565. filepath.Clean(v.MappedPath) == filepath.Clean(v1.MappedPath) {
  566. found = true
  567. break
  568. }
  569. }
  570. if !found {
  571. return errors.New("Virtual folders mismatch")
  572. }
  573. }
  574. return nil
  575. }
  576. func compareUserFsConfig(expected *dataprovider.User, actual *dataprovider.User) error {
  577. if expected.FsConfig.Provider != actual.FsConfig.Provider {
  578. return errors.New("Fs provider mismatch")
  579. }
  580. if err := compareS3Config(expected, actual); err != nil {
  581. return err
  582. }
  583. if err := compareGCSConfig(expected, actual); err != nil {
  584. return err
  585. }
  586. return nil
  587. }
  588. func compareS3Config(expected *dataprovider.User, actual *dataprovider.User) error {
  589. if expected.FsConfig.S3Config.Bucket != actual.FsConfig.S3Config.Bucket {
  590. return errors.New("S3 bucket mismatch")
  591. }
  592. if expected.FsConfig.S3Config.Region != actual.FsConfig.S3Config.Region {
  593. return errors.New("S3 region mismatch")
  594. }
  595. if expected.FsConfig.S3Config.AccessKey != actual.FsConfig.S3Config.AccessKey {
  596. return errors.New("S3 access key mismatch")
  597. }
  598. if err := checkS3AccessSecret(expected.FsConfig.S3Config.AccessSecret, actual.FsConfig.S3Config.AccessSecret); err != nil {
  599. return err
  600. }
  601. if expected.FsConfig.S3Config.Endpoint != actual.FsConfig.S3Config.Endpoint {
  602. return errors.New("S3 endpoint mismatch")
  603. }
  604. if expected.FsConfig.S3Config.StorageClass != actual.FsConfig.S3Config.StorageClass {
  605. return errors.New("S3 storage class mismatch")
  606. }
  607. if expected.FsConfig.S3Config.UploadPartSize != actual.FsConfig.S3Config.UploadPartSize {
  608. return errors.New("S3 upload part size mismatch")
  609. }
  610. if expected.FsConfig.S3Config.UploadConcurrency != actual.FsConfig.S3Config.UploadConcurrency {
  611. return errors.New("S3 upload concurrency mismatch")
  612. }
  613. if expected.FsConfig.S3Config.KeyPrefix != actual.FsConfig.S3Config.KeyPrefix &&
  614. expected.FsConfig.S3Config.KeyPrefix+"/" != actual.FsConfig.S3Config.KeyPrefix {
  615. return errors.New("S3 key prefix mismatch")
  616. }
  617. return nil
  618. }
  619. func compareGCSConfig(expected *dataprovider.User, actual *dataprovider.User) error {
  620. if expected.FsConfig.GCSConfig.Bucket != actual.FsConfig.GCSConfig.Bucket {
  621. return errors.New("GCS bucket mismatch")
  622. }
  623. if expected.FsConfig.GCSConfig.StorageClass != actual.FsConfig.GCSConfig.StorageClass {
  624. return errors.New("GCS storage class mismatch")
  625. }
  626. if expected.FsConfig.GCSConfig.KeyPrefix != actual.FsConfig.GCSConfig.KeyPrefix &&
  627. expected.FsConfig.GCSConfig.KeyPrefix+"/" != actual.FsConfig.GCSConfig.KeyPrefix {
  628. return errors.New("GCS key prefix mismatch")
  629. }
  630. if expected.FsConfig.GCSConfig.AutomaticCredentials != actual.FsConfig.GCSConfig.AutomaticCredentials {
  631. return errors.New("GCS automatic credentials mismatch")
  632. }
  633. return nil
  634. }
  635. func checkS3AccessSecret(expectedAccessSecret, actualAccessSecret string) error {
  636. if len(expectedAccessSecret) > 0 {
  637. vals := strings.Split(expectedAccessSecret, "$")
  638. if strings.HasPrefix(expectedAccessSecret, "$aes$") && len(vals) == 4 {
  639. expectedAccessSecret = utils.RemoveDecryptionKey(expectedAccessSecret)
  640. if expectedAccessSecret != actualAccessSecret {
  641. return fmt.Errorf("S3 access secret mismatch, expected: %v", expectedAccessSecret)
  642. }
  643. } else {
  644. // here we check that actualAccessSecret is aes encrypted without the nonce
  645. parts := strings.Split(actualAccessSecret, "$")
  646. if !strings.HasPrefix(actualAccessSecret, "$aes$") || len(parts) != 3 {
  647. return errors.New("Invalid S3 access secret")
  648. }
  649. if len(parts) == len(vals) {
  650. if expectedAccessSecret != actualAccessSecret {
  651. return errors.New("S3 encrypted access secret mismatch")
  652. }
  653. }
  654. }
  655. } else {
  656. if expectedAccessSecret != actualAccessSecret {
  657. return errors.New("S3 access secret mismatch")
  658. }
  659. }
  660. return nil
  661. }
  662. func compareUserFilters(expected *dataprovider.User, actual *dataprovider.User) error {
  663. if len(expected.Filters.AllowedIP) != len(actual.Filters.AllowedIP) {
  664. return errors.New("AllowedIP mismatch")
  665. }
  666. if len(expected.Filters.DeniedIP) != len(actual.Filters.DeniedIP) {
  667. return errors.New("DeniedIP mismatch")
  668. }
  669. if len(expected.Filters.DeniedLoginMethods) != len(actual.Filters.DeniedLoginMethods) {
  670. return errors.New("Denied login methods mismatch")
  671. }
  672. for _, IPMask := range expected.Filters.AllowedIP {
  673. if !utils.IsStringInSlice(IPMask, actual.Filters.AllowedIP) {
  674. return errors.New("AllowedIP contents mismatch")
  675. }
  676. }
  677. for _, IPMask := range expected.Filters.DeniedIP {
  678. if !utils.IsStringInSlice(IPMask, actual.Filters.DeniedIP) {
  679. return errors.New("DeniedIP contents mismatch")
  680. }
  681. }
  682. for _, method := range expected.Filters.DeniedLoginMethods {
  683. if !utils.IsStringInSlice(method, actual.Filters.DeniedLoginMethods) {
  684. return errors.New("Denied login methods contents mismatch")
  685. }
  686. }
  687. if err := compareUserFileExtensionsFilters(expected, actual); err != nil {
  688. return err
  689. }
  690. return nil
  691. }
  692. func compareUserFileExtensionsFilters(expected *dataprovider.User, actual *dataprovider.User) error {
  693. if len(expected.Filters.FileExtensions) != len(actual.Filters.FileExtensions) {
  694. return errors.New("file extensions mismatch")
  695. }
  696. for _, f := range expected.Filters.FileExtensions {
  697. found := false
  698. for _, f1 := range actual.Filters.FileExtensions {
  699. if path.Clean(f.Path) == path.Clean(f1.Path) {
  700. if len(f.AllowedExtensions) != len(f1.AllowedExtensions) || len(f.DeniedExtensions) != len(f1.DeniedExtensions) {
  701. return errors.New("file extensions contents mismatch")
  702. }
  703. for _, e := range f.AllowedExtensions {
  704. if !utils.IsStringInSlice(e, f1.AllowedExtensions) {
  705. return errors.New("file extensions contents mismatch")
  706. }
  707. }
  708. for _, e := range f.DeniedExtensions {
  709. if !utils.IsStringInSlice(e, f1.DeniedExtensions) {
  710. return errors.New("file extensions contents mismatch")
  711. }
  712. }
  713. found = true
  714. }
  715. }
  716. if !found {
  717. return errors.New("file extensions contents mismatch")
  718. }
  719. }
  720. return nil
  721. }
  722. func compareEqualsUserFields(expected *dataprovider.User, actual *dataprovider.User) error {
  723. if expected.Username != actual.Username {
  724. return errors.New("Username mismatch")
  725. }
  726. if expected.HomeDir != actual.HomeDir {
  727. return errors.New("HomeDir mismatch")
  728. }
  729. if expected.UID != actual.UID {
  730. return errors.New("UID mismatch")
  731. }
  732. if expected.GID != actual.GID {
  733. return errors.New("GID mismatch")
  734. }
  735. if expected.MaxSessions != actual.MaxSessions {
  736. return errors.New("MaxSessions mismatch")
  737. }
  738. if expected.QuotaSize != actual.QuotaSize {
  739. return errors.New("QuotaSize mismatch")
  740. }
  741. if expected.QuotaFiles != actual.QuotaFiles {
  742. return errors.New("QuotaFiles mismatch")
  743. }
  744. if len(expected.Permissions) != len(actual.Permissions) {
  745. return errors.New("Permissions mismatch")
  746. }
  747. if expected.UploadBandwidth != actual.UploadBandwidth {
  748. return errors.New("UploadBandwidth mismatch")
  749. }
  750. if expected.DownloadBandwidth != actual.DownloadBandwidth {
  751. return errors.New("DownloadBandwidth mismatch")
  752. }
  753. if expected.Status != actual.Status {
  754. return errors.New("Status mismatch")
  755. }
  756. if expected.ExpirationDate != actual.ExpirationDate {
  757. return errors.New("ExpirationDate mismatch")
  758. }
  759. return nil
  760. }
  761. func addLimitAndOffsetQueryParams(rawurl string, limit, offset int64) (*url.URL, error) {
  762. url, err := url.Parse(rawurl)
  763. if err != nil {
  764. return nil, err
  765. }
  766. q := url.Query()
  767. if limit > 0 {
  768. q.Add("limit", strconv.FormatInt(limit, 10))
  769. }
  770. if offset > 0 {
  771. q.Add("offset", strconv.FormatInt(offset, 10))
  772. }
  773. url.RawQuery = q.Encode()
  774. return url, err
  775. }
  776. func addModeQueryParam(rawurl, mode string) (*url.URL, error) {
  777. url, err := url.Parse(rawurl)
  778. if err != nil {
  779. return nil, err
  780. }
  781. q := url.Query()
  782. if len(mode) > 0 {
  783. q.Add("mode", mode)
  784. }
  785. url.RawQuery = q.Encode()
  786. return url, err
  787. }