httpdtest.go 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381
  1. // Copyright (C) 2019-2022 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. // Package httpdtest provides utilities for testing the exposed REST API.
  15. package httpdtest
  16. import (
  17. "bytes"
  18. "encoding/hex"
  19. "encoding/json"
  20. "errors"
  21. "fmt"
  22. "io"
  23. "net/http"
  24. "net/url"
  25. "path"
  26. "strconv"
  27. "strings"
  28. "github.com/go-chi/render"
  29. "github.com/sftpgo/sdk"
  30. "github.com/drakkan/sftpgo/v2/internal/common"
  31. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  32. "github.com/drakkan/sftpgo/v2/internal/httpclient"
  33. "github.com/drakkan/sftpgo/v2/internal/httpd"
  34. "github.com/drakkan/sftpgo/v2/internal/kms"
  35. "github.com/drakkan/sftpgo/v2/internal/util"
  36. "github.com/drakkan/sftpgo/v2/internal/version"
  37. "github.com/drakkan/sftpgo/v2/internal/vfs"
  38. )
  39. const (
  40. tokenPath = "/api/v2/token"
  41. activeConnectionsPath = "/api/v2/connections"
  42. quotasBasePath = "/api/v2/quotas"
  43. quotaScanPath = "/api/v2/quotas/users/scans"
  44. quotaScanVFolderPath = "/api/v2/quotas/folders/scans"
  45. userPath = "/api/v2/users"
  46. groupPath = "/api/v2/groups"
  47. versionPath = "/api/v2/version"
  48. folderPath = "/api/v2/folders"
  49. serverStatusPath = "/api/v2/status"
  50. dumpDataPath = "/api/v2/dumpdata"
  51. loadDataPath = "/api/v2/loaddata"
  52. defenderHosts = "/api/v2/defender/hosts"
  53. adminPath = "/api/v2/admins"
  54. adminPwdPath = "/api/v2/admin/changepwd"
  55. apiKeysPath = "/api/v2/apikeys"
  56. retentionBasePath = "/api/v2/retention/users"
  57. retentionChecksPath = "/api/v2/retention/users/checks"
  58. eventActionsPath = "/api/v2/eventactions"
  59. eventRulesPath = "/api/v2/eventrules"
  60. )
  61. const (
  62. defaultTokenAuthUser = "admin"
  63. defaultTokenAuthPass = "password"
  64. )
  65. var (
  66. httpBaseURL = "http://127.0.0.1:8080"
  67. jwtToken = ""
  68. )
  69. // SetBaseURL sets the base url to use for HTTP requests.
  70. // Default URL is "http://127.0.0.1:8080"
  71. func SetBaseURL(url string) {
  72. httpBaseURL = url
  73. }
  74. // SetJWTToken sets the JWT token to use
  75. func SetJWTToken(token string) {
  76. jwtToken = token
  77. }
  78. func sendHTTPRequest(method, url string, body io.Reader, contentType, token string) (*http.Response, error) {
  79. req, err := http.NewRequest(method, url, body)
  80. if err != nil {
  81. return nil, err
  82. }
  83. if contentType != "" {
  84. req.Header.Set("Content-Type", "application/json")
  85. }
  86. if token != "" {
  87. req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", token))
  88. }
  89. return httpclient.GetHTTPClient().Do(req)
  90. }
  91. func buildURLRelativeToBase(paths ...string) string {
  92. // we need to use path.Join and not filepath.Join
  93. // since filepath.Join will use backslash separator on Windows
  94. p := path.Join(paths...)
  95. return fmt.Sprintf("%s/%s", strings.TrimRight(httpBaseURL, "/"), strings.TrimLeft(p, "/"))
  96. }
  97. // GetToken tries to return a JWT token
  98. func GetToken(username, password string) (string, map[string]any, error) {
  99. req, err := http.NewRequest(http.MethodGet, buildURLRelativeToBase(tokenPath), nil)
  100. if err != nil {
  101. return "", nil, err
  102. }
  103. req.SetBasicAuth(username, password)
  104. resp, err := httpclient.GetHTTPClient().Do(req)
  105. if err != nil {
  106. return "", nil, err
  107. }
  108. defer resp.Body.Close()
  109. err = checkResponse(resp.StatusCode, http.StatusOK)
  110. if err != nil {
  111. return "", nil, err
  112. }
  113. responseHolder := make(map[string]any)
  114. err = render.DecodeJSON(resp.Body, &responseHolder)
  115. if err != nil {
  116. return "", nil, err
  117. }
  118. return responseHolder["access_token"].(string), responseHolder, nil
  119. }
  120. func getDefaultToken() string {
  121. if jwtToken != "" {
  122. return jwtToken
  123. }
  124. token, _, err := GetToken(defaultTokenAuthUser, defaultTokenAuthPass)
  125. if err != nil {
  126. return ""
  127. }
  128. return token
  129. }
  130. // AddUser adds a new user and checks the received HTTP Status code against expectedStatusCode.
  131. func AddUser(user dataprovider.User, expectedStatusCode int) (dataprovider.User, []byte, error) {
  132. var newUser dataprovider.User
  133. var body []byte
  134. userAsJSON, _ := json.Marshal(user)
  135. resp, err := sendHTTPRequest(http.MethodPost, buildURLRelativeToBase(userPath), bytes.NewBuffer(userAsJSON),
  136. "application/json", getDefaultToken())
  137. if err != nil {
  138. return newUser, body, err
  139. }
  140. defer resp.Body.Close()
  141. err = checkResponse(resp.StatusCode, expectedStatusCode)
  142. if expectedStatusCode != http.StatusCreated {
  143. body, _ = getResponseBody(resp)
  144. return newUser, body, err
  145. }
  146. if err == nil {
  147. err = render.DecodeJSON(resp.Body, &newUser)
  148. } else {
  149. body, _ = getResponseBody(resp)
  150. }
  151. if err == nil {
  152. err = checkUser(&user, &newUser)
  153. }
  154. return newUser, body, err
  155. }
  156. // UpdateUserWithJSON update a user using the provided JSON as POST body
  157. func UpdateUserWithJSON(user dataprovider.User, expectedStatusCode int, disconnect string, userAsJSON []byte) (dataprovider.User, []byte, error) {
  158. var newUser dataprovider.User
  159. var body []byte
  160. url, err := addDisconnectQueryParam(buildURLRelativeToBase(userPath, url.PathEscape(user.Username)), disconnect)
  161. if err != nil {
  162. return user, body, err
  163. }
  164. resp, err := sendHTTPRequest(http.MethodPut, url.String(), bytes.NewBuffer(userAsJSON), "application/json",
  165. getDefaultToken())
  166. if err != nil {
  167. return user, body, err
  168. }
  169. defer resp.Body.Close()
  170. body, _ = getResponseBody(resp)
  171. err = checkResponse(resp.StatusCode, expectedStatusCode)
  172. if expectedStatusCode != http.StatusOK {
  173. return newUser, body, err
  174. }
  175. if err == nil {
  176. newUser, body, err = GetUserByUsername(user.Username, expectedStatusCode)
  177. }
  178. if err == nil {
  179. err = checkUser(&user, &newUser)
  180. }
  181. return newUser, body, err
  182. }
  183. // UpdateUser updates an existing user and checks the received HTTP Status code against expectedStatusCode.
  184. func UpdateUser(user dataprovider.User, expectedStatusCode int, disconnect string) (dataprovider.User, []byte, error) {
  185. userAsJSON, _ := json.Marshal(user)
  186. return UpdateUserWithJSON(user, expectedStatusCode, disconnect, userAsJSON)
  187. }
  188. // RemoveUser removes an existing user and checks the received HTTP Status code against expectedStatusCode.
  189. func RemoveUser(user dataprovider.User, expectedStatusCode int) ([]byte, error) {
  190. var body []byte
  191. resp, err := sendHTTPRequest(http.MethodDelete, buildURLRelativeToBase(userPath, url.PathEscape(user.Username)),
  192. nil, "", getDefaultToken())
  193. if err != nil {
  194. return body, err
  195. }
  196. defer resp.Body.Close()
  197. body, _ = getResponseBody(resp)
  198. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  199. }
  200. // GetUserByUsername gets a user by username and checks the received HTTP Status code against expectedStatusCode.
  201. func GetUserByUsername(username string, expectedStatusCode int) (dataprovider.User, []byte, error) {
  202. var user dataprovider.User
  203. var body []byte
  204. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(userPath, url.PathEscape(username)),
  205. nil, "", getDefaultToken())
  206. if err != nil {
  207. return user, body, err
  208. }
  209. defer resp.Body.Close()
  210. err = checkResponse(resp.StatusCode, expectedStatusCode)
  211. if err == nil && expectedStatusCode == http.StatusOK {
  212. err = render.DecodeJSON(resp.Body, &user)
  213. } else {
  214. body, _ = getResponseBody(resp)
  215. }
  216. return user, body, err
  217. }
  218. // GetUsers returns a list of users and checks the received HTTP Status code against expectedStatusCode.
  219. // The number of results can be limited specifying a limit.
  220. // Some results can be skipped specifying an offset.
  221. func GetUsers(limit, offset int64, expectedStatusCode int) ([]dataprovider.User, []byte, error) {
  222. var users []dataprovider.User
  223. var body []byte
  224. url, err := addLimitAndOffsetQueryParams(buildURLRelativeToBase(userPath), limit, offset)
  225. if err != nil {
  226. return users, body, err
  227. }
  228. resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "", getDefaultToken())
  229. if err != nil {
  230. return users, body, err
  231. }
  232. defer resp.Body.Close()
  233. err = checkResponse(resp.StatusCode, expectedStatusCode)
  234. if err == nil && expectedStatusCode == http.StatusOK {
  235. err = render.DecodeJSON(resp.Body, &users)
  236. } else {
  237. body, _ = getResponseBody(resp)
  238. }
  239. return users, body, err
  240. }
  241. // AddGroup adds a new group and checks the received HTTP Status code against expectedStatusCode.
  242. func AddGroup(group dataprovider.Group, expectedStatusCode int) (dataprovider.Group, []byte, error) {
  243. var newGroup dataprovider.Group
  244. var body []byte
  245. asJSON, _ := json.Marshal(group)
  246. resp, err := sendHTTPRequest(http.MethodPost, buildURLRelativeToBase(groupPath), bytes.NewBuffer(asJSON),
  247. "application/json", getDefaultToken())
  248. if err != nil {
  249. return newGroup, body, err
  250. }
  251. defer resp.Body.Close()
  252. err = checkResponse(resp.StatusCode, expectedStatusCode)
  253. if expectedStatusCode != http.StatusCreated {
  254. body, _ = getResponseBody(resp)
  255. return newGroup, body, err
  256. }
  257. if err == nil {
  258. err = render.DecodeJSON(resp.Body, &newGroup)
  259. } else {
  260. body, _ = getResponseBody(resp)
  261. }
  262. if err == nil {
  263. err = checkGroup(group, newGroup)
  264. }
  265. return newGroup, body, err
  266. }
  267. // UpdateGroup updates an existing group and checks the received HTTP Status code against expectedStatusCode
  268. func UpdateGroup(group dataprovider.Group, expectedStatusCode int) (dataprovider.Group, []byte, error) {
  269. var newGroup dataprovider.Group
  270. var body []byte
  271. asJSON, _ := json.Marshal(group)
  272. resp, err := sendHTTPRequest(http.MethodPut, buildURLRelativeToBase(groupPath, url.PathEscape(group.Name)),
  273. bytes.NewBuffer(asJSON), "application/json", getDefaultToken())
  274. if err != nil {
  275. return newGroup, body, err
  276. }
  277. defer resp.Body.Close()
  278. body, _ = getResponseBody(resp)
  279. err = checkResponse(resp.StatusCode, expectedStatusCode)
  280. if expectedStatusCode != http.StatusOK {
  281. return newGroup, body, err
  282. }
  283. if err == nil {
  284. newGroup, body, err = GetGroupByName(group.Name, expectedStatusCode)
  285. }
  286. if err == nil {
  287. err = checkGroup(group, newGroup)
  288. }
  289. return newGroup, body, err
  290. }
  291. // RemoveGroup removes an existing group and checks the received HTTP Status code against expectedStatusCode.
  292. func RemoveGroup(group dataprovider.Group, expectedStatusCode int) ([]byte, error) {
  293. var body []byte
  294. resp, err := sendHTTPRequest(http.MethodDelete, buildURLRelativeToBase(groupPath, url.PathEscape(group.Name)),
  295. nil, "", getDefaultToken())
  296. if err != nil {
  297. return body, err
  298. }
  299. defer resp.Body.Close()
  300. body, _ = getResponseBody(resp)
  301. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  302. }
  303. // GetGroupByName gets a group by name and checks the received HTTP Status code against expectedStatusCode.
  304. func GetGroupByName(name string, expectedStatusCode int) (dataprovider.Group, []byte, error) {
  305. var group dataprovider.Group
  306. var body []byte
  307. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(groupPath, url.PathEscape(name)),
  308. nil, "", getDefaultToken())
  309. if err != nil {
  310. return group, body, err
  311. }
  312. defer resp.Body.Close()
  313. err = checkResponse(resp.StatusCode, expectedStatusCode)
  314. if err == nil && expectedStatusCode == http.StatusOK {
  315. err = render.DecodeJSON(resp.Body, &group)
  316. } else {
  317. body, _ = getResponseBody(resp)
  318. }
  319. return group, body, err
  320. }
  321. // GetGroups returns a list of groups and checks the received HTTP Status code against expectedStatusCode.
  322. // The number of results can be limited specifying a limit.
  323. // Some results can be skipped specifying an offset.
  324. func GetGroups(limit, offset int64, expectedStatusCode int) ([]dataprovider.Group, []byte, error) {
  325. var groups []dataprovider.Group
  326. var body []byte
  327. url, err := addLimitAndOffsetQueryParams(buildURLRelativeToBase(groupPath), limit, offset)
  328. if err != nil {
  329. return groups, body, err
  330. }
  331. resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "", getDefaultToken())
  332. if err != nil {
  333. return groups, body, err
  334. }
  335. defer resp.Body.Close()
  336. err = checkResponse(resp.StatusCode, expectedStatusCode)
  337. if err == nil && expectedStatusCode == http.StatusOK {
  338. err = render.DecodeJSON(resp.Body, &groups)
  339. } else {
  340. body, _ = getResponseBody(resp)
  341. }
  342. return groups, body, err
  343. }
  344. // AddAdmin adds a new admin and checks the received HTTP Status code against expectedStatusCode.
  345. func AddAdmin(admin dataprovider.Admin, expectedStatusCode int) (dataprovider.Admin, []byte, error) {
  346. var newAdmin dataprovider.Admin
  347. var body []byte
  348. asJSON, _ := json.Marshal(admin)
  349. resp, err := sendHTTPRequest(http.MethodPost, buildURLRelativeToBase(adminPath), bytes.NewBuffer(asJSON),
  350. "application/json", getDefaultToken())
  351. if err != nil {
  352. return newAdmin, body, err
  353. }
  354. defer resp.Body.Close()
  355. err = checkResponse(resp.StatusCode, expectedStatusCode)
  356. if expectedStatusCode != http.StatusCreated {
  357. body, _ = getResponseBody(resp)
  358. return newAdmin, body, err
  359. }
  360. if err == nil {
  361. err = render.DecodeJSON(resp.Body, &newAdmin)
  362. } else {
  363. body, _ = getResponseBody(resp)
  364. }
  365. if err == nil {
  366. err = checkAdmin(&admin, &newAdmin)
  367. }
  368. return newAdmin, body, err
  369. }
  370. // UpdateAdmin updates an existing admin and checks the received HTTP Status code against expectedStatusCode
  371. func UpdateAdmin(admin dataprovider.Admin, expectedStatusCode int) (dataprovider.Admin, []byte, error) {
  372. var newAdmin dataprovider.Admin
  373. var body []byte
  374. asJSON, _ := json.Marshal(admin)
  375. resp, err := sendHTTPRequest(http.MethodPut, buildURLRelativeToBase(adminPath, url.PathEscape(admin.Username)),
  376. bytes.NewBuffer(asJSON), "application/json", getDefaultToken())
  377. if err != nil {
  378. return newAdmin, body, err
  379. }
  380. defer resp.Body.Close()
  381. body, _ = getResponseBody(resp)
  382. err = checkResponse(resp.StatusCode, expectedStatusCode)
  383. if expectedStatusCode != http.StatusOK {
  384. return newAdmin, body, err
  385. }
  386. if err == nil {
  387. newAdmin, body, err = GetAdminByUsername(admin.Username, expectedStatusCode)
  388. }
  389. if err == nil {
  390. err = checkAdmin(&admin, &newAdmin)
  391. }
  392. return newAdmin, body, err
  393. }
  394. // RemoveAdmin removes an existing admin and checks the received HTTP Status code against expectedStatusCode.
  395. func RemoveAdmin(admin dataprovider.Admin, expectedStatusCode int) ([]byte, error) {
  396. var body []byte
  397. resp, err := sendHTTPRequest(http.MethodDelete, buildURLRelativeToBase(adminPath, url.PathEscape(admin.Username)),
  398. nil, "", getDefaultToken())
  399. if err != nil {
  400. return body, err
  401. }
  402. defer resp.Body.Close()
  403. body, _ = getResponseBody(resp)
  404. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  405. }
  406. // GetAdminByUsername gets an admin by username and checks the received HTTP Status code against expectedStatusCode.
  407. func GetAdminByUsername(username string, expectedStatusCode int) (dataprovider.Admin, []byte, error) {
  408. var admin dataprovider.Admin
  409. var body []byte
  410. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(adminPath, url.PathEscape(username)),
  411. nil, "", getDefaultToken())
  412. if err != nil {
  413. return admin, body, err
  414. }
  415. defer resp.Body.Close()
  416. err = checkResponse(resp.StatusCode, expectedStatusCode)
  417. if err == nil && expectedStatusCode == http.StatusOK {
  418. err = render.DecodeJSON(resp.Body, &admin)
  419. } else {
  420. body, _ = getResponseBody(resp)
  421. }
  422. return admin, body, err
  423. }
  424. // GetAdmins returns a list of admins and checks the received HTTP Status code against expectedStatusCode.
  425. // The number of results can be limited specifying a limit.
  426. // Some results can be skipped specifying an offset.
  427. func GetAdmins(limit, offset int64, expectedStatusCode int) ([]dataprovider.Admin, []byte, error) {
  428. var admins []dataprovider.Admin
  429. var body []byte
  430. url, err := addLimitAndOffsetQueryParams(buildURLRelativeToBase(adminPath), limit, offset)
  431. if err != nil {
  432. return admins, body, err
  433. }
  434. resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "", getDefaultToken())
  435. if err != nil {
  436. return admins, body, err
  437. }
  438. defer resp.Body.Close()
  439. err = checkResponse(resp.StatusCode, expectedStatusCode)
  440. if err == nil && expectedStatusCode == http.StatusOK {
  441. err = render.DecodeJSON(resp.Body, &admins)
  442. } else {
  443. body, _ = getResponseBody(resp)
  444. }
  445. return admins, body, err
  446. }
  447. // ChangeAdminPassword changes the password for an existing admin
  448. func ChangeAdminPassword(currentPassword, newPassword string, expectedStatusCode int) ([]byte, error) {
  449. var body []byte
  450. pwdChange := make(map[string]string)
  451. pwdChange["current_password"] = currentPassword
  452. pwdChange["new_password"] = newPassword
  453. asJSON, _ := json.Marshal(&pwdChange)
  454. resp, err := sendHTTPRequest(http.MethodPut, buildURLRelativeToBase(adminPwdPath),
  455. bytes.NewBuffer(asJSON), "application/json", getDefaultToken())
  456. if err != nil {
  457. return body, err
  458. }
  459. defer resp.Body.Close()
  460. err = checkResponse(resp.StatusCode, expectedStatusCode)
  461. body, _ = getResponseBody(resp)
  462. return body, err
  463. }
  464. // GetAPIKeys returns a list of API keys and checks the received HTTP Status code against expectedStatusCode.
  465. // The number of results can be limited specifying a limit.
  466. // Some results can be skipped specifying an offset.
  467. func GetAPIKeys(limit, offset int64, expectedStatusCode int) ([]dataprovider.APIKey, []byte, error) {
  468. var apiKeys []dataprovider.APIKey
  469. var body []byte
  470. url, err := addLimitAndOffsetQueryParams(buildURLRelativeToBase(apiKeysPath), limit, offset)
  471. if err != nil {
  472. return apiKeys, body, err
  473. }
  474. resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "", getDefaultToken())
  475. if err != nil {
  476. return apiKeys, body, err
  477. }
  478. defer resp.Body.Close()
  479. err = checkResponse(resp.StatusCode, expectedStatusCode)
  480. if err == nil && expectedStatusCode == http.StatusOK {
  481. err = render.DecodeJSON(resp.Body, &apiKeys)
  482. } else {
  483. body, _ = getResponseBody(resp)
  484. }
  485. return apiKeys, body, err
  486. }
  487. // AddAPIKey adds a new API key and checks the received HTTP Status code against expectedStatusCode.
  488. func AddAPIKey(apiKey dataprovider.APIKey, expectedStatusCode int) (dataprovider.APIKey, []byte, error) {
  489. var newAPIKey dataprovider.APIKey
  490. var body []byte
  491. asJSON, _ := json.Marshal(apiKey)
  492. resp, err := sendHTTPRequest(http.MethodPost, buildURLRelativeToBase(apiKeysPath), bytes.NewBuffer(asJSON),
  493. "application/json", getDefaultToken())
  494. if err != nil {
  495. return newAPIKey, body, err
  496. }
  497. defer resp.Body.Close()
  498. err = checkResponse(resp.StatusCode, expectedStatusCode)
  499. if expectedStatusCode != http.StatusCreated {
  500. body, _ = getResponseBody(resp)
  501. return newAPIKey, body, err
  502. }
  503. if err != nil {
  504. body, _ = getResponseBody(resp)
  505. return newAPIKey, body, err
  506. }
  507. response := make(map[string]string)
  508. err = render.DecodeJSON(resp.Body, &response)
  509. if err == nil {
  510. newAPIKey, body, err = GetAPIKeyByID(resp.Header.Get("X-Object-ID"), http.StatusOK)
  511. }
  512. if err == nil {
  513. err = checkAPIKey(&apiKey, &newAPIKey)
  514. }
  515. newAPIKey.Key = response["key"]
  516. return newAPIKey, body, err
  517. }
  518. // UpdateAPIKey updates an existing API key and checks the received HTTP Status code against expectedStatusCode
  519. func UpdateAPIKey(apiKey dataprovider.APIKey, expectedStatusCode int) (dataprovider.APIKey, []byte, error) {
  520. var newAPIKey dataprovider.APIKey
  521. var body []byte
  522. asJSON, _ := json.Marshal(apiKey)
  523. resp, err := sendHTTPRequest(http.MethodPut, buildURLRelativeToBase(apiKeysPath, url.PathEscape(apiKey.KeyID)),
  524. bytes.NewBuffer(asJSON), "application/json", getDefaultToken())
  525. if err != nil {
  526. return newAPIKey, body, err
  527. }
  528. defer resp.Body.Close()
  529. body, _ = getResponseBody(resp)
  530. err = checkResponse(resp.StatusCode, expectedStatusCode)
  531. if expectedStatusCode != http.StatusOK {
  532. return newAPIKey, body, err
  533. }
  534. if err == nil {
  535. newAPIKey, body, err = GetAPIKeyByID(apiKey.KeyID, expectedStatusCode)
  536. }
  537. if err == nil {
  538. err = checkAPIKey(&apiKey, &newAPIKey)
  539. }
  540. return newAPIKey, body, err
  541. }
  542. // RemoveAPIKey removes an existing API key and checks the received HTTP Status code against expectedStatusCode.
  543. func RemoveAPIKey(apiKey dataprovider.APIKey, expectedStatusCode int) ([]byte, error) {
  544. var body []byte
  545. resp, err := sendHTTPRequest(http.MethodDelete, buildURLRelativeToBase(apiKeysPath, url.PathEscape(apiKey.KeyID)),
  546. nil, "", getDefaultToken())
  547. if err != nil {
  548. return body, err
  549. }
  550. defer resp.Body.Close()
  551. body, _ = getResponseBody(resp)
  552. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  553. }
  554. // GetAPIKeyByID gets a API key by ID and checks the received HTTP Status code against expectedStatusCode.
  555. func GetAPIKeyByID(keyID string, expectedStatusCode int) (dataprovider.APIKey, []byte, error) {
  556. var apiKey dataprovider.APIKey
  557. var body []byte
  558. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(apiKeysPath, url.PathEscape(keyID)),
  559. nil, "", getDefaultToken())
  560. if err != nil {
  561. return apiKey, body, err
  562. }
  563. defer resp.Body.Close()
  564. err = checkResponse(resp.StatusCode, expectedStatusCode)
  565. if err == nil && expectedStatusCode == http.StatusOK {
  566. err = render.DecodeJSON(resp.Body, &apiKey)
  567. } else {
  568. body, _ = getResponseBody(resp)
  569. }
  570. return apiKey, body, err
  571. }
  572. // AddEventAction adds a new event action
  573. func AddEventAction(action dataprovider.BaseEventAction, expectedStatusCode int) (dataprovider.BaseEventAction, []byte, error) {
  574. var newAction dataprovider.BaseEventAction
  575. var body []byte
  576. asJSON, _ := json.Marshal(action)
  577. resp, err := sendHTTPRequest(http.MethodPost, buildURLRelativeToBase(eventActionsPath), bytes.NewBuffer(asJSON),
  578. "application/json", getDefaultToken())
  579. if err != nil {
  580. return newAction, body, err
  581. }
  582. defer resp.Body.Close()
  583. err = checkResponse(resp.StatusCode, expectedStatusCode)
  584. if expectedStatusCode != http.StatusCreated {
  585. body, _ = getResponseBody(resp)
  586. return newAction, body, err
  587. }
  588. if err == nil {
  589. err = render.DecodeJSON(resp.Body, &newAction)
  590. } else {
  591. body, _ = getResponseBody(resp)
  592. }
  593. if err == nil {
  594. err = checkEventAction(action, newAction)
  595. }
  596. return newAction, body, err
  597. }
  598. // UpdateEventAction updates an existing event action
  599. func UpdateEventAction(action dataprovider.BaseEventAction, expectedStatusCode int) (dataprovider.BaseEventAction, []byte, error) {
  600. var newAction dataprovider.BaseEventAction
  601. var body []byte
  602. asJSON, _ := json.Marshal(action)
  603. resp, err := sendHTTPRequest(http.MethodPut, buildURLRelativeToBase(eventActionsPath, url.PathEscape(action.Name)),
  604. bytes.NewBuffer(asJSON), "application/json", getDefaultToken())
  605. if err != nil {
  606. return newAction, body, err
  607. }
  608. defer resp.Body.Close()
  609. body, _ = getResponseBody(resp)
  610. err = checkResponse(resp.StatusCode, expectedStatusCode)
  611. if expectedStatusCode != http.StatusOK {
  612. return newAction, body, err
  613. }
  614. if err == nil {
  615. newAction, body, err = GetEventActionByName(action.Name, expectedStatusCode)
  616. }
  617. if err == nil {
  618. err = checkEventAction(action, newAction)
  619. }
  620. return newAction, body, err
  621. }
  622. // RemoveEventAction removes an existing action and checks the received HTTP Status code against expectedStatusCode.
  623. func RemoveEventAction(action dataprovider.BaseEventAction, expectedStatusCode int) ([]byte, error) {
  624. var body []byte
  625. resp, err := sendHTTPRequest(http.MethodDelete, buildURLRelativeToBase(eventActionsPath, url.PathEscape(action.Name)),
  626. nil, "", getDefaultToken())
  627. if err != nil {
  628. return body, err
  629. }
  630. defer resp.Body.Close()
  631. body, _ = getResponseBody(resp)
  632. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  633. }
  634. // GetEventActionByName gets an event action by name and checks the received HTTP Status code against expectedStatusCode.
  635. func GetEventActionByName(name string, expectedStatusCode int) (dataprovider.BaseEventAction, []byte, error) {
  636. var action dataprovider.BaseEventAction
  637. var body []byte
  638. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(eventActionsPath, url.PathEscape(name)),
  639. nil, "", getDefaultToken())
  640. if err != nil {
  641. return action, body, err
  642. }
  643. defer resp.Body.Close()
  644. err = checkResponse(resp.StatusCode, expectedStatusCode)
  645. if err == nil && expectedStatusCode == http.StatusOK {
  646. err = render.DecodeJSON(resp.Body, &action)
  647. } else {
  648. body, _ = getResponseBody(resp)
  649. }
  650. return action, body, err
  651. }
  652. // GetEventActions returns a list of event actions and checks the received HTTP Status code against expectedStatusCode.
  653. // The number of results can be limited specifying a limit.
  654. // Some results can be skipped specifying an offset.
  655. func GetEventActions(limit, offset int64, expectedStatusCode int) ([]dataprovider.BaseEventAction, []byte, error) {
  656. var actions []dataprovider.BaseEventAction
  657. var body []byte
  658. url, err := addLimitAndOffsetQueryParams(buildURLRelativeToBase(eventActionsPath), limit, offset)
  659. if err != nil {
  660. return actions, body, err
  661. }
  662. resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "", getDefaultToken())
  663. if err != nil {
  664. return actions, body, err
  665. }
  666. defer resp.Body.Close()
  667. err = checkResponse(resp.StatusCode, expectedStatusCode)
  668. if err == nil && expectedStatusCode == http.StatusOK {
  669. err = render.DecodeJSON(resp.Body, &actions)
  670. } else {
  671. body, _ = getResponseBody(resp)
  672. }
  673. return actions, body, err
  674. }
  675. // AddEventRule adds a new event rule
  676. func AddEventRule(rule dataprovider.EventRule, expectedStatusCode int) (dataprovider.EventRule, []byte, error) {
  677. var newRule dataprovider.EventRule
  678. var body []byte
  679. asJSON, _ := json.Marshal(rule)
  680. resp, err := sendHTTPRequest(http.MethodPost, buildURLRelativeToBase(eventRulesPath), bytes.NewBuffer(asJSON),
  681. "application/json", getDefaultToken())
  682. if err != nil {
  683. return newRule, body, err
  684. }
  685. defer resp.Body.Close()
  686. err = checkResponse(resp.StatusCode, expectedStatusCode)
  687. if expectedStatusCode != http.StatusCreated {
  688. body, _ = getResponseBody(resp)
  689. return newRule, body, err
  690. }
  691. if err == nil {
  692. err = render.DecodeJSON(resp.Body, &newRule)
  693. } else {
  694. body, _ = getResponseBody(resp)
  695. }
  696. if err == nil {
  697. err = checkEventRule(rule, newRule)
  698. }
  699. return newRule, body, err
  700. }
  701. // UpdateEventRule updates an existing event rule
  702. func UpdateEventRule(rule dataprovider.EventRule, expectedStatusCode int) (dataprovider.EventRule, []byte, error) {
  703. var newRule dataprovider.EventRule
  704. var body []byte
  705. asJSON, _ := json.Marshal(rule)
  706. resp, err := sendHTTPRequest(http.MethodPut, buildURLRelativeToBase(eventRulesPath, url.PathEscape(rule.Name)),
  707. bytes.NewBuffer(asJSON), "application/json", getDefaultToken())
  708. if err != nil {
  709. return newRule, body, err
  710. }
  711. defer resp.Body.Close()
  712. body, _ = getResponseBody(resp)
  713. err = checkResponse(resp.StatusCode, expectedStatusCode)
  714. if expectedStatusCode != http.StatusOK {
  715. return newRule, body, err
  716. }
  717. if err == nil {
  718. newRule, body, err = GetEventRuleByName(rule.Name, expectedStatusCode)
  719. }
  720. if err == nil {
  721. err = checkEventRule(rule, newRule)
  722. }
  723. return newRule, body, err
  724. }
  725. // RemoveEventRule removes an existing rule and checks the received HTTP Status code against expectedStatusCode.
  726. func RemoveEventRule(rule dataprovider.EventRule, expectedStatusCode int) ([]byte, error) {
  727. var body []byte
  728. resp, err := sendHTTPRequest(http.MethodDelete, buildURLRelativeToBase(eventRulesPath, url.PathEscape(rule.Name)),
  729. nil, "", getDefaultToken())
  730. if err != nil {
  731. return body, err
  732. }
  733. defer resp.Body.Close()
  734. body, _ = getResponseBody(resp)
  735. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  736. }
  737. // GetEventRuleByName gets an event rule by name and checks the received HTTP Status code against expectedStatusCode.
  738. func GetEventRuleByName(name string, expectedStatusCode int) (dataprovider.EventRule, []byte, error) {
  739. var rule dataprovider.EventRule
  740. var body []byte
  741. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(eventRulesPath, url.PathEscape(name)),
  742. nil, "", getDefaultToken())
  743. if err != nil {
  744. return rule, body, err
  745. }
  746. defer resp.Body.Close()
  747. err = checkResponse(resp.StatusCode, expectedStatusCode)
  748. if err == nil && expectedStatusCode == http.StatusOK {
  749. err = render.DecodeJSON(resp.Body, &rule)
  750. } else {
  751. body, _ = getResponseBody(resp)
  752. }
  753. return rule, body, err
  754. }
  755. // GetEventRules returns a list of event rules and checks the received HTTP Status code against expectedStatusCode.
  756. // The number of results can be limited specifying a limit.
  757. // Some results can be skipped specifying an offset.
  758. func GetEventRules(limit, offset int64, expectedStatusCode int) ([]dataprovider.EventRule, []byte, error) {
  759. var rules []dataprovider.EventRule
  760. var body []byte
  761. url, err := addLimitAndOffsetQueryParams(buildURLRelativeToBase(eventRulesPath), limit, offset)
  762. if err != nil {
  763. return rules, body, err
  764. }
  765. resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "", getDefaultToken())
  766. if err != nil {
  767. return rules, body, err
  768. }
  769. defer resp.Body.Close()
  770. err = checkResponse(resp.StatusCode, expectedStatusCode)
  771. if err == nil && expectedStatusCode == http.StatusOK {
  772. err = render.DecodeJSON(resp.Body, &rules)
  773. } else {
  774. body, _ = getResponseBody(resp)
  775. }
  776. return rules, body, err
  777. }
  778. // GetQuotaScans gets active quota scans for users and checks the received HTTP Status code against expectedStatusCode.
  779. func GetQuotaScans(expectedStatusCode int) ([]dataprovider.ActiveQuotaScan, []byte, error) {
  780. var quotaScans []dataprovider.ActiveQuotaScan
  781. var body []byte
  782. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(quotaScanPath), nil, "", getDefaultToken())
  783. if err != nil {
  784. return quotaScans, body, err
  785. }
  786. defer resp.Body.Close()
  787. err = checkResponse(resp.StatusCode, expectedStatusCode)
  788. if err == nil && expectedStatusCode == http.StatusOK {
  789. err = render.DecodeJSON(resp.Body, &quotaScans)
  790. } else {
  791. body, _ = getResponseBody(resp)
  792. }
  793. return quotaScans, body, err
  794. }
  795. // StartQuotaScan starts a new quota scan for the given user and checks the received HTTP Status code against expectedStatusCode.
  796. func StartQuotaScan(user dataprovider.User, expectedStatusCode int) ([]byte, error) {
  797. var body []byte
  798. resp, err := sendHTTPRequest(http.MethodPost, buildURLRelativeToBase(quotasBasePath, "users", user.Username, "scan"),
  799. nil, "", getDefaultToken())
  800. if err != nil {
  801. return body, err
  802. }
  803. defer resp.Body.Close()
  804. body, _ = getResponseBody(resp)
  805. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  806. }
  807. // UpdateQuotaUsage updates the user used quota limits and checks the received
  808. // HTTP Status code against expectedStatusCode.
  809. func UpdateQuotaUsage(user dataprovider.User, mode string, expectedStatusCode int) ([]byte, error) {
  810. var body []byte
  811. userAsJSON, _ := json.Marshal(user)
  812. url, err := addModeQueryParam(buildURLRelativeToBase(quotasBasePath, "users", user.Username, "usage"), mode)
  813. if err != nil {
  814. return body, err
  815. }
  816. resp, err := sendHTTPRequest(http.MethodPut, url.String(), bytes.NewBuffer(userAsJSON), "application/json",
  817. getDefaultToken())
  818. if err != nil {
  819. return body, err
  820. }
  821. defer resp.Body.Close()
  822. body, _ = getResponseBody(resp)
  823. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  824. }
  825. // UpdateTransferQuotaUsage updates the user used transfer quota limits and checks the received
  826. // HTTP Status code against expectedStatusCode.
  827. func UpdateTransferQuotaUsage(user dataprovider.User, mode string, expectedStatusCode int) ([]byte, error) {
  828. var body []byte
  829. userAsJSON, _ := json.Marshal(user)
  830. url, err := addModeQueryParam(buildURLRelativeToBase(quotasBasePath, "users", user.Username, "transfer-usage"), mode)
  831. if err != nil {
  832. return body, err
  833. }
  834. resp, err := sendHTTPRequest(http.MethodPut, url.String(), bytes.NewBuffer(userAsJSON), "application/json",
  835. getDefaultToken())
  836. if err != nil {
  837. return body, err
  838. }
  839. defer resp.Body.Close()
  840. body, _ = getResponseBody(resp)
  841. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  842. }
  843. // GetRetentionChecks returns the active retention checks
  844. func GetRetentionChecks(expectedStatusCode int) ([]common.ActiveRetentionChecks, []byte, error) {
  845. var checks []common.ActiveRetentionChecks
  846. var body []byte
  847. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(retentionChecksPath), nil, "", getDefaultToken())
  848. if err != nil {
  849. return checks, body, err
  850. }
  851. defer resp.Body.Close()
  852. err = checkResponse(resp.StatusCode, expectedStatusCode)
  853. if err == nil && expectedStatusCode == http.StatusOK {
  854. err = render.DecodeJSON(resp.Body, &checks)
  855. } else {
  856. body, _ = getResponseBody(resp)
  857. }
  858. return checks, body, err
  859. }
  860. // StartRetentionCheck starts a new retention check
  861. func StartRetentionCheck(username string, retention []common.FolderRetention, expectedStatusCode int) ([]byte, error) {
  862. var body []byte
  863. asJSON, _ := json.Marshal(retention)
  864. resp, err := sendHTTPRequest(http.MethodPost, buildURLRelativeToBase(retentionBasePath, username, "check"),
  865. bytes.NewBuffer(asJSON), "application/json", getDefaultToken())
  866. if err != nil {
  867. return body, err
  868. }
  869. defer resp.Body.Close()
  870. body, _ = getResponseBody(resp)
  871. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  872. }
  873. // GetConnections returns status and stats for active SFTP/SCP connections
  874. func GetConnections(expectedStatusCode int) ([]common.ConnectionStatus, []byte, error) {
  875. var connections []common.ConnectionStatus
  876. var body []byte
  877. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(activeConnectionsPath), nil, "", getDefaultToken())
  878. if err != nil {
  879. return connections, body, err
  880. }
  881. defer resp.Body.Close()
  882. err = checkResponse(resp.StatusCode, expectedStatusCode)
  883. if err == nil && expectedStatusCode == http.StatusOK {
  884. err = render.DecodeJSON(resp.Body, &connections)
  885. } else {
  886. body, _ = getResponseBody(resp)
  887. }
  888. return connections, body, err
  889. }
  890. // CloseConnection closes an active connection identified by connectionID
  891. func CloseConnection(connectionID string, expectedStatusCode int) ([]byte, error) {
  892. var body []byte
  893. resp, err := sendHTTPRequest(http.MethodDelete, buildURLRelativeToBase(activeConnectionsPath, connectionID),
  894. nil, "", getDefaultToken())
  895. if err != nil {
  896. return body, err
  897. }
  898. defer resp.Body.Close()
  899. err = checkResponse(resp.StatusCode, expectedStatusCode)
  900. body, _ = getResponseBody(resp)
  901. return body, err
  902. }
  903. // AddFolder adds a new folder and checks the received HTTP Status code against expectedStatusCode
  904. func AddFolder(folder vfs.BaseVirtualFolder, expectedStatusCode int) (vfs.BaseVirtualFolder, []byte, error) {
  905. var newFolder vfs.BaseVirtualFolder
  906. var body []byte
  907. folderAsJSON, _ := json.Marshal(folder)
  908. resp, err := sendHTTPRequest(http.MethodPost, buildURLRelativeToBase(folderPath), bytes.NewBuffer(folderAsJSON),
  909. "application/json", getDefaultToken())
  910. if err != nil {
  911. return newFolder, body, err
  912. }
  913. defer resp.Body.Close()
  914. err = checkResponse(resp.StatusCode, expectedStatusCode)
  915. if expectedStatusCode != http.StatusCreated {
  916. body, _ = getResponseBody(resp)
  917. return newFolder, body, err
  918. }
  919. if err == nil {
  920. err = render.DecodeJSON(resp.Body, &newFolder)
  921. } else {
  922. body, _ = getResponseBody(resp)
  923. }
  924. if err == nil {
  925. err = checkFolder(&folder, &newFolder)
  926. }
  927. return newFolder, body, err
  928. }
  929. // UpdateFolder updates an existing folder and checks the received HTTP Status code against expectedStatusCode.
  930. func UpdateFolder(folder vfs.BaseVirtualFolder, expectedStatusCode int) (vfs.BaseVirtualFolder, []byte, error) {
  931. var updatedFolder vfs.BaseVirtualFolder
  932. var body []byte
  933. folderAsJSON, _ := json.Marshal(folder)
  934. resp, err := sendHTTPRequest(http.MethodPut, buildURLRelativeToBase(folderPath, url.PathEscape(folder.Name)),
  935. bytes.NewBuffer(folderAsJSON), "application/json", getDefaultToken())
  936. if err != nil {
  937. return updatedFolder, body, err
  938. }
  939. defer resp.Body.Close()
  940. body, _ = getResponseBody(resp)
  941. err = checkResponse(resp.StatusCode, expectedStatusCode)
  942. if expectedStatusCode != http.StatusOK {
  943. return updatedFolder, body, err
  944. }
  945. if err == nil {
  946. updatedFolder, body, err = GetFolderByName(folder.Name, expectedStatusCode)
  947. }
  948. if err == nil {
  949. err = checkFolder(&folder, &updatedFolder)
  950. }
  951. return updatedFolder, body, err
  952. }
  953. // RemoveFolder removes an existing user and checks the received HTTP Status code against expectedStatusCode.
  954. func RemoveFolder(folder vfs.BaseVirtualFolder, expectedStatusCode int) ([]byte, error) {
  955. var body []byte
  956. resp, err := sendHTTPRequest(http.MethodDelete, buildURLRelativeToBase(folderPath, url.PathEscape(folder.Name)),
  957. nil, "", getDefaultToken())
  958. if err != nil {
  959. return body, err
  960. }
  961. defer resp.Body.Close()
  962. body, _ = getResponseBody(resp)
  963. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  964. }
  965. // GetFolderByName gets a folder by name and checks the received HTTP Status code against expectedStatusCode.
  966. func GetFolderByName(name string, expectedStatusCode int) (vfs.BaseVirtualFolder, []byte, error) {
  967. var folder vfs.BaseVirtualFolder
  968. var body []byte
  969. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(folderPath, url.PathEscape(name)),
  970. nil, "", getDefaultToken())
  971. if err != nil {
  972. return folder, body, err
  973. }
  974. defer resp.Body.Close()
  975. err = checkResponse(resp.StatusCode, expectedStatusCode)
  976. if err == nil && expectedStatusCode == http.StatusOK {
  977. err = render.DecodeJSON(resp.Body, &folder)
  978. } else {
  979. body, _ = getResponseBody(resp)
  980. }
  981. return folder, body, err
  982. }
  983. // GetFolders returns a list of folders and checks the received HTTP Status code against expectedStatusCode.
  984. // The number of results can be limited specifying a limit.
  985. // Some results can be skipped specifying an offset.
  986. // The results can be filtered specifying a folder path, the folder path filter is an exact match
  987. func GetFolders(limit int64, offset int64, expectedStatusCode int) ([]vfs.BaseVirtualFolder, []byte, error) {
  988. var folders []vfs.BaseVirtualFolder
  989. var body []byte
  990. url, err := addLimitAndOffsetQueryParams(buildURLRelativeToBase(folderPath), limit, offset)
  991. if err != nil {
  992. return folders, body, err
  993. }
  994. resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "", getDefaultToken())
  995. if err != nil {
  996. return folders, body, err
  997. }
  998. defer resp.Body.Close()
  999. err = checkResponse(resp.StatusCode, expectedStatusCode)
  1000. if err == nil && expectedStatusCode == http.StatusOK {
  1001. err = render.DecodeJSON(resp.Body, &folders)
  1002. } else {
  1003. body, _ = getResponseBody(resp)
  1004. }
  1005. return folders, body, err
  1006. }
  1007. // GetFoldersQuotaScans gets active quota scans for folders and checks the received HTTP Status code against expectedStatusCode.
  1008. func GetFoldersQuotaScans(expectedStatusCode int) ([]dataprovider.ActiveVirtualFolderQuotaScan, []byte, error) {
  1009. var quotaScans []dataprovider.ActiveVirtualFolderQuotaScan
  1010. var body []byte
  1011. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(quotaScanVFolderPath), nil, "", getDefaultToken())
  1012. if err != nil {
  1013. return quotaScans, body, err
  1014. }
  1015. defer resp.Body.Close()
  1016. err = checkResponse(resp.StatusCode, expectedStatusCode)
  1017. if err == nil && expectedStatusCode == http.StatusOK {
  1018. err = render.DecodeJSON(resp.Body, &quotaScans)
  1019. } else {
  1020. body, _ = getResponseBody(resp)
  1021. }
  1022. return quotaScans, body, err
  1023. }
  1024. // StartFolderQuotaScan start a new quota scan for the given folder and checks the received HTTP Status code against expectedStatusCode.
  1025. func StartFolderQuotaScan(folder vfs.BaseVirtualFolder, expectedStatusCode int) ([]byte, error) {
  1026. var body []byte
  1027. resp, err := sendHTTPRequest(http.MethodPost, buildURLRelativeToBase(quotasBasePath, "folders", folder.Name, "scan"),
  1028. nil, "", getDefaultToken())
  1029. if err != nil {
  1030. return body, err
  1031. }
  1032. defer resp.Body.Close()
  1033. body, _ = getResponseBody(resp)
  1034. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  1035. }
  1036. // UpdateFolderQuotaUsage updates the folder used quota limits and checks the received HTTP Status code against expectedStatusCode.
  1037. func UpdateFolderQuotaUsage(folder vfs.BaseVirtualFolder, mode string, expectedStatusCode int) ([]byte, error) {
  1038. var body []byte
  1039. folderAsJSON, _ := json.Marshal(folder)
  1040. url, err := addModeQueryParam(buildURLRelativeToBase(quotasBasePath, "folders", folder.Name, "usage"), mode)
  1041. if err != nil {
  1042. return body, err
  1043. }
  1044. resp, err := sendHTTPRequest(http.MethodPut, url.String(), bytes.NewBuffer(folderAsJSON), "", getDefaultToken())
  1045. if err != nil {
  1046. return body, err
  1047. }
  1048. defer resp.Body.Close()
  1049. body, _ = getResponseBody(resp)
  1050. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  1051. }
  1052. // GetVersion returns version details
  1053. func GetVersion(expectedStatusCode int) (version.Info, []byte, error) {
  1054. var appVersion version.Info
  1055. var body []byte
  1056. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(versionPath), nil, "", getDefaultToken())
  1057. if err != nil {
  1058. return appVersion, body, err
  1059. }
  1060. defer resp.Body.Close()
  1061. err = checkResponse(resp.StatusCode, expectedStatusCode)
  1062. if err == nil && expectedStatusCode == http.StatusOK {
  1063. err = render.DecodeJSON(resp.Body, &appVersion)
  1064. } else {
  1065. body, _ = getResponseBody(resp)
  1066. }
  1067. return appVersion, body, err
  1068. }
  1069. // GetStatus returns the server status
  1070. func GetStatus(expectedStatusCode int) (httpd.ServicesStatus, []byte, error) {
  1071. var response httpd.ServicesStatus
  1072. var body []byte
  1073. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(serverStatusPath), nil, "", getDefaultToken())
  1074. if err != nil {
  1075. return response, body, err
  1076. }
  1077. defer resp.Body.Close()
  1078. err = checkResponse(resp.StatusCode, expectedStatusCode)
  1079. if err == nil && (expectedStatusCode == http.StatusOK) {
  1080. err = render.DecodeJSON(resp.Body, &response)
  1081. } else {
  1082. body, _ = getResponseBody(resp)
  1083. }
  1084. return response, body, err
  1085. }
  1086. // GetDefenderHosts returns hosts that are banned or for which some violations have been detected
  1087. func GetDefenderHosts(expectedStatusCode int) ([]dataprovider.DefenderEntry, []byte, error) {
  1088. var response []dataprovider.DefenderEntry
  1089. var body []byte
  1090. url, err := url.Parse(buildURLRelativeToBase(defenderHosts))
  1091. if err != nil {
  1092. return response, body, err
  1093. }
  1094. resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "", getDefaultToken())
  1095. if err != nil {
  1096. return response, body, err
  1097. }
  1098. defer resp.Body.Close()
  1099. err = checkResponse(resp.StatusCode, expectedStatusCode)
  1100. if err == nil && expectedStatusCode == http.StatusOK {
  1101. err = render.DecodeJSON(resp.Body, &response)
  1102. } else {
  1103. body, _ = getResponseBody(resp)
  1104. }
  1105. return response, body, err
  1106. }
  1107. // GetDefenderHostByIP returns the host with the given IP, if it exists
  1108. func GetDefenderHostByIP(ip string, expectedStatusCode int) (dataprovider.DefenderEntry, []byte, error) {
  1109. var host dataprovider.DefenderEntry
  1110. var body []byte
  1111. id := hex.EncodeToString([]byte(ip))
  1112. resp, err := sendHTTPRequest(http.MethodGet, buildURLRelativeToBase(defenderHosts, id),
  1113. nil, "", getDefaultToken())
  1114. if err != nil {
  1115. return host, body, err
  1116. }
  1117. defer resp.Body.Close()
  1118. err = checkResponse(resp.StatusCode, expectedStatusCode)
  1119. if err == nil && expectedStatusCode == http.StatusOK {
  1120. err = render.DecodeJSON(resp.Body, &host)
  1121. } else {
  1122. body, _ = getResponseBody(resp)
  1123. }
  1124. return host, body, err
  1125. }
  1126. // RemoveDefenderHostByIP removes the host with the given IP from the defender list
  1127. func RemoveDefenderHostByIP(ip string, expectedStatusCode int) ([]byte, error) {
  1128. var body []byte
  1129. id := hex.EncodeToString([]byte(ip))
  1130. resp, err := sendHTTPRequest(http.MethodDelete, buildURLRelativeToBase(defenderHosts, id), nil, "", getDefaultToken())
  1131. if err != nil {
  1132. return body, err
  1133. }
  1134. defer resp.Body.Close()
  1135. body, _ = getResponseBody(resp)
  1136. return body, checkResponse(resp.StatusCode, expectedStatusCode)
  1137. }
  1138. // Dumpdata requests a backup to outputFile.
  1139. // outputFile is relative to the configured backups_path
  1140. func Dumpdata(outputFile, outputData, indent string, expectedStatusCode int) (map[string]any, []byte, error) {
  1141. var response map[string]any
  1142. var body []byte
  1143. url, err := url.Parse(buildURLRelativeToBase(dumpDataPath))
  1144. if err != nil {
  1145. return response, body, err
  1146. }
  1147. q := url.Query()
  1148. if outputData != "" {
  1149. q.Add("output-data", outputData)
  1150. }
  1151. if outputFile != "" {
  1152. q.Add("output-file", outputFile)
  1153. }
  1154. if indent != "" {
  1155. q.Add("indent", indent)
  1156. }
  1157. url.RawQuery = q.Encode()
  1158. resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "", getDefaultToken())
  1159. if err != nil {
  1160. return response, body, err
  1161. }
  1162. defer resp.Body.Close()
  1163. err = checkResponse(resp.StatusCode, expectedStatusCode)
  1164. if err == nil && expectedStatusCode == http.StatusOK {
  1165. err = render.DecodeJSON(resp.Body, &response)
  1166. } else {
  1167. body, _ = getResponseBody(resp)
  1168. }
  1169. return response, body, err
  1170. }
  1171. // Loaddata restores a backup.
  1172. func Loaddata(inputFile, scanQuota, mode string, expectedStatusCode int) (map[string]any, []byte, error) {
  1173. var response map[string]any
  1174. var body []byte
  1175. url, err := url.Parse(buildURLRelativeToBase(loadDataPath))
  1176. if err != nil {
  1177. return response, body, err
  1178. }
  1179. q := url.Query()
  1180. q.Add("input-file", inputFile)
  1181. if scanQuota != "" {
  1182. q.Add("scan-quota", scanQuota)
  1183. }
  1184. if mode != "" {
  1185. q.Add("mode", mode)
  1186. }
  1187. url.RawQuery = q.Encode()
  1188. resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "", getDefaultToken())
  1189. if err != nil {
  1190. return response, body, err
  1191. }
  1192. defer resp.Body.Close()
  1193. err = checkResponse(resp.StatusCode, expectedStatusCode)
  1194. if err == nil && expectedStatusCode == http.StatusOK {
  1195. err = render.DecodeJSON(resp.Body, &response)
  1196. } else {
  1197. body, _ = getResponseBody(resp)
  1198. }
  1199. return response, body, err
  1200. }
  1201. // LoaddataFromPostBody restores a backup
  1202. func LoaddataFromPostBody(data []byte, scanQuota, mode string, expectedStatusCode int) (map[string]any, []byte, error) {
  1203. var response map[string]any
  1204. var body []byte
  1205. url, err := url.Parse(buildURLRelativeToBase(loadDataPath))
  1206. if err != nil {
  1207. return response, body, err
  1208. }
  1209. q := url.Query()
  1210. if scanQuota != "" {
  1211. q.Add("scan-quota", scanQuota)
  1212. }
  1213. if mode != "" {
  1214. q.Add("mode", mode)
  1215. }
  1216. url.RawQuery = q.Encode()
  1217. resp, err := sendHTTPRequest(http.MethodPost, url.String(), bytes.NewReader(data), "", getDefaultToken())
  1218. if err != nil {
  1219. return response, body, err
  1220. }
  1221. defer resp.Body.Close()
  1222. err = checkResponse(resp.StatusCode, expectedStatusCode)
  1223. if err == nil && expectedStatusCode == http.StatusOK {
  1224. err = render.DecodeJSON(resp.Body, &response)
  1225. } else {
  1226. body, _ = getResponseBody(resp)
  1227. }
  1228. return response, body, err
  1229. }
  1230. func checkResponse(actual int, expected int) error {
  1231. if expected != actual {
  1232. return fmt.Errorf("wrong status code: got %v want %v", actual, expected)
  1233. }
  1234. return nil
  1235. }
  1236. func getResponseBody(resp *http.Response) ([]byte, error) {
  1237. return io.ReadAll(resp.Body)
  1238. }
  1239. func checkEventAction(expected, actual dataprovider.BaseEventAction) error {
  1240. if expected.ID <= 0 {
  1241. if actual.ID <= 0 {
  1242. return errors.New("actual action ID must be > 0")
  1243. }
  1244. } else {
  1245. if actual.ID != expected.ID {
  1246. return errors.New("action ID mismatch")
  1247. }
  1248. }
  1249. if dataprovider.ConvertName(expected.Name) != actual.Name {
  1250. return errors.New("name mismatch")
  1251. }
  1252. if expected.Description != actual.Description {
  1253. return errors.New("description mismatch")
  1254. }
  1255. if expected.Type != actual.Type {
  1256. return errors.New("type mismatch")
  1257. }
  1258. if err := compareEventActionCmdConfigFields(expected.Options.CmdConfig, actual.Options.CmdConfig); err != nil {
  1259. return err
  1260. }
  1261. if err := compareEventActionEmailConfigFields(expected.Options.EmailConfig, actual.Options.EmailConfig); err != nil {
  1262. return err
  1263. }
  1264. return compareEventActionHTTPConfigFields(expected.Options.HTTPConfig, actual.Options.HTTPConfig)
  1265. }
  1266. func checkEventSchedules(expected, actual []dataprovider.Schedule) error {
  1267. if len(expected) != len(actual) {
  1268. return errors.New("schedules mismatch")
  1269. }
  1270. for _, ex := range expected {
  1271. found := false
  1272. for _, ac := range actual {
  1273. if ac.DayOfMonth == ex.DayOfMonth && ac.DayOfWeek == ex.DayOfWeek && ac.Hours == ex.Hours && ac.Month == ex.Month {
  1274. found = true
  1275. break
  1276. }
  1277. }
  1278. if !found {
  1279. return errors.New("schedules content mismatch")
  1280. }
  1281. }
  1282. return nil
  1283. }
  1284. func compareConditionPatternOptions(expected, actual []dataprovider.ConditionPattern) error {
  1285. if len(expected) != len(actual) {
  1286. return errors.New("condition pattern mismatch")
  1287. }
  1288. for _, ex := range expected {
  1289. found := false
  1290. for _, ac := range actual {
  1291. if ac.Pattern == ex.Pattern && ac.InverseMatch == ex.InverseMatch {
  1292. found = true
  1293. break
  1294. }
  1295. }
  1296. if !found {
  1297. return errors.New("condition pattern content mismatch")
  1298. }
  1299. }
  1300. return nil
  1301. }
  1302. func checkEventConditionOptions(expected, actual dataprovider.ConditionOptions) error {
  1303. if err := compareConditionPatternOptions(expected.Names, actual.Names); err != nil {
  1304. return errors.New("condition names mismatch")
  1305. }
  1306. if err := compareConditionPatternOptions(expected.FsPaths, actual.FsPaths); err != nil {
  1307. return errors.New("condition fs_paths mismatch")
  1308. }
  1309. if len(expected.Protocols) != len(actual.Protocols) {
  1310. return errors.New("condition protocols mismatch")
  1311. }
  1312. for _, v := range expected.Protocols {
  1313. if !util.Contains(actual.Protocols, v) {
  1314. return errors.New("condition protocols content mismatch")
  1315. }
  1316. }
  1317. if len(expected.ProviderObjects) != len(actual.ProviderObjects) {
  1318. return errors.New("condition provider objects mismatch")
  1319. }
  1320. for _, v := range expected.ProviderObjects {
  1321. if !util.Contains(actual.ProviderObjects, v) {
  1322. return errors.New("condition provider objects content mismatch")
  1323. }
  1324. }
  1325. if expected.MinFileSize != actual.MinFileSize {
  1326. return errors.New("condition min file size mismatch")
  1327. }
  1328. if expected.MaxFileSize != actual.MaxFileSize {
  1329. return errors.New("condition max file size mismatch")
  1330. }
  1331. return nil
  1332. }
  1333. func checkEventConditions(expected, actual dataprovider.EventConditions) error {
  1334. if len(expected.FsEvents) != len(actual.FsEvents) {
  1335. return errors.New("fs events mismatch")
  1336. }
  1337. for _, v := range expected.FsEvents {
  1338. if !util.Contains(actual.FsEvents, v) {
  1339. return errors.New("fs events content mismatch")
  1340. }
  1341. }
  1342. if len(expected.ProviderEvents) != len(actual.ProviderEvents) {
  1343. return errors.New("provider events mismatch")
  1344. }
  1345. for _, v := range expected.ProviderEvents {
  1346. if !util.Contains(actual.ProviderEvents, v) {
  1347. return errors.New("provider events content mismatch")
  1348. }
  1349. }
  1350. if err := checkEventConditionOptions(expected.Options, actual.Options); err != nil {
  1351. return err
  1352. }
  1353. return checkEventSchedules(expected.Schedules, actual.Schedules)
  1354. }
  1355. func checkEventRuleActions(expected, actual []dataprovider.EventAction) error {
  1356. if len(expected) != len(actual) {
  1357. return errors.New("actions mismatch")
  1358. }
  1359. for _, ex := range expected {
  1360. found := false
  1361. for _, ac := range actual {
  1362. if ex.Name == ac.Name && ex.Order == ac.Order && ex.Options.ExecuteSync == ac.Options.ExecuteSync &&
  1363. ex.Options.IsFailureAction == ac.Options.IsFailureAction && ex.Options.StopOnFailure == ac.Options.StopOnFailure {
  1364. found = true
  1365. break
  1366. }
  1367. }
  1368. if !found {
  1369. return errors.New("actions contents mismatch")
  1370. }
  1371. }
  1372. return nil
  1373. }
  1374. func checkEventRule(expected, actual dataprovider.EventRule) error {
  1375. if expected.ID <= 0 {
  1376. if actual.ID <= 0 {
  1377. return errors.New("actual group ID must be > 0")
  1378. }
  1379. } else {
  1380. if actual.ID != expected.ID {
  1381. return errors.New("group ID mismatch")
  1382. }
  1383. }
  1384. if dataprovider.ConvertName(expected.Name) != actual.Name {
  1385. return errors.New("name mismatch")
  1386. }
  1387. if expected.Description != actual.Description {
  1388. return errors.New("description mismatch")
  1389. }
  1390. if actual.CreatedAt == 0 {
  1391. return errors.New("created_at unset")
  1392. }
  1393. if actual.UpdatedAt == 0 {
  1394. return errors.New("updated_at unset")
  1395. }
  1396. if expected.Trigger != actual.Trigger {
  1397. return errors.New("trigger mismatch")
  1398. }
  1399. if err := checkEventConditions(expected.Conditions, actual.Conditions); err != nil {
  1400. return err
  1401. }
  1402. return checkEventRuleActions(expected.Actions, actual.Actions)
  1403. }
  1404. func checkGroup(expected, actual dataprovider.Group) error {
  1405. if expected.ID <= 0 {
  1406. if actual.ID <= 0 {
  1407. return errors.New("actual group ID must be > 0")
  1408. }
  1409. } else {
  1410. if actual.ID != expected.ID {
  1411. return errors.New("group ID mismatch")
  1412. }
  1413. }
  1414. if dataprovider.ConvertName(expected.Name) != actual.Name {
  1415. return errors.New("name mismatch")
  1416. }
  1417. if expected.Description != actual.Description {
  1418. return errors.New("description mismatch")
  1419. }
  1420. if actual.CreatedAt == 0 {
  1421. return errors.New("created_at unset")
  1422. }
  1423. if actual.UpdatedAt == 0 {
  1424. return errors.New("updated_at unset")
  1425. }
  1426. if err := compareEqualGroupSettingsFields(expected.UserSettings.BaseGroupUserSettings,
  1427. actual.UserSettings.BaseGroupUserSettings); err != nil {
  1428. return err
  1429. }
  1430. if err := compareVirtualFolders(expected.VirtualFolders, actual.VirtualFolders); err != nil {
  1431. return err
  1432. }
  1433. if err := compareUserFilters(expected.UserSettings.Filters, actual.UserSettings.Filters); err != nil {
  1434. return err
  1435. }
  1436. return compareFsConfig(&expected.UserSettings.FsConfig, &actual.UserSettings.FsConfig)
  1437. }
  1438. func checkFolder(expected *vfs.BaseVirtualFolder, actual *vfs.BaseVirtualFolder) error {
  1439. if expected.ID <= 0 {
  1440. if actual.ID <= 0 {
  1441. return errors.New("actual folder ID must be > 0")
  1442. }
  1443. } else {
  1444. if actual.ID != expected.ID {
  1445. return errors.New("folder ID mismatch")
  1446. }
  1447. }
  1448. if dataprovider.ConvertName(expected.Name) != actual.Name {
  1449. return errors.New("name mismatch")
  1450. }
  1451. if expected.MappedPath != actual.MappedPath {
  1452. return errors.New("mapped path mismatch")
  1453. }
  1454. if expected.Description != actual.Description {
  1455. return errors.New("description mismatch")
  1456. }
  1457. return compareFsConfig(&expected.FsConfig, &actual.FsConfig)
  1458. }
  1459. func checkAPIKey(expected, actual *dataprovider.APIKey) error {
  1460. if actual.Key != "" {
  1461. return errors.New("key must not be visible")
  1462. }
  1463. if actual.KeyID == "" {
  1464. return errors.New("actual key_id cannot be empty")
  1465. }
  1466. if expected.Name != actual.Name {
  1467. return errors.New("name mismatch")
  1468. }
  1469. if expected.Scope != actual.Scope {
  1470. return errors.New("scope mismatch")
  1471. }
  1472. if actual.CreatedAt == 0 {
  1473. return errors.New("created_at cannot be 0")
  1474. }
  1475. if actual.UpdatedAt == 0 {
  1476. return errors.New("updated_at cannot be 0")
  1477. }
  1478. if expected.ExpiresAt != actual.ExpiresAt {
  1479. return errors.New("expires_at mismatch")
  1480. }
  1481. if expected.Description != actual.Description {
  1482. return errors.New("description mismatch")
  1483. }
  1484. if expected.User != actual.User {
  1485. return errors.New("user mismatch")
  1486. }
  1487. if expected.Admin != actual.Admin {
  1488. return errors.New("admin mismatch")
  1489. }
  1490. return nil
  1491. }
  1492. func checkAdmin(expected, actual *dataprovider.Admin) error {
  1493. if actual.Password != "" {
  1494. return errors.New("admin password must not be visible")
  1495. }
  1496. if expected.ID <= 0 {
  1497. if actual.ID <= 0 {
  1498. return errors.New("actual admin ID must be > 0")
  1499. }
  1500. } else {
  1501. if actual.ID != expected.ID {
  1502. return errors.New("admin ID mismatch")
  1503. }
  1504. }
  1505. if expected.CreatedAt > 0 {
  1506. if expected.CreatedAt != actual.CreatedAt {
  1507. return fmt.Errorf("created_at mismatch %v != %v", expected.CreatedAt, actual.CreatedAt)
  1508. }
  1509. }
  1510. if err := compareAdminEqualFields(expected, actual); err != nil {
  1511. return err
  1512. }
  1513. if len(expected.Permissions) != len(actual.Permissions) {
  1514. return errors.New("permissions mismatch")
  1515. }
  1516. for _, p := range expected.Permissions {
  1517. if !util.Contains(actual.Permissions, p) {
  1518. return errors.New("permissions content mismatch")
  1519. }
  1520. }
  1521. if expected.Filters.AllowAPIKeyAuth != actual.Filters.AllowAPIKeyAuth {
  1522. return errors.New("allow_api_key_auth mismatch")
  1523. }
  1524. if len(expected.Filters.AllowList) != len(actual.Filters.AllowList) {
  1525. return errors.New("allow list mismatch")
  1526. }
  1527. for _, v := range expected.Filters.AllowList {
  1528. if !util.Contains(actual.Filters.AllowList, v) {
  1529. return errors.New("allow list content mismatch")
  1530. }
  1531. }
  1532. return nil
  1533. }
  1534. func compareAdminEqualFields(expected *dataprovider.Admin, actual *dataprovider.Admin) error {
  1535. if dataprovider.ConvertName(expected.Username) != actual.Username {
  1536. return errors.New("sername mismatch")
  1537. }
  1538. if expected.Email != actual.Email {
  1539. return errors.New("email mismatch")
  1540. }
  1541. if expected.Status != actual.Status {
  1542. return errors.New("status mismatch")
  1543. }
  1544. if expected.Description != actual.Description {
  1545. return errors.New("description mismatch")
  1546. }
  1547. if expected.AdditionalInfo != actual.AdditionalInfo {
  1548. return errors.New("additional info mismatch")
  1549. }
  1550. return nil
  1551. }
  1552. func checkUser(expected *dataprovider.User, actual *dataprovider.User) error {
  1553. if actual.Password != "" {
  1554. return errors.New("user password must not be visible")
  1555. }
  1556. if expected.ID <= 0 {
  1557. if actual.ID <= 0 {
  1558. return errors.New("actual user ID must be > 0")
  1559. }
  1560. } else {
  1561. if actual.ID != expected.ID {
  1562. return errors.New("user ID mismatch")
  1563. }
  1564. }
  1565. if expected.CreatedAt > 0 {
  1566. if expected.CreatedAt != actual.CreatedAt {
  1567. return fmt.Errorf("created_at mismatch %v != %v", expected.CreatedAt, actual.CreatedAt)
  1568. }
  1569. }
  1570. if expected.Email != actual.Email {
  1571. return errors.New("email mismatch")
  1572. }
  1573. if err := compareUserPermissions(expected.Permissions, actual.Permissions); err != nil {
  1574. return err
  1575. }
  1576. if err := compareUserFilters(expected.Filters.BaseUserFilters, actual.Filters.BaseUserFilters); err != nil {
  1577. return err
  1578. }
  1579. if err := compareFsConfig(&expected.FsConfig, &actual.FsConfig); err != nil {
  1580. return err
  1581. }
  1582. if err := compareUserGroups(expected, actual); err != nil {
  1583. return err
  1584. }
  1585. if err := compareVirtualFolders(expected.VirtualFolders, actual.VirtualFolders); err != nil {
  1586. return err
  1587. }
  1588. return compareEqualsUserFields(expected, actual)
  1589. }
  1590. func compareUserPermissions(expected map[string][]string, actual map[string][]string) error {
  1591. if len(expected) != len(actual) {
  1592. return errors.New("permissions mismatch")
  1593. }
  1594. for dir, perms := range expected {
  1595. if actualPerms, ok := actual[dir]; ok {
  1596. for _, v := range actualPerms {
  1597. if !util.Contains(perms, v) {
  1598. return errors.New("permissions contents mismatch")
  1599. }
  1600. }
  1601. } else {
  1602. return errors.New("permissions directories mismatch")
  1603. }
  1604. }
  1605. return nil
  1606. }
  1607. func compareUserGroups(expected *dataprovider.User, actual *dataprovider.User) error {
  1608. if len(actual.Groups) != len(expected.Groups) {
  1609. return errors.New("groups len mismatch")
  1610. }
  1611. for _, g := range actual.Groups {
  1612. found := false
  1613. for _, g1 := range expected.Groups {
  1614. if g1.Name == g.Name {
  1615. found = true
  1616. if g1.Type != g.Type {
  1617. return fmt.Errorf("type mismatch for group %s", g.Name)
  1618. }
  1619. }
  1620. }
  1621. if !found {
  1622. return errors.New("groups mismatch")
  1623. }
  1624. }
  1625. return nil
  1626. }
  1627. func compareVirtualFolders(expected []vfs.VirtualFolder, actual []vfs.VirtualFolder) error {
  1628. if len(actual) != len(expected) {
  1629. return errors.New("virtual folders len mismatch")
  1630. }
  1631. for _, v := range actual {
  1632. found := false
  1633. for _, v1 := range expected {
  1634. if path.Clean(v.VirtualPath) == path.Clean(v1.VirtualPath) {
  1635. if err := checkFolder(&v1.BaseVirtualFolder, &v.BaseVirtualFolder); err != nil {
  1636. return err
  1637. }
  1638. if v.QuotaSize != v1.QuotaSize {
  1639. return errors.New("vfolder quota size mismatch")
  1640. }
  1641. if (v.QuotaFiles) != (v1.QuotaFiles) {
  1642. return errors.New("vfolder quota files mismatch")
  1643. }
  1644. found = true
  1645. break
  1646. }
  1647. }
  1648. if !found {
  1649. return errors.New("virtual folders mismatch")
  1650. }
  1651. }
  1652. return nil
  1653. }
  1654. func compareFsConfig(expected *vfs.Filesystem, actual *vfs.Filesystem) error {
  1655. if expected.Provider != actual.Provider {
  1656. return errors.New("fs provider mismatch")
  1657. }
  1658. if err := compareS3Config(expected, actual); err != nil {
  1659. return err
  1660. }
  1661. if err := compareGCSConfig(expected, actual); err != nil {
  1662. return err
  1663. }
  1664. if err := compareAzBlobConfig(expected, actual); err != nil {
  1665. return err
  1666. }
  1667. if err := checkEncryptedSecret(expected.CryptConfig.Passphrase, actual.CryptConfig.Passphrase); err != nil {
  1668. return err
  1669. }
  1670. if err := compareSFTPFsConfig(expected, actual); err != nil {
  1671. return err
  1672. }
  1673. return compareHTTPFsConfig(expected, actual)
  1674. }
  1675. func compareS3Config(expected *vfs.Filesystem, actual *vfs.Filesystem) error { //nolint:gocyclo
  1676. if expected.S3Config.Bucket != actual.S3Config.Bucket {
  1677. return errors.New("fs S3 bucket mismatch")
  1678. }
  1679. if expected.S3Config.Region != actual.S3Config.Region {
  1680. return errors.New("fs S3 region mismatch")
  1681. }
  1682. if expected.S3Config.AccessKey != actual.S3Config.AccessKey {
  1683. return errors.New("fs S3 access key mismatch")
  1684. }
  1685. if expected.S3Config.RoleARN != actual.S3Config.RoleARN {
  1686. return errors.New("fs S3 role ARN mismatch")
  1687. }
  1688. if err := checkEncryptedSecret(expected.S3Config.AccessSecret, actual.S3Config.AccessSecret); err != nil {
  1689. return fmt.Errorf("fs S3 access secret mismatch: %v", err)
  1690. }
  1691. if expected.S3Config.Endpoint != actual.S3Config.Endpoint {
  1692. return errors.New("fs S3 endpoint mismatch")
  1693. }
  1694. if expected.S3Config.StorageClass != actual.S3Config.StorageClass {
  1695. return errors.New("fs S3 storage class mismatch")
  1696. }
  1697. if expected.S3Config.ACL != actual.S3Config.ACL {
  1698. return errors.New("fs S3 ACL mismatch")
  1699. }
  1700. if expected.S3Config.UploadPartSize != actual.S3Config.UploadPartSize {
  1701. return errors.New("fs S3 upload part size mismatch")
  1702. }
  1703. if expected.S3Config.UploadConcurrency != actual.S3Config.UploadConcurrency {
  1704. return errors.New("fs S3 upload concurrency mismatch")
  1705. }
  1706. if expected.S3Config.DownloadPartSize != actual.S3Config.DownloadPartSize {
  1707. return errors.New("fs S3 download part size mismatch")
  1708. }
  1709. if expected.S3Config.DownloadConcurrency != actual.S3Config.DownloadConcurrency {
  1710. return errors.New("fs S3 download concurrency mismatch")
  1711. }
  1712. if expected.S3Config.ForcePathStyle != actual.S3Config.ForcePathStyle {
  1713. return errors.New("fs S3 force path style mismatch")
  1714. }
  1715. if expected.S3Config.DownloadPartMaxTime != actual.S3Config.DownloadPartMaxTime {
  1716. return errors.New("fs S3 download part max time mismatch")
  1717. }
  1718. if expected.S3Config.UploadPartMaxTime != actual.S3Config.UploadPartMaxTime {
  1719. return errors.New("fs S3 upload part max time mismatch")
  1720. }
  1721. if expected.S3Config.KeyPrefix != actual.S3Config.KeyPrefix &&
  1722. expected.S3Config.KeyPrefix+"/" != actual.S3Config.KeyPrefix {
  1723. return errors.New("fs S3 key prefix mismatch")
  1724. }
  1725. return nil
  1726. }
  1727. func compareGCSConfig(expected *vfs.Filesystem, actual *vfs.Filesystem) error {
  1728. if expected.GCSConfig.Bucket != actual.GCSConfig.Bucket {
  1729. return errors.New("GCS bucket mismatch")
  1730. }
  1731. if expected.GCSConfig.StorageClass != actual.GCSConfig.StorageClass {
  1732. return errors.New("GCS storage class mismatch")
  1733. }
  1734. if expected.GCSConfig.ACL != actual.GCSConfig.ACL {
  1735. return errors.New("GCS ACL mismatch")
  1736. }
  1737. if expected.GCSConfig.KeyPrefix != actual.GCSConfig.KeyPrefix &&
  1738. expected.GCSConfig.KeyPrefix+"/" != actual.GCSConfig.KeyPrefix {
  1739. return errors.New("GCS key prefix mismatch")
  1740. }
  1741. if expected.GCSConfig.AutomaticCredentials != actual.GCSConfig.AutomaticCredentials {
  1742. return errors.New("GCS automatic credentials mismatch")
  1743. }
  1744. return nil
  1745. }
  1746. func compareHTTPFsConfig(expected *vfs.Filesystem, actual *vfs.Filesystem) error {
  1747. if expected.HTTPConfig.Endpoint != actual.HTTPConfig.Endpoint {
  1748. return errors.New("HTTPFs endpoint mismatch")
  1749. }
  1750. if expected.HTTPConfig.Username != actual.HTTPConfig.Username {
  1751. return errors.New("HTTPFs username mismatch")
  1752. }
  1753. if expected.HTTPConfig.SkipTLSVerify != actual.HTTPConfig.SkipTLSVerify {
  1754. return errors.New("HTTPFs skip_tls_verify mismatch")
  1755. }
  1756. if err := checkEncryptedSecret(expected.HTTPConfig.Password, actual.HTTPConfig.Password); err != nil {
  1757. return fmt.Errorf("HTTPFs password mismatch: %v", err)
  1758. }
  1759. if err := checkEncryptedSecret(expected.HTTPConfig.APIKey, actual.HTTPConfig.APIKey); err != nil {
  1760. return fmt.Errorf("HTTPFs API key mismatch: %v", err)
  1761. }
  1762. return nil
  1763. }
  1764. func compareSFTPFsConfig(expected *vfs.Filesystem, actual *vfs.Filesystem) error {
  1765. if expected.SFTPConfig.Endpoint != actual.SFTPConfig.Endpoint {
  1766. return errors.New("SFTPFs endpoint mismatch")
  1767. }
  1768. if expected.SFTPConfig.Username != actual.SFTPConfig.Username {
  1769. return errors.New("SFTPFs username mismatch")
  1770. }
  1771. if expected.SFTPConfig.DisableCouncurrentReads != actual.SFTPConfig.DisableCouncurrentReads {
  1772. return errors.New("SFTPFs disable_concurrent_reads mismatch")
  1773. }
  1774. if expected.SFTPConfig.BufferSize != actual.SFTPConfig.BufferSize {
  1775. return errors.New("SFTPFs buffer_size mismatch")
  1776. }
  1777. if err := checkEncryptedSecret(expected.SFTPConfig.Password, actual.SFTPConfig.Password); err != nil {
  1778. return fmt.Errorf("SFTPFs password mismatch: %v", err)
  1779. }
  1780. if err := checkEncryptedSecret(expected.SFTPConfig.PrivateKey, actual.SFTPConfig.PrivateKey); err != nil {
  1781. return fmt.Errorf("SFTPFs private key mismatch: %v", err)
  1782. }
  1783. if err := checkEncryptedSecret(expected.SFTPConfig.KeyPassphrase, actual.SFTPConfig.KeyPassphrase); err != nil {
  1784. return fmt.Errorf("SFTPFs private key passphrase mismatch: %v", err)
  1785. }
  1786. if expected.SFTPConfig.Prefix != actual.SFTPConfig.Prefix {
  1787. if expected.SFTPConfig.Prefix != "" && actual.SFTPConfig.Prefix != "/" {
  1788. return errors.New("SFTPFs prefix mismatch")
  1789. }
  1790. }
  1791. if len(expected.SFTPConfig.Fingerprints) != len(actual.SFTPConfig.Fingerprints) {
  1792. return errors.New("SFTPFs fingerprints mismatch")
  1793. }
  1794. for _, value := range actual.SFTPConfig.Fingerprints {
  1795. if !util.Contains(expected.SFTPConfig.Fingerprints, value) {
  1796. return errors.New("SFTPFs fingerprints mismatch")
  1797. }
  1798. }
  1799. return nil
  1800. }
  1801. func compareAzBlobConfig(expected *vfs.Filesystem, actual *vfs.Filesystem) error {
  1802. if expected.AzBlobConfig.Container != actual.AzBlobConfig.Container {
  1803. return errors.New("azure Blob container mismatch")
  1804. }
  1805. if expected.AzBlobConfig.AccountName != actual.AzBlobConfig.AccountName {
  1806. return errors.New("azure Blob account name mismatch")
  1807. }
  1808. if err := checkEncryptedSecret(expected.AzBlobConfig.AccountKey, actual.AzBlobConfig.AccountKey); err != nil {
  1809. return fmt.Errorf("azure Blob account key mismatch: %v", err)
  1810. }
  1811. if expected.AzBlobConfig.Endpoint != actual.AzBlobConfig.Endpoint {
  1812. return errors.New("azure Blob endpoint mismatch")
  1813. }
  1814. if err := checkEncryptedSecret(expected.AzBlobConfig.SASURL, actual.AzBlobConfig.SASURL); err != nil {
  1815. return fmt.Errorf("azure Blob SAS URL mismatch: %v", err)
  1816. }
  1817. if expected.AzBlobConfig.UploadPartSize != actual.AzBlobConfig.UploadPartSize {
  1818. return errors.New("azure Blob upload part size mismatch")
  1819. }
  1820. if expected.AzBlobConfig.UploadConcurrency != actual.AzBlobConfig.UploadConcurrency {
  1821. return errors.New("azure Blob upload concurrency mismatch")
  1822. }
  1823. if expected.AzBlobConfig.DownloadPartSize != actual.AzBlobConfig.DownloadPartSize {
  1824. return errors.New("azure Blob download part size mismatch")
  1825. }
  1826. if expected.AzBlobConfig.DownloadConcurrency != actual.AzBlobConfig.DownloadConcurrency {
  1827. return errors.New("azure Blob download concurrency mismatch")
  1828. }
  1829. if expected.AzBlobConfig.KeyPrefix != actual.AzBlobConfig.KeyPrefix &&
  1830. expected.AzBlobConfig.KeyPrefix+"/" != actual.AzBlobConfig.KeyPrefix {
  1831. return errors.New("azure Blob key prefix mismatch")
  1832. }
  1833. if expected.AzBlobConfig.UseEmulator != actual.AzBlobConfig.UseEmulator {
  1834. return errors.New("azure Blob use emulator mismatch")
  1835. }
  1836. if expected.AzBlobConfig.AccessTier != actual.AzBlobConfig.AccessTier {
  1837. return errors.New("azure Blob access tier mismatch")
  1838. }
  1839. return nil
  1840. }
  1841. func areSecretEquals(expected, actual *kms.Secret) bool {
  1842. if expected == nil && actual == nil {
  1843. return true
  1844. }
  1845. if expected != nil && expected.IsEmpty() && actual == nil {
  1846. return true
  1847. }
  1848. if actual != nil && actual.IsEmpty() && expected == nil {
  1849. return true
  1850. }
  1851. return false
  1852. }
  1853. func checkEncryptedSecret(expected, actual *kms.Secret) error {
  1854. if areSecretEquals(expected, actual) {
  1855. return nil
  1856. }
  1857. if expected == nil && actual != nil && !actual.IsEmpty() {
  1858. return errors.New("secret mismatch")
  1859. }
  1860. if actual == nil && expected != nil && !expected.IsEmpty() {
  1861. return errors.New("secret mismatch")
  1862. }
  1863. if expected.IsPlain() && actual.IsEncrypted() {
  1864. if actual.GetPayload() == "" {
  1865. return errors.New("invalid secret payload")
  1866. }
  1867. if actual.GetAdditionalData() != "" {
  1868. return errors.New("invalid secret additional data")
  1869. }
  1870. if actual.GetKey() != "" {
  1871. return errors.New("invalid secret key")
  1872. }
  1873. } else {
  1874. if expected.GetStatus() != actual.GetStatus() || expected.GetPayload() != actual.GetPayload() {
  1875. return errors.New("secret mismatch")
  1876. }
  1877. }
  1878. return nil
  1879. }
  1880. func compareUserFilterSubStructs(expected sdk.BaseUserFilters, actual sdk.BaseUserFilters) error {
  1881. for _, IPMask := range expected.AllowedIP {
  1882. if !util.Contains(actual.AllowedIP, IPMask) {
  1883. return errors.New("allowed IP contents mismatch")
  1884. }
  1885. }
  1886. for _, IPMask := range expected.DeniedIP {
  1887. if !util.Contains(actual.DeniedIP, IPMask) {
  1888. return errors.New("denied IP contents mismatch")
  1889. }
  1890. }
  1891. for _, method := range expected.DeniedLoginMethods {
  1892. if !util.Contains(actual.DeniedLoginMethods, method) {
  1893. return errors.New("denied login methods contents mismatch")
  1894. }
  1895. }
  1896. for _, protocol := range expected.DeniedProtocols {
  1897. if !util.Contains(actual.DeniedProtocols, protocol) {
  1898. return errors.New("denied protocols contents mismatch")
  1899. }
  1900. }
  1901. for _, options := range expected.WebClient {
  1902. if !util.Contains(actual.WebClient, options) {
  1903. return errors.New("web client options contents mismatch")
  1904. }
  1905. }
  1906. return compareUserFiltersEqualFields(expected, actual)
  1907. }
  1908. func compareUserFiltersEqualFields(expected sdk.BaseUserFilters, actual sdk.BaseUserFilters) error {
  1909. if expected.Hooks.ExternalAuthDisabled != actual.Hooks.ExternalAuthDisabled {
  1910. return errors.New("external_auth_disabled hook mismatch")
  1911. }
  1912. if expected.Hooks.PreLoginDisabled != actual.Hooks.PreLoginDisabled {
  1913. return errors.New("pre_login_disabled hook mismatch")
  1914. }
  1915. if expected.Hooks.CheckPasswordDisabled != actual.Hooks.CheckPasswordDisabled {
  1916. return errors.New("check_password_disabled hook mismatch")
  1917. }
  1918. if expected.DisableFsChecks != actual.DisableFsChecks {
  1919. return errors.New("disable_fs_checks mismatch")
  1920. }
  1921. if expected.StartDirectory != actual.StartDirectory {
  1922. return errors.New("start_directory mismatch")
  1923. }
  1924. return nil
  1925. }
  1926. func compareUserFilters(expected sdk.BaseUserFilters, actual sdk.BaseUserFilters) error {
  1927. if len(expected.AllowedIP) != len(actual.AllowedIP) {
  1928. return errors.New("allowed IP mismatch")
  1929. }
  1930. if len(expected.DeniedIP) != len(actual.DeniedIP) {
  1931. return errors.New("denied IP mismatch")
  1932. }
  1933. if len(expected.DeniedLoginMethods) != len(actual.DeniedLoginMethods) {
  1934. return errors.New("denied login methods mismatch")
  1935. }
  1936. if len(expected.DeniedProtocols) != len(actual.DeniedProtocols) {
  1937. return errors.New("denied protocols mismatch")
  1938. }
  1939. if expected.MaxUploadFileSize != actual.MaxUploadFileSize {
  1940. return errors.New("max upload file size mismatch")
  1941. }
  1942. if expected.TLSUsername != actual.TLSUsername {
  1943. return errors.New("TLSUsername mismatch")
  1944. }
  1945. if len(expected.WebClient) != len(actual.WebClient) {
  1946. return errors.New("WebClient filter mismatch")
  1947. }
  1948. if expected.AllowAPIKeyAuth != actual.AllowAPIKeyAuth {
  1949. return errors.New("allow_api_key_auth mismatch")
  1950. }
  1951. if expected.ExternalAuthCacheTime != actual.ExternalAuthCacheTime {
  1952. return errors.New("external_auth_cache_time mismatch")
  1953. }
  1954. if expected.FTPSecurity != actual.FTPSecurity {
  1955. return errors.New("ftp_security mismatch")
  1956. }
  1957. if expected.IsAnonymous != actual.IsAnonymous {
  1958. return errors.New("is_anonymous mismatch")
  1959. }
  1960. if err := compareUserFilterSubStructs(expected, actual); err != nil {
  1961. return err
  1962. }
  1963. if err := compareUserBandwidthLimitFilters(expected, actual); err != nil {
  1964. return err
  1965. }
  1966. if err := compareUserDataTransferLimitFilters(expected, actual); err != nil {
  1967. return err
  1968. }
  1969. return compareUserFilePatternsFilters(expected, actual)
  1970. }
  1971. func checkFilterMatch(expected []string, actual []string) bool {
  1972. if len(expected) != len(actual) {
  1973. return false
  1974. }
  1975. for _, e := range expected {
  1976. if !util.Contains(actual, strings.ToLower(e)) {
  1977. return false
  1978. }
  1979. }
  1980. return true
  1981. }
  1982. func compareUserDataTransferLimitFilters(expected sdk.BaseUserFilters, actual sdk.BaseUserFilters) error {
  1983. if len(expected.DataTransferLimits) != len(actual.DataTransferLimits) {
  1984. return errors.New("data transfer limits filters mismatch")
  1985. }
  1986. for idx, l := range expected.DataTransferLimits {
  1987. if actual.DataTransferLimits[idx].UploadDataTransfer != l.UploadDataTransfer {
  1988. return errors.New("data transfer limit upload_data_transfer mismatch")
  1989. }
  1990. if actual.DataTransferLimits[idx].DownloadDataTransfer != l.DownloadDataTransfer {
  1991. return errors.New("data transfer limit download_data_transfer mismatch")
  1992. }
  1993. if actual.DataTransferLimits[idx].TotalDataTransfer != l.TotalDataTransfer {
  1994. return errors.New("data transfer limit total_data_transfer mismatch")
  1995. }
  1996. for _, source := range actual.DataTransferLimits[idx].Sources {
  1997. if !util.Contains(l.Sources, source) {
  1998. return errors.New("data transfer limit source mismatch")
  1999. }
  2000. }
  2001. }
  2002. return nil
  2003. }
  2004. func compareUserBandwidthLimitFilters(expected sdk.BaseUserFilters, actual sdk.BaseUserFilters) error {
  2005. if len(expected.BandwidthLimits) != len(actual.BandwidthLimits) {
  2006. return errors.New("bandwidth limits filters mismatch")
  2007. }
  2008. for idx, l := range expected.BandwidthLimits {
  2009. if actual.BandwidthLimits[idx].UploadBandwidth != l.UploadBandwidth {
  2010. return errors.New("bandwidth filters upload_bandwidth mismatch")
  2011. }
  2012. if actual.BandwidthLimits[idx].DownloadBandwidth != l.DownloadBandwidth {
  2013. return errors.New("bandwidth filters download_bandwidth mismatch")
  2014. }
  2015. if len(actual.BandwidthLimits[idx].Sources) != len(l.Sources) {
  2016. return errors.New("bandwidth filters sources mismatch")
  2017. }
  2018. for _, source := range actual.BandwidthLimits[idx].Sources {
  2019. if !util.Contains(l.Sources, source) {
  2020. return errors.New("bandwidth filters source mismatch")
  2021. }
  2022. }
  2023. }
  2024. return nil
  2025. }
  2026. func compareUserFilePatternsFilters(expected sdk.BaseUserFilters, actual sdk.BaseUserFilters) error {
  2027. if len(expected.FilePatterns) != len(actual.FilePatterns) {
  2028. return errors.New("file patterns mismatch")
  2029. }
  2030. for _, f := range expected.FilePatterns {
  2031. found := false
  2032. for _, f1 := range actual.FilePatterns {
  2033. if path.Clean(f.Path) == path.Clean(f1.Path) && f.DenyPolicy == f1.DenyPolicy {
  2034. if !checkFilterMatch(f.AllowedPatterns, f1.AllowedPatterns) ||
  2035. !checkFilterMatch(f.DeniedPatterns, f1.DeniedPatterns) {
  2036. return errors.New("file patterns contents mismatch")
  2037. }
  2038. found = true
  2039. }
  2040. }
  2041. if !found {
  2042. return errors.New("file patterns contents mismatch")
  2043. }
  2044. }
  2045. return nil
  2046. }
  2047. func compareKeyValues(expected, actual []dataprovider.KeyValue) error {
  2048. if len(expected) != len(actual) {
  2049. return errors.New("kay values mismatch")
  2050. }
  2051. for _, ex := range expected {
  2052. found := false
  2053. for _, ac := range actual {
  2054. if ac.Key == ex.Key && ac.Value == ex.Value {
  2055. found = true
  2056. break
  2057. }
  2058. }
  2059. if !found {
  2060. return errors.New("kay values mismatch")
  2061. }
  2062. }
  2063. return nil
  2064. }
  2065. func compareEventActionHTTPConfigFields(expected, actual dataprovider.EventActionHTTPConfig) error {
  2066. if expected.Endpoint != actual.Endpoint {
  2067. return errors.New("http endpoint mismatch")
  2068. }
  2069. if expected.Username != actual.Username {
  2070. return errors.New("http username mismatch")
  2071. }
  2072. if err := checkEncryptedSecret(expected.Password, actual.Password); err != nil {
  2073. return err
  2074. }
  2075. if err := compareKeyValues(expected.Headers, actual.Headers); err != nil {
  2076. return errors.New("http headers mismatch")
  2077. }
  2078. if expected.Timeout != actual.Timeout {
  2079. return errors.New("http timeout mismatch")
  2080. }
  2081. if expected.SkipTLSVerify != actual.SkipTLSVerify {
  2082. return errors.New("http skip TLS verify mismatch")
  2083. }
  2084. if expected.Method != actual.Method {
  2085. return errors.New("http method mismatch")
  2086. }
  2087. if err := compareKeyValues(expected.QueryParameters, actual.QueryParameters); err != nil {
  2088. return errors.New("http query parameters mismatch")
  2089. }
  2090. if expected.Body != actual.Body {
  2091. return errors.New("http body mismatch")
  2092. }
  2093. return nil
  2094. }
  2095. func compareEventActionEmailConfigFields(expected, actual dataprovider.EventActionEmailConfig) error {
  2096. if len(expected.Recipients) != len(actual.Recipients) {
  2097. return errors.New("email recipients mismatch")
  2098. }
  2099. for _, v := range expected.Recipients {
  2100. if !util.Contains(actual.Recipients, v) {
  2101. return errors.New("email recipients content mismatch")
  2102. }
  2103. }
  2104. if expected.Subject != actual.Subject {
  2105. return errors.New("email subject mismatch")
  2106. }
  2107. if expected.Body != actual.Body {
  2108. return errors.New("email body mismatch")
  2109. }
  2110. return nil
  2111. }
  2112. func compareEventActionCmdConfigFields(expected, actual dataprovider.EventActionCommandConfig) error {
  2113. if expected.Cmd != actual.Cmd {
  2114. return errors.New("command mismatch")
  2115. }
  2116. if expected.Timeout != actual.Timeout {
  2117. return errors.New("cmd timeout mismatch")
  2118. }
  2119. if err := compareKeyValues(expected.EnvVars, actual.EnvVars); err != nil {
  2120. return errors.New("cmd env vars mismatch")
  2121. }
  2122. return nil
  2123. }
  2124. func compareEqualGroupSettingsFields(expected sdk.BaseGroupUserSettings, actual sdk.BaseGroupUserSettings) error {
  2125. if expected.HomeDir != actual.HomeDir {
  2126. return errors.New("home dir mismatch")
  2127. }
  2128. if expected.MaxSessions != actual.MaxSessions {
  2129. return errors.New("MaxSessions mismatch")
  2130. }
  2131. if expected.QuotaSize != actual.QuotaSize {
  2132. return errors.New("QuotaSize mismatch")
  2133. }
  2134. if expected.QuotaFiles != actual.QuotaFiles {
  2135. return errors.New("QuotaFiles mismatch")
  2136. }
  2137. if expected.UploadBandwidth != actual.UploadBandwidth {
  2138. return errors.New("UploadBandwidth mismatch")
  2139. }
  2140. if expected.DownloadBandwidth != actual.DownloadBandwidth {
  2141. return errors.New("DownloadBandwidth mismatch")
  2142. }
  2143. if expected.UploadDataTransfer != actual.UploadDataTransfer {
  2144. return errors.New("upload_data_transfer mismatch")
  2145. }
  2146. if expected.DownloadDataTransfer != actual.DownloadDataTransfer {
  2147. return errors.New("download_data_transfer mismatch")
  2148. }
  2149. if expected.TotalDataTransfer != actual.TotalDataTransfer {
  2150. return errors.New("total_data_transfer mismatch")
  2151. }
  2152. return compareUserPermissions(expected.Permissions, actual.Permissions)
  2153. }
  2154. func compareEqualsUserFields(expected *dataprovider.User, actual *dataprovider.User) error {
  2155. if dataprovider.ConvertName(expected.Username) != actual.Username {
  2156. return errors.New("username mismatch")
  2157. }
  2158. if expected.HomeDir != actual.HomeDir {
  2159. return errors.New("home dir mismatch")
  2160. }
  2161. if expected.UID != actual.UID {
  2162. return errors.New("UID mismatch")
  2163. }
  2164. if expected.GID != actual.GID {
  2165. return errors.New("GID mismatch")
  2166. }
  2167. if expected.MaxSessions != actual.MaxSessions {
  2168. return errors.New("MaxSessions mismatch")
  2169. }
  2170. if len(expected.Permissions) != len(actual.Permissions) {
  2171. return errors.New("permissions mismatch")
  2172. }
  2173. if expected.UploadBandwidth != actual.UploadBandwidth {
  2174. return errors.New("UploadBandwidth mismatch")
  2175. }
  2176. if expected.DownloadBandwidth != actual.DownloadBandwidth {
  2177. return errors.New("DownloadBandwidth mismatch")
  2178. }
  2179. if expected.Status != actual.Status {
  2180. return errors.New("status mismatch")
  2181. }
  2182. if expected.ExpirationDate != actual.ExpirationDate {
  2183. return errors.New("ExpirationDate mismatch")
  2184. }
  2185. if expected.AdditionalInfo != actual.AdditionalInfo {
  2186. return errors.New("AdditionalInfo mismatch")
  2187. }
  2188. if expected.Description != actual.Description {
  2189. return errors.New("description mismatch")
  2190. }
  2191. return compareQuotaUserFields(expected, actual)
  2192. }
  2193. func compareQuotaUserFields(expected *dataprovider.User, actual *dataprovider.User) error {
  2194. if expected.QuotaSize != actual.QuotaSize {
  2195. return errors.New("QuotaSize mismatch")
  2196. }
  2197. if expected.QuotaFiles != actual.QuotaFiles {
  2198. return errors.New("QuotaFiles mismatch")
  2199. }
  2200. if expected.UploadDataTransfer != actual.UploadDataTransfer {
  2201. return errors.New("upload_data_transfer mismatch")
  2202. }
  2203. if expected.DownloadDataTransfer != actual.DownloadDataTransfer {
  2204. return errors.New("download_data_transfer mismatch")
  2205. }
  2206. if expected.TotalDataTransfer != actual.TotalDataTransfer {
  2207. return errors.New("total_data_transfer mismatch")
  2208. }
  2209. return nil
  2210. }
  2211. func addLimitAndOffsetQueryParams(rawurl string, limit, offset int64) (*url.URL, error) {
  2212. url, err := url.Parse(rawurl)
  2213. if err != nil {
  2214. return nil, err
  2215. }
  2216. q := url.Query()
  2217. if limit > 0 {
  2218. q.Add("limit", strconv.FormatInt(limit, 10))
  2219. }
  2220. if offset > 0 {
  2221. q.Add("offset", strconv.FormatInt(offset, 10))
  2222. }
  2223. url.RawQuery = q.Encode()
  2224. return url, err
  2225. }
  2226. func addModeQueryParam(rawurl, mode string) (*url.URL, error) {
  2227. url, err := url.Parse(rawurl)
  2228. if err != nil {
  2229. return nil, err
  2230. }
  2231. q := url.Query()
  2232. if len(mode) > 0 {
  2233. q.Add("mode", mode)
  2234. }
  2235. url.RawQuery = q.Encode()
  2236. return url, err
  2237. }
  2238. func addDisconnectQueryParam(rawurl, disconnect string) (*url.URL, error) {
  2239. url, err := url.Parse(rawurl)
  2240. if err != nil {
  2241. return nil, err
  2242. }
  2243. q := url.Query()
  2244. if len(disconnect) > 0 {
  2245. q.Add("disconnect", disconnect)
  2246. }
  2247. url.RawQuery = q.Encode()
  2248. return url, err
  2249. }