handler.go 5.7 KB

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