httpdtest.go 90 KB

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