decisions.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. package v1
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "time"
  8. "github.com/crowdsecurity/crowdsec/pkg/database/ent"
  9. "github.com/crowdsecurity/crowdsec/pkg/fflag"
  10. "github.com/crowdsecurity/crowdsec/pkg/models"
  11. "github.com/gin-gonic/gin"
  12. log "github.com/sirupsen/logrus"
  13. )
  14. // Format decisions for the bouncers
  15. func FormatDecisions(decisions []*ent.Decision) []*models.Decision {
  16. var results []*models.Decision
  17. for _, dbDecision := range decisions {
  18. duration := dbDecision.Until.Sub(time.Now().UTC()).String()
  19. decision := models.Decision{
  20. ID: int64(dbDecision.ID),
  21. Duration: &duration,
  22. Scenario: &dbDecision.Scenario,
  23. Scope: &dbDecision.Scope,
  24. Value: &dbDecision.Value,
  25. Type: &dbDecision.Type,
  26. Origin: &dbDecision.Origin,
  27. UUID: dbDecision.UUID,
  28. }
  29. results = append(results, &decision)
  30. }
  31. return results
  32. }
  33. func (c *Controller) GetDecision(gctx *gin.Context) {
  34. var err error
  35. var results []*models.Decision
  36. var data []*ent.Decision
  37. bouncerInfo, err := getBouncerFromContext(gctx)
  38. if err != nil {
  39. gctx.JSON(http.StatusUnauthorized, gin.H{"message": "not allowed"})
  40. return
  41. }
  42. data, err = c.DBClient.QueryDecisionWithFilter(gctx.Request.URL.Query())
  43. if err != nil {
  44. c.HandleDBErrors(gctx, err)
  45. return
  46. }
  47. results = FormatDecisions(data)
  48. /*let's follow a naive logic : when a bouncer queries /decisions, if the answer is empty, we assume there is no decision for this ip/user/...,
  49. but if it's non-empty, it means that there is one or more decisions for this target*/
  50. if len(results) > 0 {
  51. PrometheusBouncersHasNonEmptyDecision(gctx)
  52. } else {
  53. PrometheusBouncersHasEmptyDecision(gctx)
  54. }
  55. if gctx.Request.Method == http.MethodHead {
  56. gctx.String(http.StatusOK, "")
  57. return
  58. }
  59. if time.Now().UTC().Sub(bouncerInfo.LastPull) >= time.Minute {
  60. if err := c.DBClient.UpdateBouncerLastPull(time.Now().UTC(), bouncerInfo.ID); err != nil {
  61. log.Errorf("failed to update bouncer last pull: %v", err)
  62. }
  63. }
  64. gctx.JSON(http.StatusOK, results)
  65. }
  66. func (c *Controller) DeleteDecisionById(gctx *gin.Context) {
  67. var err error
  68. decisionIDStr := gctx.Param("decision_id")
  69. decisionID, err := strconv.Atoi(decisionIDStr)
  70. if err != nil {
  71. gctx.JSON(http.StatusBadRequest, gin.H{"message": "decision_id must be valid integer"})
  72. return
  73. }
  74. nbDeleted, deletedFromDB, err := c.DBClient.SoftDeleteDecisionByID(decisionID)
  75. if err != nil {
  76. c.HandleDBErrors(gctx, err)
  77. return
  78. }
  79. //transform deleted decisions to be sendable to capi
  80. deletedDecisions := FormatDecisions(deletedFromDB)
  81. if err != nil {
  82. log.Warningf("failed to format decisions: %v", err)
  83. }
  84. if c.DecisionDeleteChan != nil {
  85. c.DecisionDeleteChan <- deletedDecisions
  86. }
  87. deleteDecisionResp := models.DeleteDecisionResponse{
  88. NbDeleted: strconv.Itoa(nbDeleted),
  89. }
  90. gctx.JSON(http.StatusOK, deleteDecisionResp)
  91. }
  92. func (c *Controller) DeleteDecisions(gctx *gin.Context) {
  93. var err error
  94. nbDeleted, deletedFromDB, err := c.DBClient.SoftDeleteDecisionsWithFilter(gctx.Request.URL.Query())
  95. if err != nil {
  96. c.HandleDBErrors(gctx, err)
  97. return
  98. }
  99. //transform deleted decisions to be sendable to capi
  100. deletedDecisions := FormatDecisions(deletedFromDB)
  101. if err != nil {
  102. log.Warningf("failed to format decisions: %v", err)
  103. }
  104. if c.DecisionDeleteChan != nil {
  105. c.DecisionDeleteChan <- deletedDecisions
  106. }
  107. deleteDecisionResp := models.DeleteDecisionResponse{
  108. NbDeleted: nbDeleted,
  109. }
  110. gctx.JSON(http.StatusOK, deleteDecisionResp)
  111. }
  112. func writeStartupDecisions(gctx *gin.Context, filters map[string][]string, dbFunc func(map[string][]string) ([]*ent.Decision, error)) error {
  113. // respBuffer := bytes.NewBuffer([]byte{})
  114. limit := 30000 //FIXME : make it configurable
  115. needComma := false
  116. lastId := 0
  117. limitStr := fmt.Sprintf("%d", limit)
  118. filters["limit"] = []string{limitStr}
  119. for {
  120. if lastId > 0 {
  121. lastIdStr := fmt.Sprintf("%d", lastId)
  122. filters["id_gt"] = []string{lastIdStr}
  123. }
  124. data, err := dbFunc(filters)
  125. if err != nil {
  126. return err
  127. }
  128. if len(data) > 0 {
  129. lastId = data[len(data)-1].ID
  130. results := FormatDecisions(data)
  131. for _, decision := range results {
  132. decisionJSON, _ := json.Marshal(decision)
  133. if needComma {
  134. //respBuffer.Write([]byte(","))
  135. gctx.Writer.Write([]byte(","))
  136. } else {
  137. needComma = true
  138. }
  139. //respBuffer.Write(decisionJSON)
  140. //_, err := gctx.Writer.Write(respBuffer.Bytes())
  141. _, err := gctx.Writer.Write(decisionJSON)
  142. if err != nil {
  143. gctx.Writer.Flush()
  144. return err
  145. }
  146. //respBuffer.Reset()
  147. }
  148. }
  149. log.Debugf("startup: %d decisions returned (limit: %d, lastid: %d)", len(data), limit, lastId)
  150. if len(data) < limit {
  151. gctx.Writer.Flush()
  152. break
  153. }
  154. }
  155. return nil
  156. }
  157. func writeDeltaDecisions(gctx *gin.Context, filters map[string][]string, lastPull time.Time, dbFunc func(time.Time, map[string][]string) ([]*ent.Decision, error)) error {
  158. //respBuffer := bytes.NewBuffer([]byte{})
  159. limit := 30000 //FIXME : make it configurable
  160. needComma := false
  161. lastId := 0
  162. limitStr := fmt.Sprintf("%d", limit)
  163. filters["limit"] = []string{limitStr}
  164. for {
  165. if lastId > 0 {
  166. lastIdStr := fmt.Sprintf("%d", lastId)
  167. filters["id_gt"] = []string{lastIdStr}
  168. }
  169. data, err := dbFunc(lastPull, filters)
  170. if err != nil {
  171. return err
  172. }
  173. if len(data) > 0 {
  174. lastId = data[len(data)-1].ID
  175. results := FormatDecisions(data)
  176. for _, decision := range results {
  177. decisionJSON, _ := json.Marshal(decision)
  178. if needComma {
  179. //respBuffer.Write([]byte(","))
  180. gctx.Writer.Write([]byte(","))
  181. } else {
  182. needComma = true
  183. }
  184. //respBuffer.Write(decisionJSON)
  185. //_, err := gctx.Writer.Write(respBuffer.Bytes())
  186. _, err := gctx.Writer.Write(decisionJSON)
  187. if err != nil {
  188. gctx.Writer.Flush()
  189. return err
  190. }
  191. //respBuffer.Reset()
  192. }
  193. }
  194. log.Debugf("startup: %d decisions returned (limit: %d, lastid: %d)", len(data), limit, lastId)
  195. if len(data) < limit {
  196. gctx.Writer.Flush()
  197. break
  198. }
  199. }
  200. return nil
  201. }
  202. func (c *Controller) StreamDecisionChunked(gctx *gin.Context, bouncerInfo *ent.Bouncer, streamStartTime time.Time, filters map[string][]string) error {
  203. var err error
  204. gctx.Writer.Header().Set("Content-Type", "application/json")
  205. gctx.Writer.Header().Set("Transfer-Encoding", "chunked")
  206. gctx.Writer.WriteHeader(http.StatusOK)
  207. gctx.Writer.Write([]byte(`{"new": [`)) //No need to check for errors, the doc says it always returns nil
  208. // if the blocker just start, return all decisions
  209. if val, ok := gctx.Request.URL.Query()["startup"]; ok && val[0] == "true" {
  210. //Active decisions
  211. err := writeStartupDecisions(gctx, filters, c.DBClient.QueryAllDecisionsWithFilters)
  212. if err != nil {
  213. log.Errorf("failed sending new decisions for startup: %v", err)
  214. gctx.Writer.Write([]byte(`], "deleted": []}`))
  215. gctx.Writer.Flush()
  216. return err
  217. }
  218. gctx.Writer.Write([]byte(`], "deleted": [`))
  219. //Expired decisions
  220. err = writeStartupDecisions(gctx, filters, c.DBClient.QueryExpiredDecisionsWithFilters)
  221. if err != nil {
  222. log.Errorf("failed sending expired decisions for startup: %v", err)
  223. gctx.Writer.Write([]byte(`]}`))
  224. gctx.Writer.Flush()
  225. return err
  226. }
  227. gctx.Writer.Write([]byte(`]}`))
  228. gctx.Writer.Flush()
  229. } else {
  230. err = writeDeltaDecisions(gctx, filters, bouncerInfo.LastPull, c.DBClient.QueryNewDecisionsSinceWithFilters)
  231. if err != nil {
  232. log.Errorf("failed sending new decisions for delta: %v", err)
  233. gctx.Writer.Write([]byte(`], "deleted": []}`))
  234. gctx.Writer.Flush()
  235. return err
  236. }
  237. gctx.Writer.Write([]byte(`], "deleted": [`))
  238. err = writeDeltaDecisions(gctx, filters, bouncerInfo.LastPull, c.DBClient.QueryExpiredDecisionsSinceWithFilters)
  239. if err != nil {
  240. log.Errorf("failed sending expired decisions for delta: %v", err)
  241. gctx.Writer.Write([]byte(`]}`))
  242. gctx.Writer.Flush()
  243. return err
  244. }
  245. gctx.Writer.Write([]byte(`]}`))
  246. gctx.Writer.Flush()
  247. }
  248. return nil
  249. }
  250. func (c *Controller) StreamDecisionNonChunked(gctx *gin.Context, bouncerInfo *ent.Bouncer, streamStartTime time.Time, filters map[string][]string) error {
  251. var data []*ent.Decision
  252. var err error
  253. ret := make(map[string][]*models.Decision, 0)
  254. ret["new"] = []*models.Decision{}
  255. ret["deleted"] = []*models.Decision{}
  256. if val, ok := gctx.Request.URL.Query()["startup"]; ok {
  257. if val[0] == "true" {
  258. data, err = c.DBClient.QueryAllDecisionsWithFilters(filters)
  259. if err != nil {
  260. log.Errorf("failed querying decisions: %v", err)
  261. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  262. return err
  263. }
  264. //data = KeepLongestDecision(data)
  265. ret["new"] = FormatDecisions(data)
  266. // getting expired decisions
  267. data, err = c.DBClient.QueryExpiredDecisionsWithFilters(filters)
  268. if err != nil {
  269. log.Errorf("unable to query expired decision for '%s' : %v", bouncerInfo.Name, err)
  270. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  271. return err
  272. }
  273. ret["deleted"] = FormatDecisions(data)
  274. gctx.JSON(http.StatusOK, ret)
  275. return nil
  276. }
  277. }
  278. // getting new decisions
  279. data, err = c.DBClient.QueryNewDecisionsSinceWithFilters(bouncerInfo.LastPull, filters)
  280. if err != nil {
  281. log.Errorf("unable to query new decision for '%s' : %v", bouncerInfo.Name, err)
  282. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  283. return err
  284. }
  285. //data = KeepLongestDecision(data)
  286. ret["new"] = FormatDecisions(data)
  287. // getting expired decisions
  288. data, err = c.DBClient.QueryExpiredDecisionsSinceWithFilters(bouncerInfo.LastPull.Add((-2 * time.Second)), filters) // do we want to give exactly lastPull time ?
  289. if err != nil {
  290. log.Errorf("unable to query expired decision for '%s' : %v", bouncerInfo.Name, err)
  291. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  292. return err
  293. }
  294. ret["deleted"] = FormatDecisions(data)
  295. gctx.JSON(http.StatusOK, ret)
  296. return nil
  297. }
  298. func (c *Controller) StreamDecision(gctx *gin.Context) {
  299. var err error
  300. streamStartTime := time.Now().UTC()
  301. bouncerInfo, err := getBouncerFromContext(gctx)
  302. if err != nil {
  303. gctx.JSON(http.StatusUnauthorized, gin.H{"message": "not allowed"})
  304. return
  305. }
  306. if gctx.Request.Method == http.MethodHead {
  307. //For HEAD, just return as the bouncer won't get a body anyway, so no need to query the db
  308. //We also don't update the last pull time, as it would mess with the delta sent on the next request (if done without startup=true)
  309. gctx.String(http.StatusOK, "")
  310. return
  311. }
  312. filters := gctx.Request.URL.Query()
  313. if _, ok := filters["scopes"]; !ok {
  314. filters["scopes"] = []string{"ip,range"}
  315. }
  316. if fflag.ChunkedDecisionsStream.IsEnabled() {
  317. err = c.StreamDecisionChunked(gctx, bouncerInfo, streamStartTime, filters)
  318. } else {
  319. err = c.StreamDecisionNonChunked(gctx, bouncerInfo, streamStartTime, filters)
  320. }
  321. if err == nil {
  322. //Only update the last pull time if no error occurred when sending the decisions to avoid missing decisions
  323. if err := c.DBClient.UpdateBouncerLastPull(streamStartTime, bouncerInfo.ID); err != nil {
  324. log.Errorf("unable to update bouncer '%s' pull: %v", bouncerInfo.Name, err)
  325. }
  326. }
  327. }