httpdtest.go 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932
  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 := addUpdateUserQueryParams(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, scopes ...string) (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. if len(scopes) > 0 {
  1392. q.Add("scopes", strings.Join(scopes, ","))
  1393. }
  1394. url.RawQuery = q.Encode()
  1395. resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "", getDefaultToken())
  1396. if err != nil {
  1397. return response, body, err
  1398. }
  1399. defer resp.Body.Close()
  1400. err = checkResponse(resp.StatusCode, expectedStatusCode)
  1401. if err == nil && expectedStatusCode == http.StatusOK {
  1402. err = render.DecodeJSON(resp.Body, &response)
  1403. } else {
  1404. body, _ = getResponseBody(resp)
  1405. }
  1406. return response, body, err
  1407. }
  1408. // Loaddata restores a backup.
  1409. func Loaddata(inputFile, scanQuota, mode string, expectedStatusCode int) (map[string]any, []byte, error) {
  1410. var response map[string]any
  1411. var body []byte
  1412. url, err := url.Parse(buildURLRelativeToBase(loadDataPath))
  1413. if err != nil {
  1414. return response, body, err
  1415. }
  1416. q := url.Query()
  1417. q.Add("input-file", inputFile)
  1418. if scanQuota != "" {
  1419. q.Add("scan-quota", scanQuota)
  1420. }
  1421. if mode != "" {
  1422. q.Add("mode", mode)
  1423. }
  1424. url.RawQuery = q.Encode()
  1425. resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "", getDefaultToken())
  1426. if err != nil {
  1427. return response, body, err
  1428. }
  1429. defer resp.Body.Close()
  1430. err = checkResponse(resp.StatusCode, expectedStatusCode)
  1431. if err == nil && expectedStatusCode == http.StatusOK {
  1432. err = render.DecodeJSON(resp.Body, &response)
  1433. } else {
  1434. body, _ = getResponseBody(resp)
  1435. }
  1436. return response, body, err
  1437. }
  1438. // LoaddataFromPostBody restores a backup
  1439. func LoaddataFromPostBody(data []byte, scanQuota, mode string, expectedStatusCode int) (map[string]any, []byte, error) {
  1440. var response map[string]any
  1441. var body []byte
  1442. url, err := url.Parse(buildURLRelativeToBase(loadDataPath))
  1443. if err != nil {
  1444. return response, body, err
  1445. }
  1446. q := url.Query()
  1447. if scanQuota != "" {
  1448. q.Add("scan-quota", scanQuota)
  1449. }
  1450. if mode != "" {
  1451. q.Add("mode", mode)
  1452. }
  1453. url.RawQuery = q.Encode()
  1454. resp, err := sendHTTPRequest(http.MethodPost, url.String(), bytes.NewReader(data), "", getDefaultToken())
  1455. if err != nil {
  1456. return response, body, err
  1457. }
  1458. defer resp.Body.Close()
  1459. err = checkResponse(resp.StatusCode, expectedStatusCode)
  1460. if err == nil && expectedStatusCode == http.StatusOK {
  1461. err = render.DecodeJSON(resp.Body, &response)
  1462. } else {
  1463. body, _ = getResponseBody(resp)
  1464. }
  1465. return response, body, err
  1466. }
  1467. func checkResponse(actual int, expected int) error {
  1468. if expected != actual {
  1469. return fmt.Errorf("wrong status code: got %v want %v", actual, expected)
  1470. }
  1471. return nil
  1472. }
  1473. func getResponseBody(resp *http.Response) ([]byte, error) {
  1474. return io.ReadAll(resp.Body)
  1475. }
  1476. func checkEventAction(expected, actual dataprovider.BaseEventAction) error {
  1477. if expected.ID <= 0 {
  1478. if actual.ID <= 0 {
  1479. return errors.New("actual action ID must be > 0")
  1480. }
  1481. } else {
  1482. if actual.ID != expected.ID {
  1483. return errors.New("action ID mismatch")
  1484. }
  1485. }
  1486. if dataprovider.ConvertName(expected.Name) != actual.Name {
  1487. return errors.New("name mismatch")
  1488. }
  1489. if expected.Description != actual.Description {
  1490. return errors.New("description mismatch")
  1491. }
  1492. if expected.Type != actual.Type {
  1493. return errors.New("type mismatch")
  1494. }
  1495. if expected.Options.PwdExpirationConfig.Threshold != actual.Options.PwdExpirationConfig.Threshold {
  1496. return errors.New("password expiration threshold mismatch")
  1497. }
  1498. if err := compareEventActionIDPConfigFields(expected.Options.IDPConfig, actual.Options.IDPConfig); err != nil {
  1499. return err
  1500. }
  1501. if err := compareEventActionCmdConfigFields(expected.Options.CmdConfig, actual.Options.CmdConfig); err != nil {
  1502. return err
  1503. }
  1504. if err := compareEventActionEmailConfigFields(expected.Options.EmailConfig, actual.Options.EmailConfig); err != nil {
  1505. return err
  1506. }
  1507. if err := compareEventActionDataRetentionFields(expected.Options.RetentionConfig, actual.Options.RetentionConfig); err != nil {
  1508. return err
  1509. }
  1510. if err := compareEventActionFsConfigFields(expected.Options.FsConfig, actual.Options.FsConfig); err != nil {
  1511. return err
  1512. }
  1513. return compareEventActionHTTPConfigFields(expected.Options.HTTPConfig, actual.Options.HTTPConfig)
  1514. }
  1515. func checkEventSchedules(expected, actual []dataprovider.Schedule) error {
  1516. if len(expected) != len(actual) {
  1517. return errors.New("schedules mismatch")
  1518. }
  1519. for _, ex := range expected {
  1520. found := false
  1521. for _, ac := range actual {
  1522. if ac.DayOfMonth == ex.DayOfMonth && ac.DayOfWeek == ex.DayOfWeek && ac.Hours == ex.Hours && ac.Month == ex.Month {
  1523. found = true
  1524. break
  1525. }
  1526. }
  1527. if !found {
  1528. return errors.New("schedules content mismatch")
  1529. }
  1530. }
  1531. return nil
  1532. }
  1533. func compareConditionPatternOptions(expected, actual []dataprovider.ConditionPattern) error {
  1534. if len(expected) != len(actual) {
  1535. return errors.New("condition pattern mismatch")
  1536. }
  1537. for _, ex := range expected {
  1538. found := false
  1539. for _, ac := range actual {
  1540. if ac.Pattern == ex.Pattern && ac.InverseMatch == ex.InverseMatch {
  1541. found = true
  1542. break
  1543. }
  1544. }
  1545. if !found {
  1546. return errors.New("condition pattern content mismatch")
  1547. }
  1548. }
  1549. return nil
  1550. }
  1551. func checkEventConditionOptions(expected, actual dataprovider.ConditionOptions) error {
  1552. if err := compareConditionPatternOptions(expected.Names, actual.Names); err != nil {
  1553. return errors.New("condition names mismatch")
  1554. }
  1555. if err := compareConditionPatternOptions(expected.GroupNames, actual.GroupNames); err != nil {
  1556. return errors.New("condition group names mismatch")
  1557. }
  1558. if err := compareConditionPatternOptions(expected.RoleNames, actual.RoleNames); err != nil {
  1559. return errors.New("condition role names mismatch")
  1560. }
  1561. if err := compareConditionPatternOptions(expected.FsPaths, actual.FsPaths); err != nil {
  1562. return errors.New("condition fs_paths mismatch")
  1563. }
  1564. if len(expected.Protocols) != len(actual.Protocols) {
  1565. return errors.New("condition protocols mismatch")
  1566. }
  1567. for _, v := range expected.Protocols {
  1568. if !util.Contains(actual.Protocols, v) {
  1569. return errors.New("condition protocols content mismatch")
  1570. }
  1571. }
  1572. if len(expected.ProviderObjects) != len(actual.ProviderObjects) {
  1573. return errors.New("condition provider objects mismatch")
  1574. }
  1575. for _, v := range expected.ProviderObjects {
  1576. if !util.Contains(actual.ProviderObjects, v) {
  1577. return errors.New("condition provider objects content mismatch")
  1578. }
  1579. }
  1580. if expected.MinFileSize != actual.MinFileSize {
  1581. return errors.New("condition min file size mismatch")
  1582. }
  1583. if expected.MaxFileSize != actual.MaxFileSize {
  1584. return errors.New("condition max file size mismatch")
  1585. }
  1586. return nil
  1587. }
  1588. func checkEventConditions(expected, actual dataprovider.EventConditions) error {
  1589. if len(expected.FsEvents) != len(actual.FsEvents) {
  1590. return errors.New("fs events mismatch")
  1591. }
  1592. for _, v := range expected.FsEvents {
  1593. if !util.Contains(actual.FsEvents, v) {
  1594. return errors.New("fs events content mismatch")
  1595. }
  1596. }
  1597. if len(expected.ProviderEvents) != len(actual.ProviderEvents) {
  1598. return errors.New("provider events mismatch")
  1599. }
  1600. for _, v := range expected.ProviderEvents {
  1601. if !util.Contains(actual.ProviderEvents, v) {
  1602. return errors.New("provider events content mismatch")
  1603. }
  1604. }
  1605. if err := checkEventConditionOptions(expected.Options, actual.Options); err != nil {
  1606. return err
  1607. }
  1608. if expected.IDPLoginEvent != actual.IDPLoginEvent {
  1609. return errors.New("IDP login event mismatch")
  1610. }
  1611. return checkEventSchedules(expected.Schedules, actual.Schedules)
  1612. }
  1613. func checkEventRuleActions(expected, actual []dataprovider.EventAction) error {
  1614. if len(expected) != len(actual) {
  1615. return errors.New("actions mismatch")
  1616. }
  1617. for _, ex := range expected {
  1618. found := false
  1619. for _, ac := range actual {
  1620. if ex.Name == ac.Name && ex.Order == ac.Order && ex.Options.ExecuteSync == ac.Options.ExecuteSync &&
  1621. ex.Options.IsFailureAction == ac.Options.IsFailureAction && ex.Options.StopOnFailure == ac.Options.StopOnFailure {
  1622. found = true
  1623. break
  1624. }
  1625. }
  1626. if !found {
  1627. return errors.New("actions contents mismatch")
  1628. }
  1629. }
  1630. return nil
  1631. }
  1632. func checkEventRule(expected, actual dataprovider.EventRule) error {
  1633. if expected.ID <= 0 {
  1634. if actual.ID <= 0 {
  1635. return errors.New("actual group ID must be > 0")
  1636. }
  1637. } else {
  1638. if actual.ID != expected.ID {
  1639. return errors.New("group ID mismatch")
  1640. }
  1641. }
  1642. if dataprovider.ConvertName(expected.Name) != actual.Name {
  1643. return errors.New("name mismatch")
  1644. }
  1645. if expected.Status != actual.Status {
  1646. return errors.New("status mismatch")
  1647. }
  1648. if expected.Description != actual.Description {
  1649. return errors.New("description mismatch")
  1650. }
  1651. if actual.CreatedAt == 0 {
  1652. return errors.New("created_at unset")
  1653. }
  1654. if actual.UpdatedAt == 0 {
  1655. return errors.New("updated_at unset")
  1656. }
  1657. if expected.Trigger != actual.Trigger {
  1658. return errors.New("trigger mismatch")
  1659. }
  1660. if err := checkEventConditions(expected.Conditions, actual.Conditions); err != nil {
  1661. return err
  1662. }
  1663. return checkEventRuleActions(expected.Actions, actual.Actions)
  1664. }
  1665. func checkIPListEntry(expected, actual dataprovider.IPListEntry) error {
  1666. if expected.IPOrNet != actual.IPOrNet {
  1667. return errors.New("ipornet mismatch")
  1668. }
  1669. if expected.Description != actual.Description {
  1670. return errors.New("description mismatch")
  1671. }
  1672. if expected.Type != actual.Type {
  1673. return errors.New("type mismatch")
  1674. }
  1675. if expected.Mode != actual.Mode {
  1676. return errors.New("mode mismatch")
  1677. }
  1678. if expected.Protocols != actual.Protocols {
  1679. return errors.New("protocols mismatch")
  1680. }
  1681. if actual.CreatedAt == 0 {
  1682. return errors.New("created_at unset")
  1683. }
  1684. if actual.UpdatedAt == 0 {
  1685. return errors.New("updated_at unset")
  1686. }
  1687. return nil
  1688. }
  1689. func checkRole(expected, actual dataprovider.Role) error {
  1690. if expected.ID <= 0 {
  1691. if actual.ID <= 0 {
  1692. return errors.New("actual role ID must be > 0")
  1693. }
  1694. } else {
  1695. if actual.ID != expected.ID {
  1696. return errors.New("role ID mismatch")
  1697. }
  1698. }
  1699. if dataprovider.ConvertName(expected.Name) != actual.Name {
  1700. return errors.New("name mismatch")
  1701. }
  1702. if expected.Description != actual.Description {
  1703. return errors.New("description mismatch")
  1704. }
  1705. if actual.CreatedAt == 0 {
  1706. return errors.New("created_at unset")
  1707. }
  1708. if actual.UpdatedAt == 0 {
  1709. return errors.New("updated_at unset")
  1710. }
  1711. return nil
  1712. }
  1713. func checkGroup(expected, actual dataprovider.Group) error {
  1714. if expected.ID <= 0 {
  1715. if actual.ID <= 0 {
  1716. return errors.New("actual group ID must be > 0")
  1717. }
  1718. } else {
  1719. if actual.ID != expected.ID {
  1720. return errors.New("group ID mismatch")
  1721. }
  1722. }
  1723. if dataprovider.ConvertName(expected.Name) != actual.Name {
  1724. return errors.New("name mismatch")
  1725. }
  1726. if expected.Description != actual.Description {
  1727. return errors.New("description mismatch")
  1728. }
  1729. if actual.CreatedAt == 0 {
  1730. return errors.New("created_at unset")
  1731. }
  1732. if actual.UpdatedAt == 0 {
  1733. return errors.New("updated_at unset")
  1734. }
  1735. if err := compareEqualGroupSettingsFields(expected.UserSettings.BaseGroupUserSettings,
  1736. actual.UserSettings.BaseGroupUserSettings); err != nil {
  1737. return err
  1738. }
  1739. if err := compareVirtualFolders(expected.VirtualFolders, actual.VirtualFolders); err != nil {
  1740. return err
  1741. }
  1742. if err := compareUserFilters(expected.UserSettings.Filters, actual.UserSettings.Filters); err != nil {
  1743. return err
  1744. }
  1745. return compareFsConfig(&expected.UserSettings.FsConfig, &actual.UserSettings.FsConfig)
  1746. }
  1747. func checkFolder(expected *vfs.BaseVirtualFolder, actual *vfs.BaseVirtualFolder) error {
  1748. if expected.ID <= 0 {
  1749. if actual.ID <= 0 {
  1750. return errors.New("actual folder ID must be > 0")
  1751. }
  1752. } else {
  1753. if actual.ID != expected.ID {
  1754. return errors.New("folder ID mismatch")
  1755. }
  1756. }
  1757. if dataprovider.ConvertName(expected.Name) != actual.Name {
  1758. return errors.New("name mismatch")
  1759. }
  1760. if expected.MappedPath != actual.MappedPath {
  1761. return errors.New("mapped path mismatch")
  1762. }
  1763. if expected.Description != actual.Description {
  1764. return errors.New("description mismatch")
  1765. }
  1766. return compareFsConfig(&expected.FsConfig, &actual.FsConfig)
  1767. }
  1768. func checkAPIKey(expected, actual *dataprovider.APIKey) error {
  1769. if actual.Key != "" {
  1770. return errors.New("key must not be visible")
  1771. }
  1772. if actual.KeyID == "" {
  1773. return errors.New("actual key_id cannot be empty")
  1774. }
  1775. if expected.Name != actual.Name {
  1776. return errors.New("name mismatch")
  1777. }
  1778. if expected.Scope != actual.Scope {
  1779. return errors.New("scope mismatch")
  1780. }
  1781. if actual.CreatedAt == 0 {
  1782. return errors.New("created_at cannot be 0")
  1783. }
  1784. if actual.UpdatedAt == 0 {
  1785. return errors.New("updated_at cannot be 0")
  1786. }
  1787. if expected.ExpiresAt != actual.ExpiresAt {
  1788. return errors.New("expires_at mismatch")
  1789. }
  1790. if expected.Description != actual.Description {
  1791. return errors.New("description mismatch")
  1792. }
  1793. if expected.User != actual.User {
  1794. return errors.New("user mismatch")
  1795. }
  1796. if expected.Admin != actual.Admin {
  1797. return errors.New("admin mismatch")
  1798. }
  1799. return nil
  1800. }
  1801. func checkAdmin(expected, actual *dataprovider.Admin) error {
  1802. if actual.Password != "" {
  1803. return errors.New("admin password must not be visible")
  1804. }
  1805. if expected.ID <= 0 {
  1806. if actual.ID <= 0 {
  1807. return errors.New("actual admin ID must be > 0")
  1808. }
  1809. } else {
  1810. if actual.ID != expected.ID {
  1811. return errors.New("admin ID mismatch")
  1812. }
  1813. }
  1814. if expected.CreatedAt > 0 {
  1815. if expected.CreatedAt != actual.CreatedAt {
  1816. return fmt.Errorf("created_at mismatch %v != %v", expected.CreatedAt, actual.CreatedAt)
  1817. }
  1818. }
  1819. if err := compareAdminEqualFields(expected, actual); err != nil {
  1820. return err
  1821. }
  1822. if len(expected.Permissions) != len(actual.Permissions) {
  1823. return errors.New("permissions mismatch")
  1824. }
  1825. for _, p := range expected.Permissions {
  1826. if !util.Contains(actual.Permissions, p) {
  1827. return errors.New("permissions content mismatch")
  1828. }
  1829. }
  1830. if err := compareAdminFilters(expected.Filters, actual.Filters); err != nil {
  1831. return err
  1832. }
  1833. return compareAdminGroups(expected, actual)
  1834. }
  1835. func compareAdminFilters(expected, actual dataprovider.AdminFilters) error {
  1836. if expected.AllowAPIKeyAuth != actual.AllowAPIKeyAuth {
  1837. return errors.New("allow_api_key_auth mismatch")
  1838. }
  1839. if len(expected.AllowList) != len(actual.AllowList) {
  1840. return errors.New("allow list mismatch")
  1841. }
  1842. for _, v := range expected.AllowList {
  1843. if !util.Contains(actual.AllowList, v) {
  1844. return errors.New("allow list content mismatch")
  1845. }
  1846. }
  1847. if expected.Preferences.HideUserPageSections != actual.Preferences.HideUserPageSections {
  1848. return errors.New("hide user page sections mismatch")
  1849. }
  1850. if expected.Preferences.DefaultUsersExpiration != actual.Preferences.DefaultUsersExpiration {
  1851. return errors.New("default users expiration mismatch")
  1852. }
  1853. return nil
  1854. }
  1855. func compareAdminEqualFields(expected *dataprovider.Admin, actual *dataprovider.Admin) error {
  1856. if dataprovider.ConvertName(expected.Username) != actual.Username {
  1857. return errors.New("sername mismatch")
  1858. }
  1859. if expected.Email != actual.Email {
  1860. return errors.New("email mismatch")
  1861. }
  1862. if expected.Status != actual.Status {
  1863. return errors.New("status mismatch")
  1864. }
  1865. if expected.Description != actual.Description {
  1866. return errors.New("description mismatch")
  1867. }
  1868. if expected.AdditionalInfo != actual.AdditionalInfo {
  1869. return errors.New("additional info mismatch")
  1870. }
  1871. if expected.Role != actual.Role {
  1872. return errors.New("role mismatch")
  1873. }
  1874. return nil
  1875. }
  1876. func checkUser(expected *dataprovider.User, actual *dataprovider.User) error {
  1877. if actual.Password != "" {
  1878. return errors.New("user password must not be visible")
  1879. }
  1880. if expected.ID <= 0 {
  1881. if actual.ID <= 0 {
  1882. return errors.New("actual user ID must be > 0")
  1883. }
  1884. } else {
  1885. if actual.ID != expected.ID {
  1886. return errors.New("user ID mismatch")
  1887. }
  1888. }
  1889. if expected.CreatedAt > 0 {
  1890. if expected.CreatedAt != actual.CreatedAt {
  1891. return fmt.Errorf("created_at mismatch %v != %v", expected.CreatedAt, actual.CreatedAt)
  1892. }
  1893. }
  1894. if expected.Email != actual.Email {
  1895. return errors.New("email mismatch")
  1896. }
  1897. if expected.Filters.RequirePasswordChange != actual.Filters.RequirePasswordChange {
  1898. return errors.New("require_password_change mismatch")
  1899. }
  1900. if err := compareUserPermissions(expected.Permissions, actual.Permissions); err != nil {
  1901. return err
  1902. }
  1903. if err := compareUserFilters(expected.Filters.BaseUserFilters, actual.Filters.BaseUserFilters); err != nil {
  1904. return err
  1905. }
  1906. if err := compareFsConfig(&expected.FsConfig, &actual.FsConfig); err != nil {
  1907. return err
  1908. }
  1909. if err := compareUserGroups(expected, actual); err != nil {
  1910. return err
  1911. }
  1912. if err := compareVirtualFolders(expected.VirtualFolders, actual.VirtualFolders); err != nil {
  1913. return err
  1914. }
  1915. return compareEqualsUserFields(expected, actual)
  1916. }
  1917. func compareUserPermissions(expected map[string][]string, actual map[string][]string) error {
  1918. if len(expected) != len(actual) {
  1919. return errors.New("permissions mismatch")
  1920. }
  1921. for dir, perms := range expected {
  1922. if actualPerms, ok := actual[dir]; ok {
  1923. for _, v := range actualPerms {
  1924. if !util.Contains(perms, v) {
  1925. return errors.New("permissions contents mismatch")
  1926. }
  1927. }
  1928. } else {
  1929. return errors.New("permissions directories mismatch")
  1930. }
  1931. }
  1932. return nil
  1933. }
  1934. func compareAdminGroups(expected *dataprovider.Admin, actual *dataprovider.Admin) error {
  1935. if len(actual.Groups) != len(expected.Groups) {
  1936. return errors.New("groups len mismatch")
  1937. }
  1938. for _, g := range actual.Groups {
  1939. found := false
  1940. for _, g1 := range expected.Groups {
  1941. if g1.Name == g.Name {
  1942. found = true
  1943. if g1.Options.AddToUsersAs != g.Options.AddToUsersAs {
  1944. return fmt.Errorf("add to users as field mismatch for group %s", g.Name)
  1945. }
  1946. }
  1947. }
  1948. if !found {
  1949. return errors.New("groups mismatch")
  1950. }
  1951. }
  1952. return nil
  1953. }
  1954. func compareUserGroups(expected *dataprovider.User, actual *dataprovider.User) error {
  1955. if len(actual.Groups) != len(expected.Groups) {
  1956. return errors.New("groups len mismatch")
  1957. }
  1958. for _, g := range actual.Groups {
  1959. found := false
  1960. for _, g1 := range expected.Groups {
  1961. if g1.Name == g.Name {
  1962. found = true
  1963. if g1.Type != g.Type {
  1964. return fmt.Errorf("type mismatch for group %s", g.Name)
  1965. }
  1966. }
  1967. }
  1968. if !found {
  1969. return errors.New("groups mismatch")
  1970. }
  1971. }
  1972. return nil
  1973. }
  1974. func compareVirtualFolders(expected []vfs.VirtualFolder, actual []vfs.VirtualFolder) error {
  1975. if len(actual) != len(expected) {
  1976. return errors.New("virtual folders len mismatch")
  1977. }
  1978. for _, v := range actual {
  1979. found := false
  1980. for _, v1 := range expected {
  1981. if path.Clean(v.VirtualPath) == path.Clean(v1.VirtualPath) {
  1982. if err := checkFolder(&v1.BaseVirtualFolder, &v.BaseVirtualFolder); err != nil {
  1983. return err
  1984. }
  1985. if v.QuotaSize != v1.QuotaSize {
  1986. return errors.New("vfolder quota size mismatch")
  1987. }
  1988. if (v.QuotaFiles) != (v1.QuotaFiles) {
  1989. return errors.New("vfolder quota files mismatch")
  1990. }
  1991. found = true
  1992. break
  1993. }
  1994. }
  1995. if !found {
  1996. return errors.New("virtual folders mismatch")
  1997. }
  1998. }
  1999. return nil
  2000. }
  2001. func compareFsConfig(expected *vfs.Filesystem, actual *vfs.Filesystem) error {
  2002. if expected.Provider != actual.Provider {
  2003. return errors.New("fs provider mismatch")
  2004. }
  2005. if expected.OSConfig.ReadBufferSize != actual.OSConfig.ReadBufferSize {
  2006. return fmt.Errorf("read buffer size mismatch")
  2007. }
  2008. if expected.OSConfig.WriteBufferSize != actual.OSConfig.WriteBufferSize {
  2009. return fmt.Errorf("write buffer size mismatch")
  2010. }
  2011. if err := compareS3Config(expected, actual); err != nil {
  2012. return err
  2013. }
  2014. if err := compareGCSConfig(expected, actual); err != nil {
  2015. return err
  2016. }
  2017. if err := compareAzBlobConfig(expected, actual); err != nil {
  2018. return err
  2019. }
  2020. if err := checkEncryptedSecret(expected.CryptConfig.Passphrase, actual.CryptConfig.Passphrase); err != nil {
  2021. return err
  2022. }
  2023. if expected.CryptConfig.ReadBufferSize != actual.CryptConfig.ReadBufferSize {
  2024. return fmt.Errorf("crypt read buffer size mismatch")
  2025. }
  2026. if expected.CryptConfig.WriteBufferSize != actual.CryptConfig.WriteBufferSize {
  2027. return fmt.Errorf("crypt write buffer size mismatch")
  2028. }
  2029. if err := compareSFTPFsConfig(expected, actual); err != nil {
  2030. return err
  2031. }
  2032. return compareHTTPFsConfig(expected, actual)
  2033. }
  2034. func compareS3Config(expected *vfs.Filesystem, actual *vfs.Filesystem) error { //nolint:gocyclo
  2035. if expected.S3Config.Bucket != actual.S3Config.Bucket {
  2036. return errors.New("fs S3 bucket mismatch")
  2037. }
  2038. if expected.S3Config.Region != actual.S3Config.Region {
  2039. return errors.New("fs S3 region mismatch")
  2040. }
  2041. if expected.S3Config.AccessKey != actual.S3Config.AccessKey {
  2042. return errors.New("fs S3 access key mismatch")
  2043. }
  2044. if expected.S3Config.RoleARN != actual.S3Config.RoleARN {
  2045. return errors.New("fs S3 role ARN mismatch")
  2046. }
  2047. if err := checkEncryptedSecret(expected.S3Config.AccessSecret, actual.S3Config.AccessSecret); err != nil {
  2048. return fmt.Errorf("fs S3 access secret mismatch: %v", err)
  2049. }
  2050. if expected.S3Config.Endpoint != actual.S3Config.Endpoint {
  2051. return errors.New("fs S3 endpoint mismatch")
  2052. }
  2053. if expected.S3Config.StorageClass != actual.S3Config.StorageClass {
  2054. return errors.New("fs S3 storage class mismatch")
  2055. }
  2056. if expected.S3Config.ACL != actual.S3Config.ACL {
  2057. return errors.New("fs S3 ACL mismatch")
  2058. }
  2059. if expected.S3Config.UploadPartSize != actual.S3Config.UploadPartSize {
  2060. return errors.New("fs S3 upload part size mismatch")
  2061. }
  2062. if expected.S3Config.UploadConcurrency != actual.S3Config.UploadConcurrency {
  2063. return errors.New("fs S3 upload concurrency mismatch")
  2064. }
  2065. if expected.S3Config.DownloadPartSize != actual.S3Config.DownloadPartSize {
  2066. return errors.New("fs S3 download part size mismatch")
  2067. }
  2068. if expected.S3Config.DownloadConcurrency != actual.S3Config.DownloadConcurrency {
  2069. return errors.New("fs S3 download concurrency mismatch")
  2070. }
  2071. if expected.S3Config.ForcePathStyle != actual.S3Config.ForcePathStyle {
  2072. return errors.New("fs S3 force path style mismatch")
  2073. }
  2074. if expected.S3Config.DownloadPartMaxTime != actual.S3Config.DownloadPartMaxTime {
  2075. return errors.New("fs S3 download part max time mismatch")
  2076. }
  2077. if expected.S3Config.UploadPartMaxTime != actual.S3Config.UploadPartMaxTime {
  2078. return errors.New("fs S3 upload part max time mismatch")
  2079. }
  2080. if expected.S3Config.KeyPrefix != actual.S3Config.KeyPrefix &&
  2081. expected.S3Config.KeyPrefix+"/" != actual.S3Config.KeyPrefix {
  2082. return errors.New("fs S3 key prefix mismatch")
  2083. }
  2084. return nil
  2085. }
  2086. func compareGCSConfig(expected *vfs.Filesystem, actual *vfs.Filesystem) error {
  2087. if expected.GCSConfig.Bucket != actual.GCSConfig.Bucket {
  2088. return errors.New("GCS bucket mismatch")
  2089. }
  2090. if expected.GCSConfig.StorageClass != actual.GCSConfig.StorageClass {
  2091. return errors.New("GCS storage class mismatch")
  2092. }
  2093. if expected.GCSConfig.ACL != actual.GCSConfig.ACL {
  2094. return errors.New("GCS ACL mismatch")
  2095. }
  2096. if expected.GCSConfig.KeyPrefix != actual.GCSConfig.KeyPrefix &&
  2097. expected.GCSConfig.KeyPrefix+"/" != actual.GCSConfig.KeyPrefix {
  2098. return errors.New("GCS key prefix mismatch")
  2099. }
  2100. if expected.GCSConfig.AutomaticCredentials != actual.GCSConfig.AutomaticCredentials {
  2101. return errors.New("GCS automatic credentials mismatch")
  2102. }
  2103. if expected.GCSConfig.UploadPartSize != actual.GCSConfig.UploadPartSize {
  2104. return errors.New("GCS upload part size mismatch")
  2105. }
  2106. if expected.GCSConfig.UploadPartMaxTime != actual.GCSConfig.UploadPartMaxTime {
  2107. return errors.New("GCS upload part max time mismatch")
  2108. }
  2109. return nil
  2110. }
  2111. func compareHTTPFsConfig(expected *vfs.Filesystem, actual *vfs.Filesystem) error {
  2112. if expected.HTTPConfig.Endpoint != actual.HTTPConfig.Endpoint {
  2113. return errors.New("HTTPFs endpoint mismatch")
  2114. }
  2115. if expected.HTTPConfig.Username != actual.HTTPConfig.Username {
  2116. return errors.New("HTTPFs username mismatch")
  2117. }
  2118. if expected.HTTPConfig.SkipTLSVerify != actual.HTTPConfig.SkipTLSVerify {
  2119. return errors.New("HTTPFs skip_tls_verify mismatch")
  2120. }
  2121. if expected.SFTPConfig.EqualityCheckMode != actual.SFTPConfig.EqualityCheckMode {
  2122. return errors.New("HTTPFs equality_check_mode mismatch")
  2123. }
  2124. if err := checkEncryptedSecret(expected.HTTPConfig.Password, actual.HTTPConfig.Password); err != nil {
  2125. return fmt.Errorf("HTTPFs password mismatch: %v", err)
  2126. }
  2127. if err := checkEncryptedSecret(expected.HTTPConfig.APIKey, actual.HTTPConfig.APIKey); err != nil {
  2128. return fmt.Errorf("HTTPFs API key mismatch: %v", err)
  2129. }
  2130. return nil
  2131. }
  2132. func compareSFTPFsConfig(expected *vfs.Filesystem, actual *vfs.Filesystem) error {
  2133. if expected.SFTPConfig.Endpoint != actual.SFTPConfig.Endpoint {
  2134. return errors.New("SFTPFs endpoint mismatch")
  2135. }
  2136. if expected.SFTPConfig.Username != actual.SFTPConfig.Username {
  2137. return errors.New("SFTPFs username mismatch")
  2138. }
  2139. if expected.SFTPConfig.DisableCouncurrentReads != actual.SFTPConfig.DisableCouncurrentReads {
  2140. return errors.New("SFTPFs disable_concurrent_reads mismatch")
  2141. }
  2142. if expected.SFTPConfig.BufferSize != actual.SFTPConfig.BufferSize {
  2143. return errors.New("SFTPFs buffer_size mismatch")
  2144. }
  2145. if expected.SFTPConfig.EqualityCheckMode != actual.SFTPConfig.EqualityCheckMode {
  2146. return errors.New("SFTPFs equality_check_mode mismatch")
  2147. }
  2148. if err := checkEncryptedSecret(expected.SFTPConfig.Password, actual.SFTPConfig.Password); err != nil {
  2149. return fmt.Errorf("SFTPFs password mismatch: %v", err)
  2150. }
  2151. if err := checkEncryptedSecret(expected.SFTPConfig.PrivateKey, actual.SFTPConfig.PrivateKey); err != nil {
  2152. return fmt.Errorf("SFTPFs private key mismatch: %v", err)
  2153. }
  2154. if err := checkEncryptedSecret(expected.SFTPConfig.KeyPassphrase, actual.SFTPConfig.KeyPassphrase); err != nil {
  2155. return fmt.Errorf("SFTPFs private key passphrase mismatch: %v", err)
  2156. }
  2157. if expected.SFTPConfig.Prefix != actual.SFTPConfig.Prefix {
  2158. if expected.SFTPConfig.Prefix != "" && actual.SFTPConfig.Prefix != "/" {
  2159. return errors.New("SFTPFs prefix mismatch")
  2160. }
  2161. }
  2162. if len(expected.SFTPConfig.Fingerprints) != len(actual.SFTPConfig.Fingerprints) {
  2163. return errors.New("SFTPFs fingerprints mismatch")
  2164. }
  2165. for _, value := range actual.SFTPConfig.Fingerprints {
  2166. if !util.Contains(expected.SFTPConfig.Fingerprints, value) {
  2167. return errors.New("SFTPFs fingerprints mismatch")
  2168. }
  2169. }
  2170. return nil
  2171. }
  2172. func compareAzBlobConfig(expected *vfs.Filesystem, actual *vfs.Filesystem) error {
  2173. if expected.AzBlobConfig.Container != actual.AzBlobConfig.Container {
  2174. return errors.New("azure Blob container mismatch")
  2175. }
  2176. if expected.AzBlobConfig.AccountName != actual.AzBlobConfig.AccountName {
  2177. return errors.New("azure Blob account name mismatch")
  2178. }
  2179. if err := checkEncryptedSecret(expected.AzBlobConfig.AccountKey, actual.AzBlobConfig.AccountKey); err != nil {
  2180. return fmt.Errorf("azure Blob account key mismatch: %v", err)
  2181. }
  2182. if expected.AzBlobConfig.Endpoint != actual.AzBlobConfig.Endpoint {
  2183. return errors.New("azure Blob endpoint mismatch")
  2184. }
  2185. if err := checkEncryptedSecret(expected.AzBlobConfig.SASURL, actual.AzBlobConfig.SASURL); err != nil {
  2186. return fmt.Errorf("azure Blob SAS URL mismatch: %v", err)
  2187. }
  2188. if expected.AzBlobConfig.UploadPartSize != actual.AzBlobConfig.UploadPartSize {
  2189. return errors.New("azure Blob upload part size mismatch")
  2190. }
  2191. if expected.AzBlobConfig.UploadConcurrency != actual.AzBlobConfig.UploadConcurrency {
  2192. return errors.New("azure Blob upload concurrency mismatch")
  2193. }
  2194. if expected.AzBlobConfig.DownloadPartSize != actual.AzBlobConfig.DownloadPartSize {
  2195. return errors.New("azure Blob download part size mismatch")
  2196. }
  2197. if expected.AzBlobConfig.DownloadConcurrency != actual.AzBlobConfig.DownloadConcurrency {
  2198. return errors.New("azure Blob download concurrency mismatch")
  2199. }
  2200. if expected.AzBlobConfig.KeyPrefix != actual.AzBlobConfig.KeyPrefix &&
  2201. expected.AzBlobConfig.KeyPrefix+"/" != actual.AzBlobConfig.KeyPrefix {
  2202. return errors.New("azure Blob key prefix mismatch")
  2203. }
  2204. if expected.AzBlobConfig.UseEmulator != actual.AzBlobConfig.UseEmulator {
  2205. return errors.New("azure Blob use emulator mismatch")
  2206. }
  2207. if expected.AzBlobConfig.AccessTier != actual.AzBlobConfig.AccessTier {
  2208. return errors.New("azure Blob access tier mismatch")
  2209. }
  2210. return nil
  2211. }
  2212. func areSecretEquals(expected, actual *kms.Secret) bool {
  2213. if expected == nil && actual == nil {
  2214. return true
  2215. }
  2216. if expected != nil && expected.IsEmpty() && actual == nil {
  2217. return true
  2218. }
  2219. if actual != nil && actual.IsEmpty() && expected == nil {
  2220. return true
  2221. }
  2222. return false
  2223. }
  2224. func checkEncryptedSecret(expected, actual *kms.Secret) error {
  2225. if areSecretEquals(expected, actual) {
  2226. return nil
  2227. }
  2228. if expected == nil && actual != nil && !actual.IsEmpty() {
  2229. return errors.New("secret mismatch")
  2230. }
  2231. if actual == nil && expected != nil && !expected.IsEmpty() {
  2232. return errors.New("secret mismatch")
  2233. }
  2234. if expected.IsPlain() && actual.IsEncrypted() {
  2235. if actual.GetPayload() == "" {
  2236. return errors.New("invalid secret payload")
  2237. }
  2238. if actual.GetAdditionalData() != "" {
  2239. return errors.New("invalid secret additional data")
  2240. }
  2241. if actual.GetKey() != "" {
  2242. return errors.New("invalid secret key")
  2243. }
  2244. } else {
  2245. if expected.GetStatus() != actual.GetStatus() || expected.GetPayload() != actual.GetPayload() {
  2246. return errors.New("secret mismatch")
  2247. }
  2248. }
  2249. return nil
  2250. }
  2251. func compareUserFilterSubStructs(expected sdk.BaseUserFilters, actual sdk.BaseUserFilters) error {
  2252. for _, IPMask := range expected.AllowedIP {
  2253. if !util.Contains(actual.AllowedIP, IPMask) {
  2254. return errors.New("allowed IP contents mismatch")
  2255. }
  2256. }
  2257. for _, IPMask := range expected.DeniedIP {
  2258. if !util.Contains(actual.DeniedIP, IPMask) {
  2259. return errors.New("denied IP contents mismatch")
  2260. }
  2261. }
  2262. for _, method := range expected.DeniedLoginMethods {
  2263. if !util.Contains(actual.DeniedLoginMethods, method) {
  2264. return errors.New("denied login methods contents mismatch")
  2265. }
  2266. }
  2267. for _, protocol := range expected.DeniedProtocols {
  2268. if !util.Contains(actual.DeniedProtocols, protocol) {
  2269. return errors.New("denied protocols contents mismatch")
  2270. }
  2271. }
  2272. for _, options := range expected.WebClient {
  2273. if !util.Contains(actual.WebClient, options) {
  2274. return errors.New("web client options contents mismatch")
  2275. }
  2276. }
  2277. return compareUserFiltersEqualFields(expected, actual)
  2278. }
  2279. func compareUserFiltersEqualFields(expected sdk.BaseUserFilters, actual sdk.BaseUserFilters) error {
  2280. if expected.Hooks.ExternalAuthDisabled != actual.Hooks.ExternalAuthDisabled {
  2281. return errors.New("external_auth_disabled hook mismatch")
  2282. }
  2283. if expected.Hooks.PreLoginDisabled != actual.Hooks.PreLoginDisabled {
  2284. return errors.New("pre_login_disabled hook mismatch")
  2285. }
  2286. if expected.Hooks.CheckPasswordDisabled != actual.Hooks.CheckPasswordDisabled {
  2287. return errors.New("check_password_disabled hook mismatch")
  2288. }
  2289. if expected.DisableFsChecks != actual.DisableFsChecks {
  2290. return errors.New("disable_fs_checks mismatch")
  2291. }
  2292. if expected.StartDirectory != actual.StartDirectory {
  2293. return errors.New("start_directory mismatch")
  2294. }
  2295. return nil
  2296. }
  2297. func compareBaseUserFilters(expected sdk.BaseUserFilters, actual sdk.BaseUserFilters) error {
  2298. if len(expected.AllowedIP) != len(actual.AllowedIP) {
  2299. return errors.New("allowed IP mismatch")
  2300. }
  2301. if len(expected.DeniedIP) != len(actual.DeniedIP) {
  2302. return errors.New("denied IP mismatch")
  2303. }
  2304. if len(expected.DeniedLoginMethods) != len(actual.DeniedLoginMethods) {
  2305. return errors.New("denied login methods mismatch")
  2306. }
  2307. if len(expected.DeniedProtocols) != len(actual.DeniedProtocols) {
  2308. return errors.New("denied protocols mismatch")
  2309. }
  2310. if expected.MaxUploadFileSize != actual.MaxUploadFileSize {
  2311. return errors.New("max upload file size mismatch")
  2312. }
  2313. if expected.TLSUsername != actual.TLSUsername {
  2314. return errors.New("TLSUsername mismatch")
  2315. }
  2316. if len(expected.WebClient) != len(actual.WebClient) {
  2317. return errors.New("WebClient filter mismatch")
  2318. }
  2319. if expected.AllowAPIKeyAuth != actual.AllowAPIKeyAuth {
  2320. return errors.New("allow_api_key_auth mismatch")
  2321. }
  2322. if expected.ExternalAuthCacheTime != actual.ExternalAuthCacheTime {
  2323. return errors.New("external_auth_cache_time mismatch")
  2324. }
  2325. if expected.FTPSecurity != actual.FTPSecurity {
  2326. return errors.New("ftp_security mismatch")
  2327. }
  2328. if expected.IsAnonymous != actual.IsAnonymous {
  2329. return errors.New("is_anonymous mismatch")
  2330. }
  2331. if expected.DefaultSharesExpiration != actual.DefaultSharesExpiration {
  2332. return errors.New("default_shares_expiration mismatch")
  2333. }
  2334. if expected.PasswordExpiration != actual.PasswordExpiration {
  2335. return errors.New("password_expiration mismatch")
  2336. }
  2337. if expected.PasswordStrength != actual.PasswordStrength {
  2338. return errors.New("password_strength mismatch")
  2339. }
  2340. return nil
  2341. }
  2342. func compareUserFilters(expected sdk.BaseUserFilters, actual sdk.BaseUserFilters) error {
  2343. if err := compareBaseUserFilters(expected, actual); err != nil {
  2344. return err
  2345. }
  2346. if err := compareUserFilterSubStructs(expected, actual); err != nil {
  2347. return err
  2348. }
  2349. if err := compareUserBandwidthLimitFilters(expected, actual); err != nil {
  2350. return err
  2351. }
  2352. if err := compareUserDataTransferLimitFilters(expected, actual); err != nil {
  2353. return err
  2354. }
  2355. return compareUserFilePatternsFilters(expected, actual)
  2356. }
  2357. func checkFilterMatch(expected []string, actual []string) bool {
  2358. if len(expected) != len(actual) {
  2359. return false
  2360. }
  2361. for _, e := range expected {
  2362. if !util.Contains(actual, strings.ToLower(e)) {
  2363. return false
  2364. }
  2365. }
  2366. return true
  2367. }
  2368. func compareUserDataTransferLimitFilters(expected sdk.BaseUserFilters, actual sdk.BaseUserFilters) error {
  2369. if len(expected.DataTransferLimits) != len(actual.DataTransferLimits) {
  2370. return errors.New("data transfer limits filters mismatch")
  2371. }
  2372. for idx, l := range expected.DataTransferLimits {
  2373. if actual.DataTransferLimits[idx].UploadDataTransfer != l.UploadDataTransfer {
  2374. return errors.New("data transfer limit upload_data_transfer mismatch")
  2375. }
  2376. if actual.DataTransferLimits[idx].DownloadDataTransfer != l.DownloadDataTransfer {
  2377. return errors.New("data transfer limit download_data_transfer mismatch")
  2378. }
  2379. if actual.DataTransferLimits[idx].TotalDataTransfer != l.TotalDataTransfer {
  2380. return errors.New("data transfer limit total_data_transfer mismatch")
  2381. }
  2382. for _, source := range actual.DataTransferLimits[idx].Sources {
  2383. if !util.Contains(l.Sources, source) {
  2384. return errors.New("data transfer limit source mismatch")
  2385. }
  2386. }
  2387. }
  2388. return nil
  2389. }
  2390. func compareUserBandwidthLimitFilters(expected sdk.BaseUserFilters, actual sdk.BaseUserFilters) error {
  2391. if len(expected.BandwidthLimits) != len(actual.BandwidthLimits) {
  2392. return errors.New("bandwidth limits filters mismatch")
  2393. }
  2394. for idx, l := range expected.BandwidthLimits {
  2395. if actual.BandwidthLimits[idx].UploadBandwidth != l.UploadBandwidth {
  2396. return errors.New("bandwidth filters upload_bandwidth mismatch")
  2397. }
  2398. if actual.BandwidthLimits[idx].DownloadBandwidth != l.DownloadBandwidth {
  2399. return errors.New("bandwidth filters download_bandwidth mismatch")
  2400. }
  2401. if len(actual.BandwidthLimits[idx].Sources) != len(l.Sources) {
  2402. return errors.New("bandwidth filters sources mismatch")
  2403. }
  2404. for _, source := range actual.BandwidthLimits[idx].Sources {
  2405. if !util.Contains(l.Sources, source) {
  2406. return errors.New("bandwidth filters source mismatch")
  2407. }
  2408. }
  2409. }
  2410. return nil
  2411. }
  2412. func compareUserFilePatternsFilters(expected sdk.BaseUserFilters, actual sdk.BaseUserFilters) error {
  2413. if len(expected.FilePatterns) != len(actual.FilePatterns) {
  2414. return errors.New("file patterns mismatch")
  2415. }
  2416. for _, f := range expected.FilePatterns {
  2417. found := false
  2418. for _, f1 := range actual.FilePatterns {
  2419. if path.Clean(f.Path) == path.Clean(f1.Path) && f.DenyPolicy == f1.DenyPolicy {
  2420. if !checkFilterMatch(f.AllowedPatterns, f1.AllowedPatterns) ||
  2421. !checkFilterMatch(f.DeniedPatterns, f1.DeniedPatterns) {
  2422. return errors.New("file patterns contents mismatch")
  2423. }
  2424. found = true
  2425. }
  2426. }
  2427. if !found {
  2428. return errors.New("file patterns contents mismatch")
  2429. }
  2430. }
  2431. return nil
  2432. }
  2433. func compareKeyValues(expected, actual []dataprovider.KeyValue) error {
  2434. if len(expected) != len(actual) {
  2435. return errors.New("kay values mismatch")
  2436. }
  2437. for _, ex := range expected {
  2438. found := false
  2439. for _, ac := range actual {
  2440. if ac.Key == ex.Key && ac.Value == ex.Value {
  2441. found = true
  2442. break
  2443. }
  2444. }
  2445. if !found {
  2446. return errors.New("kay values mismatch")
  2447. }
  2448. }
  2449. return nil
  2450. }
  2451. func compareHTTPparts(expected, actual []dataprovider.HTTPPart) error {
  2452. for _, p1 := range expected {
  2453. found := false
  2454. for _, p2 := range actual {
  2455. if p1.Name == p2.Name {
  2456. found = true
  2457. if err := compareKeyValues(p1.Headers, p2.Headers); err != nil {
  2458. return fmt.Errorf("http headers mismatch for part %q", p1.Name)
  2459. }
  2460. if p1.Body != p2.Body || p1.Filepath != p2.Filepath {
  2461. return fmt.Errorf("http part %q mismatch", p1.Name)
  2462. }
  2463. }
  2464. }
  2465. if !found {
  2466. return fmt.Errorf("expected http part %q not found", p1.Name)
  2467. }
  2468. }
  2469. return nil
  2470. }
  2471. func compareEventActionHTTPConfigFields(expected, actual dataprovider.EventActionHTTPConfig) error {
  2472. if expected.Endpoint != actual.Endpoint {
  2473. return errors.New("http endpoint mismatch")
  2474. }
  2475. if expected.Username != actual.Username {
  2476. return errors.New("http username mismatch")
  2477. }
  2478. if err := checkEncryptedSecret(expected.Password, actual.Password); err != nil {
  2479. return err
  2480. }
  2481. if err := compareKeyValues(expected.Headers, actual.Headers); err != nil {
  2482. return errors.New("http headers mismatch")
  2483. }
  2484. if expected.Timeout != actual.Timeout {
  2485. return errors.New("http timeout mismatch")
  2486. }
  2487. if expected.SkipTLSVerify != actual.SkipTLSVerify {
  2488. return errors.New("http skip TLS verify mismatch")
  2489. }
  2490. if expected.Method != actual.Method {
  2491. return errors.New("http method mismatch")
  2492. }
  2493. if err := compareKeyValues(expected.QueryParameters, actual.QueryParameters); err != nil {
  2494. return errors.New("http query parameters mismatch")
  2495. }
  2496. if expected.Body != actual.Body {
  2497. return errors.New("http body mismatch")
  2498. }
  2499. if len(expected.Parts) != len(actual.Parts) {
  2500. return errors.New("http parts mismatch")
  2501. }
  2502. return compareHTTPparts(expected.Parts, actual.Parts)
  2503. }
  2504. func compareEventActionEmailConfigFields(expected, actual dataprovider.EventActionEmailConfig) error {
  2505. if len(expected.Recipients) != len(actual.Recipients) {
  2506. return errors.New("email recipients mismatch")
  2507. }
  2508. for _, v := range expected.Recipients {
  2509. if !util.Contains(actual.Recipients, v) {
  2510. return errors.New("email recipients content mismatch")
  2511. }
  2512. }
  2513. if expected.Subject != actual.Subject {
  2514. return errors.New("email subject mismatch")
  2515. }
  2516. if expected.ContentType != actual.ContentType {
  2517. return errors.New("email content type mismatch")
  2518. }
  2519. if expected.Body != actual.Body {
  2520. return errors.New("email body mismatch")
  2521. }
  2522. if len(expected.Attachments) != len(actual.Attachments) {
  2523. return errors.New("email attachments mismatch")
  2524. }
  2525. for _, v := range expected.Attachments {
  2526. if !util.Contains(actual.Attachments, v) {
  2527. return errors.New("email attachments content mismatch")
  2528. }
  2529. }
  2530. return nil
  2531. }
  2532. func compareEventActionFsCompressFields(expected, actual dataprovider.EventActionFsCompress) error {
  2533. if expected.Name != actual.Name {
  2534. return errors.New("fs compress name mismatch")
  2535. }
  2536. if len(expected.Paths) != len(actual.Paths) {
  2537. return errors.New("fs compress paths mismatch")
  2538. }
  2539. for _, v := range expected.Paths {
  2540. if !util.Contains(actual.Paths, v) {
  2541. return errors.New("fs compress paths content mismatch")
  2542. }
  2543. }
  2544. return nil
  2545. }
  2546. func compareEventActionFsConfigFields(expected, actual dataprovider.EventActionFilesystemConfig) error {
  2547. if expected.Type != actual.Type {
  2548. return errors.New("fs type mismatch")
  2549. }
  2550. if err := compareKeyValues(expected.Renames, actual.Renames); err != nil {
  2551. return errors.New("fs renames mismatch")
  2552. }
  2553. if err := compareKeyValues(expected.Copy, actual.Copy); err != nil {
  2554. return errors.New("fs copy mismatch")
  2555. }
  2556. if len(expected.Deletes) != len(actual.Deletes) {
  2557. return errors.New("fs deletes mismatch")
  2558. }
  2559. for _, v := range expected.Deletes {
  2560. if !util.Contains(actual.Deletes, v) {
  2561. return errors.New("fs deletes content mismatch")
  2562. }
  2563. }
  2564. if len(expected.MkDirs) != len(actual.MkDirs) {
  2565. return errors.New("fs mkdirs mismatch")
  2566. }
  2567. for _, v := range expected.MkDirs {
  2568. if !util.Contains(actual.MkDirs, v) {
  2569. return errors.New("fs mkdir content mismatch")
  2570. }
  2571. }
  2572. if len(expected.Exist) != len(actual.Exist) {
  2573. return errors.New("fs exist mismatch")
  2574. }
  2575. for _, v := range expected.Exist {
  2576. if !util.Contains(actual.Exist, v) {
  2577. return errors.New("fs exist content mismatch")
  2578. }
  2579. }
  2580. return compareEventActionFsCompressFields(expected.Compress, actual.Compress)
  2581. }
  2582. func compareEventActionIDPConfigFields(expected, actual dataprovider.EventActionIDPAccountCheck) error {
  2583. if expected.Mode != actual.Mode {
  2584. return errors.New("mode mismatch")
  2585. }
  2586. if expected.TemplateAdmin != actual.TemplateAdmin {
  2587. return errors.New("admin template mismatch")
  2588. }
  2589. if expected.TemplateUser != actual.TemplateUser {
  2590. return errors.New("user template mismatch")
  2591. }
  2592. return nil
  2593. }
  2594. func compareEventActionCmdConfigFields(expected, actual dataprovider.EventActionCommandConfig) error {
  2595. if expected.Cmd != actual.Cmd {
  2596. return errors.New("command mismatch")
  2597. }
  2598. if expected.Timeout != actual.Timeout {
  2599. return errors.New("cmd timeout mismatch")
  2600. }
  2601. if len(expected.Args) != len(actual.Args) {
  2602. return errors.New("cmd args mismatch")
  2603. }
  2604. for _, v := range expected.Args {
  2605. if !util.Contains(actual.Args, v) {
  2606. return errors.New("cmd args content mismatch")
  2607. }
  2608. }
  2609. if err := compareKeyValues(expected.EnvVars, actual.EnvVars); err != nil {
  2610. return errors.New("cmd env vars mismatch")
  2611. }
  2612. return nil
  2613. }
  2614. func compareEventActionDataRetentionFields(expected, actual dataprovider.EventActionDataRetentionConfig) error {
  2615. if len(expected.Folders) != len(actual.Folders) {
  2616. return errors.New("retention folders mismatch")
  2617. }
  2618. for _, f1 := range expected.Folders {
  2619. found := false
  2620. for _, f2 := range actual.Folders {
  2621. if f1.Path == f2.Path {
  2622. found = true
  2623. if f1.Retention != f2.Retention {
  2624. return fmt.Errorf("retention mismatch for folder %s", f1.Path)
  2625. }
  2626. if f1.DeleteEmptyDirs != f2.DeleteEmptyDirs {
  2627. return fmt.Errorf("delete_empty_dirs mismatch for folder %s", f1.Path)
  2628. }
  2629. if f1.IgnoreUserPermissions != f2.IgnoreUserPermissions {
  2630. return fmt.Errorf("ignore_user_permissions mismatch for folder %s", f1.Path)
  2631. }
  2632. break
  2633. }
  2634. }
  2635. if !found {
  2636. return errors.New("retention folders mismatch")
  2637. }
  2638. }
  2639. return nil
  2640. }
  2641. func compareEqualGroupSettingsFields(expected sdk.BaseGroupUserSettings, actual sdk.BaseGroupUserSettings) error {
  2642. if expected.HomeDir != actual.HomeDir {
  2643. return errors.New("home dir mismatch")
  2644. }
  2645. if expected.MaxSessions != actual.MaxSessions {
  2646. return errors.New("MaxSessions mismatch")
  2647. }
  2648. if expected.QuotaSize != actual.QuotaSize {
  2649. return errors.New("QuotaSize mismatch")
  2650. }
  2651. if expected.QuotaFiles != actual.QuotaFiles {
  2652. return errors.New("QuotaFiles mismatch")
  2653. }
  2654. if expected.UploadBandwidth != actual.UploadBandwidth {
  2655. return errors.New("UploadBandwidth mismatch")
  2656. }
  2657. if expected.DownloadBandwidth != actual.DownloadBandwidth {
  2658. return errors.New("DownloadBandwidth mismatch")
  2659. }
  2660. if expected.UploadDataTransfer != actual.UploadDataTransfer {
  2661. return errors.New("upload_data_transfer mismatch")
  2662. }
  2663. if expected.DownloadDataTransfer != actual.DownloadDataTransfer {
  2664. return errors.New("download_data_transfer mismatch")
  2665. }
  2666. if expected.TotalDataTransfer != actual.TotalDataTransfer {
  2667. return errors.New("total_data_transfer mismatch")
  2668. }
  2669. if expected.ExpiresIn != actual.ExpiresIn {
  2670. return errors.New("expires_in mismatch")
  2671. }
  2672. return compareUserPermissions(expected.Permissions, actual.Permissions)
  2673. }
  2674. func compareEqualsUserFields(expected *dataprovider.User, actual *dataprovider.User) error {
  2675. if dataprovider.ConvertName(expected.Username) != actual.Username {
  2676. return errors.New("username mismatch")
  2677. }
  2678. if expected.HomeDir != actual.HomeDir {
  2679. return errors.New("home dir mismatch")
  2680. }
  2681. if expected.UID != actual.UID {
  2682. return errors.New("UID mismatch")
  2683. }
  2684. if expected.GID != actual.GID {
  2685. return errors.New("GID mismatch")
  2686. }
  2687. if expected.MaxSessions != actual.MaxSessions {
  2688. return errors.New("MaxSessions mismatch")
  2689. }
  2690. if len(expected.Permissions) != len(actual.Permissions) {
  2691. return errors.New("permissions mismatch")
  2692. }
  2693. if expected.UploadBandwidth != actual.UploadBandwidth {
  2694. return errors.New("UploadBandwidth mismatch")
  2695. }
  2696. if expected.DownloadBandwidth != actual.DownloadBandwidth {
  2697. return errors.New("DownloadBandwidth mismatch")
  2698. }
  2699. if expected.Status != actual.Status {
  2700. return errors.New("status mismatch")
  2701. }
  2702. if expected.ExpirationDate != actual.ExpirationDate {
  2703. return errors.New("ExpirationDate mismatch")
  2704. }
  2705. if expected.AdditionalInfo != actual.AdditionalInfo {
  2706. return errors.New("AdditionalInfo mismatch")
  2707. }
  2708. if expected.Description != actual.Description {
  2709. return errors.New("description mismatch")
  2710. }
  2711. if expected.Role != actual.Role {
  2712. return errors.New("role mismatch")
  2713. }
  2714. return compareQuotaUserFields(expected, actual)
  2715. }
  2716. func compareQuotaUserFields(expected *dataprovider.User, actual *dataprovider.User) error {
  2717. if expected.QuotaSize != actual.QuotaSize {
  2718. return errors.New("QuotaSize mismatch")
  2719. }
  2720. if expected.QuotaFiles != actual.QuotaFiles {
  2721. return errors.New("QuotaFiles mismatch")
  2722. }
  2723. if expected.UploadDataTransfer != actual.UploadDataTransfer {
  2724. return errors.New("upload_data_transfer mismatch")
  2725. }
  2726. if expected.DownloadDataTransfer != actual.DownloadDataTransfer {
  2727. return errors.New("download_data_transfer mismatch")
  2728. }
  2729. if expected.TotalDataTransfer != actual.TotalDataTransfer {
  2730. return errors.New("total_data_transfer mismatch")
  2731. }
  2732. return nil
  2733. }
  2734. func addLimitAndOffsetQueryParams(rawurl string, limit, offset int64) (*url.URL, error) {
  2735. url, err := url.Parse(rawurl)
  2736. if err != nil {
  2737. return nil, err
  2738. }
  2739. q := url.Query()
  2740. if limit > 0 {
  2741. q.Add("limit", strconv.FormatInt(limit, 10))
  2742. }
  2743. if offset > 0 {
  2744. q.Add("offset", strconv.FormatInt(offset, 10))
  2745. }
  2746. url.RawQuery = q.Encode()
  2747. return url, err
  2748. }
  2749. func addModeQueryParam(rawurl, mode string) (*url.URL, error) {
  2750. url, err := url.Parse(rawurl)
  2751. if err != nil {
  2752. return nil, err
  2753. }
  2754. q := url.Query()
  2755. if len(mode) > 0 {
  2756. q.Add("mode", mode)
  2757. }
  2758. url.RawQuery = q.Encode()
  2759. return url, err
  2760. }
  2761. func addUpdateUserQueryParams(rawurl, disconnect string) (*url.URL, error) {
  2762. url, err := url.Parse(rawurl)
  2763. if err != nil {
  2764. return nil, err
  2765. }
  2766. q := url.Query()
  2767. if disconnect != "" {
  2768. q.Add("disconnect", disconnect)
  2769. }
  2770. url.RawQuery = q.Encode()
  2771. return url, err
  2772. }