api_utils.go 25 KB

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