httpdtest.go 96 KB

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