httpdtest.go 95 KB

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