-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhooks.go
More file actions
70 lines (59 loc) · 2 KB
/
Copy pathwebhooks.go
File metadata and controls
70 lines (59 loc) · 2 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
package flow
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
)
// WebhookService handles webhook signature verification.
type WebhookService struct {
secret string
}
// NewWebhookService creates a new WebhookService with the given signing secret.
func NewWebhookService(secret string) *WebhookService {
return &WebhookService{secret: secret}
}
// Verify checks the webhook signature and returns the parsed event.
func (s *WebhookService) Verify(payload []byte, signature string) (*WebhookEvent, error) {
if s.secret == "" {
return nil, &InvalidSignatureError{Message: "webhook secret not configured"}
}
mac := hmac.New(sha256.New, []byte(s.secret))
mac.Write(payload)
expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))
if !hmac.Equal([]byte(expected), []byte(signature)) {
return nil, &InvalidSignatureError{}
}
var event WebhookEvent
if err := json.Unmarshal(payload, &event); err != nil {
return nil, fmt.Errorf("flow: unmarshal webhook event: %w", err)
}
return &event, nil
}
// IsValid checks if a webhook signature is valid without parsing the event.
func (s *WebhookService) IsValid(payload []byte, signature string) bool {
if s.secret == "" {
return false
}
mac := hmac.New(sha256.New, []byte(s.secret))
mac.Write(payload)
expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))
return hmac.Equal([]byte(expected), []byte(signature))
}
// VerifyRequest reads and verifies a webhook from an http.Request.
// It expects the signature in the X-Flow-Signature header.
func (s *WebhookService) VerifyRequest(r *http.Request) (*WebhookEvent, error) {
signature := r.Header.Get("X-Flow-Signature")
if signature == "" {
return nil, &InvalidSignatureError{Message: "missing X-Flow-Signature header"}
}
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, fmt.Errorf("flow: read request body: %w", err)
}
defer r.Body.Close()
return s.Verify(body, signature)
}