forked from livekit/protocol
-
Notifications
You must be signed in to change notification settings - Fork 0
/
verifier.go
70 lines (58 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
59
60
61
62
63
64
65
66
67
68
69
70
package webhook
import (
"crypto/sha256"
"encoding/base64"
"io/ioutil"
"net/http"
"google.golang.org/protobuf/encoding/protojson"
"github.com/abdulhaseeb08/protocol/auth"
"github.com/abdulhaseeb08/protocol/livekit"
)
// Receive reads and verifies incoming webhook is signed with key/secret pair
// closes body after reading
func Receive(r *http.Request, provider auth.KeyProvider) ([]byte, error) {
defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
authToken := r.Header.Get(authHeader)
if authToken == "" {
return nil, ErrNoAuthHeader
}
v, err := auth.ParseAPIToken(authToken)
if err != nil {
return nil, err
}
secret := provider.GetSecret(v.APIKey())
if secret == "" {
return nil, ErrSecretNotFound
}
claims, err := v.Verify(secret)
if err != nil {
return nil, err
}
// verify checksum
sha := sha256.Sum256(data)
hash := base64.StdEncoding.EncodeToString(sha[:])
if claims.Sha256 != hash {
return nil, ErrInvalidChecksum
}
return data, nil
}
// ReceiveWebhookEvent reads and verifies incoming webhook, and returns a parsed WebhookEvent
func ReceiveWebhookEvent(r *http.Request, provider auth.KeyProvider) (*livekit.WebhookEvent, error) {
data, err := Receive(r, provider)
if err != nil {
return nil, err
}
unmarshalOpts := protojson.UnmarshalOptions{
DiscardUnknown: true,
AllowPartial: true,
}
event := livekit.WebhookEvent{}
if err = unmarshalOpts.Unmarshal(data, &event); err != nil {
return nil, err
}
return &event, nil
}