decisions.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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()).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. return
  57. }
  58. func (c *Controller) DeleteDecisionById(gctx *gin.Context) {
  59. var err error
  60. decisionIDStr := gctx.Param("decision_id")
  61. decisionID, err := strconv.Atoi(decisionIDStr)
  62. if err != nil {
  63. gctx.JSON(http.StatusBadRequest, gin.H{"message": "decision_id must be valid integer"})
  64. return
  65. }
  66. err = c.DBClient.SoftDeleteDecisionByID(decisionID)
  67. if err != nil {
  68. c.HandleDBErrors(gctx, err)
  69. return
  70. }
  71. deleteDecisionResp := models.DeleteDecisionResponse{
  72. NbDeleted: "1",
  73. }
  74. gctx.JSON(http.StatusOK, deleteDecisionResp)
  75. return
  76. }
  77. func (c *Controller) DeleteDecisions(gctx *gin.Context) {
  78. var err error
  79. nbDeleted, err := c.DBClient.SoftDeleteDecisionsWithFilter(gctx.Request.URL.Query())
  80. if err != nil {
  81. c.HandleDBErrors(gctx, err)
  82. return
  83. }
  84. deleteDecisionResp := models.DeleteDecisionResponse{
  85. NbDeleted: nbDeleted,
  86. }
  87. gctx.JSON(http.StatusOK, deleteDecisionResp)
  88. return
  89. }
  90. func (c *Controller) StreamDecision(gctx *gin.Context) {
  91. var data []*ent.Decision
  92. ret := make(map[string][]*models.Decision, 0)
  93. ret["new"] = []*models.Decision{}
  94. ret["deleted"] = []*models.Decision{}
  95. val := gctx.Request.Header.Get(c.APIKeyHeader)
  96. hashedKey := sha512.New()
  97. hashedKey.Write([]byte(val))
  98. hashStr := fmt.Sprintf("%x", hashedKey.Sum(nil))
  99. bouncerInfo, err := c.DBClient.SelectBouncer(hashStr)
  100. if err != nil {
  101. if _, ok := err.(*ent.NotFoundError); ok {
  102. gctx.JSON(http.StatusForbidden, gin.H{"message": err.Error()})
  103. } else {
  104. gctx.JSON(http.StatusUnauthorized, gin.H{"message": "not allowed"})
  105. }
  106. return
  107. }
  108. if bouncerInfo == nil {
  109. gctx.JSON(http.StatusUnauthorized, gin.H{"message": "not allowed"})
  110. return
  111. }
  112. // if the blocker just start, return all decisions
  113. if val, ok := gctx.Request.URL.Query()["startup"]; ok {
  114. if val[0] == "true" {
  115. data, err := c.DBClient.QueryAllDecisions()
  116. if err != nil {
  117. log.Errorf("failed querying decisions: %v", err)
  118. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  119. return
  120. }
  121. ret["new"], err = FormatDecisions(data)
  122. if err != nil {
  123. log.Errorf("unable to format expired decision for '%s' : %v", bouncerInfo.Name, err)
  124. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  125. return
  126. }
  127. // getting expired decisions
  128. data, err = c.DBClient.QueryExpiredDecisions()
  129. if err != nil {
  130. log.Errorf("unable to query expired decision for '%s' : %v", bouncerInfo.Name, err)
  131. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  132. return
  133. }
  134. ret["deleted"], err = FormatDecisions(data)
  135. if err != nil {
  136. log.Errorf("unable to format expired decision for '%s' : %v", bouncerInfo.Name, err)
  137. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  138. return
  139. }
  140. if err := c.DBClient.UpdateBouncerLastPull(time.Now(), bouncerInfo.ID); err != nil {
  141. log.Errorf("unable to update bouncer '%s' pull: %v", bouncerInfo.Name, err)
  142. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  143. return
  144. }
  145. if gctx.Request.Method == "HEAD" {
  146. gctx.String(http.StatusOK, "")
  147. return
  148. }
  149. gctx.JSON(http.StatusOK, ret)
  150. return
  151. }
  152. }
  153. // getting new decisions
  154. data, err = c.DBClient.QueryNewDecisionsSince(bouncerInfo.LastPull)
  155. if err != nil {
  156. log.Errorf("unable to query new decision for '%s' : %v", bouncerInfo.Name, err)
  157. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  158. return
  159. }
  160. ret["new"], err = FormatDecisions(data)
  161. if err != nil {
  162. log.Errorf("unable to format new decision for '%s' : %v", bouncerInfo.Name, err)
  163. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  164. return
  165. }
  166. // getting expired decisions
  167. data, err = c.DBClient.QueryExpiredDecisionsSince(bouncerInfo.LastPull.Add((-2 * time.Second))) // do we want to give exactly lastPull time ?
  168. if err != nil {
  169. log.Errorf("unable to query expired decision for '%s' : %v", bouncerInfo.Name, err)
  170. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  171. return
  172. }
  173. ret["deleted"], err = FormatDecisions(data)
  174. if err != nil {
  175. log.Errorf("unable to format expired decision for '%s' : %v", bouncerInfo.Name, err)
  176. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  177. return
  178. }
  179. if err := c.DBClient.UpdateBouncerLastPull(time.Now(), bouncerInfo.ID); err != nil {
  180. log.Errorf("unable to update bouncer '%s' pull: %v", bouncerInfo.Name, err)
  181. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  182. return
  183. }
  184. gctx.JSON(http.StatusOK, ret)
  185. return
  186. }