-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutil.go
92 lines (76 loc) · 2.12 KB
/
util.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package httpinterface
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
func Respond(w http.ResponseWriter, statusCode int, v interface{}) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(v)
}
func VerifySignature(payload []byte, hash, key string) (bool, error) {
hashNew := strings.Replace(hash, "sha256=", "", 1)
sig, err := hex.DecodeString(hashNew)
if err != nil {
return false, err
}
mac := hmac.New(sha256.New, []byte(key))
_, err = mac.Write(payload)
if err != nil {
return false, err
}
return hmac.Equal(sig, mac.Sum(nil)), nil
}
// VirifyType - check if a given event type is supported
func VerifyEvent(eventType string, bodyInBytes []byte, configBranchName string) error {
switch eventType {
case "push":
var payload WebhookPayload
err := json.Unmarshal(bodyInBytes, &payload)
if err != nil {
return fmt.Errorf("Couldnt unmarshal push event - %v", err)
}
if payload.Ref == "" {
return fmt.Errorf("invalid payload: cannot find ref inside given payload")
}
branchStringArr := strings.Split(payload.Ref, "/")
branchString := branchStringArr[len(branchStringArr)-1]
if configBranchName != branchString {
return fmt.Errorf("request recieved but the push event is not for the configured branch")
}
return nil
case "release":
supportedReleaseActions := map[string]bool{
"published": true,
"created": false,
"released": false,
}
var payload ReleaseWebhookPayload
err := json.Unmarshal(bodyInBytes, &payload)
if err != nil {
return fmt.Errorf("couldnt unmarshal release event - %v", err)
}
supported, exists := supportedReleaseActions[payload.Action]
if exists && supported {
return nil
}
return fmt.Errorf("release event action %s is not enabled", payload.Action)
default:
return fmt.Errorf("event type %s: is not supported", eventType)
}
}
func StreamToByte(stream io.Reader) ([]byte, error) {
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(stream)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}