decisions.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. package v1
  2. import (
  3. "crypto/sha512"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "time"
  8. "github.com/crowdsecurity/crowdsec/pkg/database/ent"
  9. "github.com/crowdsecurity/crowdsec/pkg/models"
  10. "github.com/gin-gonic/gin"
  11. log "github.com/sirupsen/logrus"
  12. )
  13. func FormatDecisions(decisions []*ent.Decision) ([]*models.Decision, error) {
  14. var results []*models.Decision
  15. for _, dbDecision := range decisions {
  16. duration := dbDecision.Until.Sub(time.Now().UTC()).String()
  17. decision := models.Decision{
  18. ID: int64(dbDecision.ID),
  19. Duration: &duration,
  20. Scenario: &dbDecision.Scenario,
  21. Scope: &dbDecision.Scope,
  22. Value: &dbDecision.Value,
  23. Type: &dbDecision.Type,
  24. Origin: &dbDecision.Origin,
  25. }
  26. results = append(results, &decision)
  27. }
  28. return results, nil
  29. }
  30. func (c *Controller) GetDecision(gctx *gin.Context) {
  31. var err error
  32. var results []*models.Decision
  33. var data []*ent.Decision
  34. data, err = c.DBClient.QueryDecisionWithFilter(gctx.Request.URL.Query())
  35. if err != nil {
  36. c.HandleDBErrors(gctx, err)
  37. return
  38. }
  39. results, err = FormatDecisions(data)
  40. if err != nil {
  41. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  42. return
  43. }
  44. /*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/...,
  45. but if it's non-empty, it means that there is one or more decisions for this target*/
  46. if len(results) > 0 {
  47. PrometheusBouncersHasNonEmptyDecision(gctx)
  48. } else {
  49. PrometheusBouncersHasEmptyDecision(gctx)
  50. }
  51. if gctx.Request.Method == "HEAD" {
  52. gctx.String(http.StatusOK, "")
  53. return
  54. }
  55. gctx.JSON(http.StatusOK, results)
  56. }
  57. func (c *Controller) DeleteDecisionById(gctx *gin.Context) {
  58. var err error
  59. decisionIDStr := gctx.Param("decision_id")
  60. decisionID, err := strconv.Atoi(decisionIDStr)
  61. if err != nil {
  62. gctx.JSON(http.StatusBadRequest, gin.H{"message": "decision_id must be valid integer"})
  63. return
  64. }
  65. err = c.DBClient.SoftDeleteDecisionByID(decisionID)
  66. if err != nil {
  67. c.HandleDBErrors(gctx, err)
  68. return
  69. }
  70. deleteDecisionResp := models.DeleteDecisionResponse{
  71. NbDeleted: "1",
  72. }
  73. gctx.JSON(http.StatusOK, deleteDecisionResp)
  74. return
  75. }
  76. func (c *Controller) DeleteDecisions(gctx *gin.Context) {
  77. var err error
  78. nbDeleted, err := c.DBClient.SoftDeleteDecisionsWithFilter(gctx.Request.URL.Query())
  79. if err != nil {
  80. c.HandleDBErrors(gctx, err)
  81. return
  82. }
  83. deleteDecisionResp := models.DeleteDecisionResponse{
  84. NbDeleted: nbDeleted,
  85. }
  86. gctx.JSON(http.StatusOK, deleteDecisionResp)
  87. return
  88. }
  89. func (c *Controller) StreamDecision(gctx *gin.Context) {
  90. var data []*ent.Decision
  91. ret := make(map[string][]*models.Decision, 0)
  92. ret["new"] = []*models.Decision{}
  93. ret["deleted"] = []*models.Decision{}
  94. val := gctx.Request.Header.Get(c.APIKeyHeader)
  95. hashedKey := sha512.New()
  96. hashedKey.Write([]byte(val))
  97. hashStr := fmt.Sprintf("%x", hashedKey.Sum(nil))
  98. bouncerInfo, err := c.DBClient.SelectBouncer(hashStr)
  99. if err != nil {
  100. if _, ok := err.(*ent.NotFoundError); ok {
  101. gctx.JSON(http.StatusForbidden, gin.H{"message": err.Error()})
  102. } else {
  103. gctx.JSON(http.StatusUnauthorized, gin.H{"message": "not allowed"})
  104. }
  105. return
  106. }
  107. if bouncerInfo == nil {
  108. gctx.JSON(http.StatusUnauthorized, gin.H{"message": "not allowed"})
  109. return
  110. }
  111. filters := gctx.Request.URL.Query()
  112. if _, ok := filters["scopes"]; !ok {
  113. filters["scopes"] = []string{"ip,range"}
  114. }
  115. // if the blocker just start, return all decisions
  116. if val, ok := gctx.Request.URL.Query()["startup"]; ok {
  117. if val[0] == "true" {
  118. data, err := c.DBClient.QueryAllDecisionsWithFilters(filters)
  119. if err != nil {
  120. log.Errorf("failed querying decisions: %v", err)
  121. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  122. return
  123. }
  124. ret["new"], err = FormatDecisions(data)
  125. if err != nil {
  126. log.Errorf("unable to format expired decision for '%s' : %v", bouncerInfo.Name, err)
  127. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  128. return
  129. }
  130. // getting expired decisions
  131. data, err = c.DBClient.QueryExpiredDecisionsWithFilters(filters)
  132. if err != nil {
  133. log.Errorf("unable to query expired decision for '%s' : %v", bouncerInfo.Name, err)
  134. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  135. return
  136. }
  137. ret["deleted"], err = FormatDecisions(data)
  138. if err != nil {
  139. log.Errorf("unable to format expired decision for '%s' : %v", bouncerInfo.Name, err)
  140. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  141. return
  142. }
  143. if err := c.DBClient.UpdateBouncerLastPull(time.Now().UTC(), bouncerInfo.ID); err != nil {
  144. log.Errorf("unable to update bouncer '%s' pull: %v", bouncerInfo.Name, err)
  145. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  146. return
  147. }
  148. if gctx.Request.Method == "HEAD" {
  149. gctx.String(http.StatusOK, "")
  150. return
  151. }
  152. gctx.JSON(http.StatusOK, ret)
  153. return
  154. }
  155. }
  156. // getting new decisions
  157. data, err = c.DBClient.QueryNewDecisionsSinceWithFilters(bouncerInfo.LastPull, filters)
  158. if err != nil {
  159. log.Errorf("unable to query new decision for '%s' : %v", bouncerInfo.Name, err)
  160. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  161. return
  162. }
  163. ret["new"], err = FormatDecisions(data)
  164. if err != nil {
  165. log.Errorf("unable to format new decision for '%s' : %v", bouncerInfo.Name, err)
  166. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  167. return
  168. }
  169. // getting expired decisions
  170. data, err = c.DBClient.QueryExpiredDecisionsSinceWithFilters(bouncerInfo.LastPull.Add((-2 * time.Second)), filters) // do we want to give exactly lastPull time ?
  171. if err != nil {
  172. log.Errorf("unable to query expired decision for '%s' : %v", bouncerInfo.Name, err)
  173. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  174. return
  175. }
  176. ret["deleted"], err = FormatDecisions(data)
  177. if err != nil {
  178. log.Errorf("unable to format expired decision for '%s' : %v", bouncerInfo.Name, err)
  179. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  180. return
  181. }
  182. if err := c.DBClient.UpdateBouncerLastPull(time.Now().UTC(), bouncerInfo.ID); err != nil {
  183. log.Errorf("unable to update bouncer '%s' pull: %v", bouncerInfo.Name, err)
  184. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  185. return
  186. }
  187. gctx.JSON(http.StatusOK, ret)
  188. return
  189. }