-
Notifications
You must be signed in to change notification settings - Fork 0
/
signature.go
55 lines (44 loc) · 1.45 KB
/
signature.go
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
package webhook
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/nam-truong-le/lambda-utils-go/v4/pkg/aws/secretsmanager"
"github.com/nam-truong-le/lambda-utils-go/v4/pkg/logger"
)
const (
signatureHeader = "X-WC-Webhook-Signature"
)
// ValidateRequest
// returns isPing, isValid, err
func ValidateRequest(ctx context.Context, request *events.APIGatewayProxyRequest, webhookID int) (bool, bool, error) {
log := logger.FromContext(ctx)
pingBody := fmt.Sprintf("webhook_id=%d", webhookID)
if request.Body == pingBody {
log.Infof("body = [%s], this is a ping request from woocommerce, skip processing", request.Body)
// ping=true, valid=true, err=nil
return true, true, nil
}
signature := request.Headers[signatureHeader]
log.Infof(request.Body)
log.Infof(fmt.Sprintf("%v", request.Headers))
secret, err := secretsmanager.GetParameter(ctx, "/shop/woo/webhook/secret")
if err != nil {
log.Errorf("failed to get webhook secret from ssm: %s", err)
// ping=false, valid=false, err=err
return false, false, err
}
hash := hmac.New(sha256.New, []byte(secret))
hash.Write([]byte(request.Body))
sha := base64.StdEncoding.EncodeToString(hash.Sum(nil))
if sha != signature {
log.Errorf("wrong signature: expected = %s, got = %s", sha, signature)
// ping=false, valid=false, err=nil
return false, false, nil
}
// ping=false, valid=true, err=nil
return false, true, nil
}