api_utils.go 28 KB

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