handler.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. package webhooks
  2. import (
  3. "io"
  4. "net/http"
  5. "github.com/OliveTin/OliveTin/internal/auth"
  6. "github.com/OliveTin/OliveTin/internal/config"
  7. "github.com/OliveTin/OliveTin/internal/executor"
  8. log "github.com/sirupsen/logrus"
  9. )
  10. type ActionWebhookConfig struct {
  11. Action *config.Action
  12. Config config.WebhookConfig
  13. }
  14. type WebhookHandler struct {
  15. cfg *config.Config
  16. executor *executor.Executor
  17. }
  18. func NewWebhookHandler(cfg *config.Config, ex *executor.Executor) *WebhookHandler {
  19. return &WebhookHandler{
  20. cfg: cfg,
  21. executor: ex,
  22. }
  23. }
  24. func (h *WebhookHandler) HandleWebhook(w http.ResponseWriter, r *http.Request) {
  25. if r.Method != http.MethodPost {
  26. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  27. return
  28. }
  29. payload, err := h.readPayload(r)
  30. if err != nil {
  31. http.Error(w, "Failed to read payload", http.StatusBadRequest)
  32. return
  33. }
  34. matchingActions := h.findMatchingActions(r, payload)
  35. if len(matchingActions) == 0 {
  36. log.WithFields(webhookRequestFields(r)).Infof("Webhook: no matching actions")
  37. h.writeOKResponse(w, "no matching webhook actions")
  38. return
  39. }
  40. processed := h.processMatchingActions(matchingActions, r, payload)
  41. log.WithFields(webhookRequestFields(r)).WithFields(log.Fields{
  42. "matched": len(matchingActions),
  43. "processed": processed,
  44. }).Infof("Webhook: matched")
  45. h.writeOKResponse(w, "webhook actions")
  46. }
  47. func webhookRequestFields(r *http.Request) log.Fields {
  48. return log.Fields{
  49. "method": r.Method,
  50. "path": r.URL.Path,
  51. "query": r.URL.RawQuery,
  52. }
  53. }
  54. func (h *WebhookHandler) readPayload(r *http.Request) ([]byte, error) {
  55. maxSize := int64(1024 * 1024)
  56. payload, err := io.ReadAll(io.LimitReader(r.Body, maxSize))
  57. if err != nil {
  58. log.WithFields(log.Fields{
  59. "error": err,
  60. }).Warnf("Failed to read webhook payload")
  61. return nil, err
  62. }
  63. return payload, nil
  64. }
  65. func (h *WebhookHandler) writeOKResponse(w http.ResponseWriter, context string) {
  66. w.WriteHeader(http.StatusOK)
  67. if _, err := w.Write([]byte("OK")); err != nil {
  68. log.WithError(err).Warnf("Failed to write response for %s", context)
  69. }
  70. }
  71. func (h *WebhookHandler) processMatchingActions(matchingActions []ActionWebhookConfig, r *http.Request, payload []byte) int {
  72. processed := 0
  73. for _, actionConfig := range matchingActions {
  74. if h.processWebhook(actionConfig, r, payload) {
  75. processed++
  76. }
  77. }
  78. return processed
  79. }
  80. func (h *WebhookHandler) findMatchingActions(r *http.Request, payload []byte) []ActionWebhookConfig {
  81. var matches []ActionWebhookConfig
  82. for _, action := range h.cfg.Actions {
  83. matches = append(matches, h.findMatchingWebhooksForAction(action, r, payload)...)
  84. }
  85. return matches
  86. }
  87. func (h *WebhookHandler) findMatchingWebhooksForAction(action *config.Action, r *http.Request, payload []byte) []ActionWebhookConfig {
  88. var matches []ActionWebhookConfig
  89. for _, webhookConfig := range action.ExecOnWebhook {
  90. webhookConfigCopy := webhookConfig
  91. if webhookConfigCopy.Template != "" {
  92. ApplyGitHubTemplate(&webhookConfigCopy, webhookConfigCopy.Template)
  93. }
  94. matcher := NewWebhookMatcher(webhookConfigCopy, r, payload)
  95. if matcher.Matches() {
  96. matches = append(matches, ActionWebhookConfig{
  97. Action: action,
  98. Config: webhookConfigCopy,
  99. })
  100. }
  101. }
  102. return matches
  103. }
  104. func (h *WebhookHandler) processWebhook(actionConfig ActionWebhookConfig, r *http.Request, payload []byte) bool {
  105. verifier := NewAuthVerifier(actionConfig.Config)
  106. if !verifier.Verify(r, payload) {
  107. log.WithFields(log.Fields{
  108. "actionTitle": actionConfig.Action.Title,
  109. "authType": actionConfig.Config.AuthType,
  110. }).Warnf("Webhook authentication failed")
  111. return false
  112. }
  113. matcher := NewWebhookMatcher(actionConfig.Config, r, payload)
  114. args, err := matcher.ExtractArguments()
  115. if err != nil {
  116. log.WithFields(log.Fields{
  117. "actionTitle": actionConfig.Action.Title,
  118. "error": err,
  119. }).Warnf("Failed to extract webhook arguments")
  120. return false
  121. }
  122. justification, err := matcher.ExtractJustification()
  123. if err != nil {
  124. log.WithFields(log.Fields{
  125. "actionTitle": actionConfig.Action.Title,
  126. "error": err,
  127. }).Warnf("Failed to extract webhook justification")
  128. return false
  129. }
  130. h.executeAction(actionConfig.Action, args, justification)
  131. return true
  132. }
  133. func (h *WebhookHandler) executeAction(action *config.Action, args map[string]string, justification string) {
  134. binding := h.executor.FindBindingWithNoEntity(action)
  135. if binding == nil {
  136. log.WithFields(log.Fields{
  137. "actionTitle": action.Title,
  138. }).Warnf("Action binding not found, skipping execution")
  139. return
  140. }
  141. definedArgs := filterToDefinedArguments(args, action)
  142. req := &executor.ExecutionRequest{
  143. Binding: binding,
  144. Cfg: h.cfg,
  145. Tags: []string{"webhook"},
  146. Arguments: definedArgs,
  147. Justification: justification,
  148. AuthenticatedUser: auth.UserFromSystem(h.cfg, "webhook"),
  149. }
  150. h.executor.ExecRequest(req)
  151. }
  152. func filterToDefinedArguments(args map[string]string, action *config.Action) map[string]string {
  153. definedNames := make(map[string]struct{})
  154. for _, arg := range action.Arguments {
  155. definedNames[arg.Name] = struct{}{}
  156. }
  157. filtered := make(map[string]string)
  158. for k, v := range args {
  159. if _, ok := definedNames[k]; ok {
  160. filtered[k] = v
  161. }
  162. }
  163. return filtered
  164. }