-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhook.go
More file actions
149 lines (130 loc) · 4.21 KB
/
Copy pathwebhook.go
File metadata and controls
149 lines (130 loc) · 4.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package server
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
// WebhookHandler handles incoming webhook requests and triggers workflow executions.
type WebhookHandler struct {
server *Server
}
// NewWebhookHandler creates a webhook handler attached to the server.
func NewWebhookHandler(s *Server) *WebhookHandler {
return &WebhookHandler{server: s}
}
// ServeHTTP handles POST /hooks/<path> by looking up the registered webhook
// trigger and executing the associated workflow.
func (h *WebhookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
return
}
// Extract the webhook path from the URL (e.g., /hooks/my-workflow → /hooks/my-workflow).
path := r.URL.Path
if !strings.HasPrefix(path, "/hooks/") {
http.Error(w, `{"error":"not found"}`, http.StatusNotFound)
return
}
// Look up trigger.
trigger, err := LookupWebhookTrigger(r.Context(), h.server.DB, path)
if err != nil {
h.server.Logger.Error("webhook: lookup error", "path", path, "error", err)
http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError)
return
}
if trigger == nil {
writeJSONError(w, "no webhook registered for path", http.StatusNotFound)
return
}
// Read request body as trigger payload.
var payload any
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) // 1MB limit
if err != nil {
http.Error(w, `{"error":"reading body"}`, http.StatusBadRequest)
return
}
// Verify HMAC signature if the trigger has a secret configured.
if trigger.Secret != "" {
if !verifyWebhookSignature(body, trigger.Secret, r.Header) {
writeJSONError(w, "invalid or missing webhook signature", http.StatusForbidden)
return
}
}
if len(body) > 0 {
if err := json.Unmarshal(body, &payload); err != nil {
// Not JSON — treat as string.
payload = string(body)
}
}
// Build inputs with trigger context.
inputs := map[string]any{
"trigger": map[string]any{
"type": "webhook",
"path": path,
"payload": payload,
"headers": headerMap(r.Header),
},
}
h.server.Logger.Info("webhook: triggering workflow",
"path", path,
"workflow", trigger.WorkflowName,
"version", trigger.WorkflowVersion)
// The /hooks/ endpoint is authenticated, so r.Context() already carries the
// caller's team — the same team the trigger was looked up under. Running with
// it keeps workflow/credential resolution scoped to that tenant.
execID, err := h.server.executeWorkflow(r.Context(), trigger.WorkflowName, trigger.WorkflowVersion, inputs)
if err != nil {
h.server.Logger.Error("webhook: execution failed",
"workflow", trigger.WorkflowName,
"error", err)
writeJSONError(w, "internal error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
fmt.Fprintf(w, `{"execution_id":"%s","workflow":"%s","version":%d}`,
execID, trigger.WorkflowName, trigger.WorkflowVersion)
}
// verifyWebhookSignature checks the HMAC-SHA256 signature of the request body.
// It looks for the signature in the X-Hub-Signature-256 header (GitHub format: "sha256=<hex>")
// or the X-Signature-256 header as an alternative. Returns false if no signature
// header is present or the signature does not match.
func verifyWebhookSignature(body []byte, secret string, headers http.Header) bool {
// Try X-Hub-Signature-256 first (GitHub convention), then X-Signature-256.
sigHeader := headers.Get("X-Hub-Signature-256")
if sigHeader == "" {
sigHeader = headers.Get("X-Signature-256")
}
if sigHeader == "" {
return false
}
// Expect format "sha256=<hex>".
if !strings.HasPrefix(sigHeader, "sha256=") {
return false
}
sigHex := sigHeader[len("sha256="):]
sig, err := hex.DecodeString(sigHex)
if err != nil {
return false
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(body)
expected := mac.Sum(nil)
return hmac.Equal(sig, expected)
}
func headerMap(h http.Header) map[string]any {
result := make(map[string]any, len(h))
for k, v := range h {
if len(v) == 1 {
result[strings.ToLower(k)] = v[0]
} else {
result[strings.ToLower(k)] = v
}
}
return result
}