httpdtest.go 98 KB

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