httpdtest.go 98 KB

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