-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathverifier.go
58 lines (47 loc) · 1.51 KB
/
verifier.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
56
57
58
package mobilepay
import (
"crypto/hmac"
"crypto/sha1"
b64 "encoding/base64"
"fmt"
"hash"
"net/http"
)
// Mobilepay signature header
const mpSignature = "x-mobilepay-signature"
type WebhooksVerifier struct {
webhookUrl []byte
signature []byte
hmac hash.Hash
}
// NewWebhooksVerifier is a helper function to verify incoming webhooks from Mobilepay.
// See https://mobilepaydev.github.io/MobilePay-Payments-API/docs/webhooks-api
// webhookUrl is your webhook url that you used to create the webhook.
// webhookSignatureKey is returned by Mobilepay when you create a webhook.
func NewWebhooksVerifier(header http.Header, webhookUrl, webhookSignatureKey string) (wv WebhooksVerifier, err error) {
signature := header.Get(mpSignature)
hash := hmac.New(sha1.New, []byte(webhookSignatureKey))
if webhookUrl == "" || signature == "" {
return WebhooksVerifier{}, ErrMissingVerifierProperties
}
if _, err := hash.Write([]byte(webhookUrl)); err != nil {
return WebhooksVerifier{}, err
}
return WebhooksVerifier{
webhookUrl: []byte(webhookUrl),
signature: []byte(signature),
hmac: hash,
}, nil
}
func (v *WebhooksVerifier) Write(body []byte) (n int, err error) {
return v.hmac.Write(body)
}
func (v WebhooksVerifier) Ensure() error {
computed := v.hmac.Sum(nil)
sEnc := b64.StdEncoding.EncodeToString(computed)
// constant time compare in order to prevent leaking information
if hmac.Equal([]byte(sEnc), v.signature) {
return nil
}
return fmt.Errorf("Computed unexpected signature of: %s", sEnc)
}