-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
46 lines (40 loc) · 1.11 KB
/
main.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
package ghclient
import (
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"io/ioutil"
"log"
"net/http"
"strings"
)
// ParseHeaders is used to return the EventID and GitHubEvent from request headers
func ParseHeaders(r *http.Request) (string, string) {
EventID := r.Header.Get("X-GitHub-Delivery")
GitHubEvent := r.Header.Get("X-GitHub-Event")
return EventID, GitHubEvent
}
// IsValidSignature validates the message body with the checksum sent by GitHub
func IsValidSignature(r *http.Request, key string) bool {
gotHash := strings.SplitN(r.Header.Get("X-Hub-Signature"), "=", 2)
if gotHash[0] != "sha1" {
log.Panicf("Checksum is invalid")
return false
}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Panicf("Cannot read the request body: %s", err)
return false
}
hash := hmac.New(sha1.New, []byte(key))
if _, err := hash.Write(b); err != nil {
log.Panicf("Cannot compute the HMAC for request: %s", err)
return false
}
expectedHash := hex.EncodeToString(hash.Sum(nil))
isValid := gotHash[1] == expectedHash
if isValid == false {
log.Panicf("Invalid Hash: %s", expectedHash)
}
return isValid
}