/
rebase.go
97 lines (78 loc) · 2.37 KB
/
rebase.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
93
94
95
96
97
package http
import (
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"strings"
"github.com/chrisledet/rebasebot/github"
"github.com/chrisledet/rebasebot/integrations"
)
func Rebase(w http.ResponseWriter, r *http.Request) {
receivedAt := time.Now()
logRequest(r)
if r.Method != "POST" {
w.WriteHeader(http.StatusNotFound)
logResponse(r, http.StatusNotFound, receivedAt)
return
}
var event github.Event
var responseStatus = http.StatusCreated
body, err := ioutil.ReadAll(r.Body)
if err != nil {
responseStatus = http.StatusInternalServerError
}
if !isVerifiedRequest(r.Header, body) {
w.WriteHeader(http.StatusUnauthorized)
logResponse(r, http.StatusUnauthorized, receivedAt)
return
}
if err := json.Unmarshal(body, &event); err != nil {
responseStatus = http.StatusBadRequest
log.Printf("http.request.body.parse_failed: %s\n", err.Error())
return
}
go func() {
if !(strings.Compare(event.Action, "created") == 0 && github.WasMentioned(event.Comment) && strings.Contains(event.Comment.Body, "rebase")) {
return
}
log.Printf("bot.rebase.started, name: %s\n", event.Repository.FullName)
defer log.Printf("bot.rebase.finished: %s\n", event.Repository.FullName)
pullRequest, err := event.Repository.FindPR(event.Issue.Number)
if err == nil {
integrations.GitRebase(pullRequest)
}
}()
w.WriteHeader(responseStatus)
logResponse(r, responseStatus, receivedAt)
}
func isVerifiedRequest(header http.Header, body []byte) bool {
serverSignature := os.Getenv("SECRET")
requestSignature := header.Get("X-Hub-Signature")
// when not set up with a secret
if len(serverSignature) < 1 {
log.Println("http.request.signature.verification.skipped")
return true
}
log.Println("http.request.signature.verification.started")
if len(requestSignature) < 1 {
log.Println("http.request.signature.verification.failed", "missing X-Hub-Signature header")
return false
}
mac := hmac.New(sha1.New, []byte(serverSignature))
mac.Write(body)
expectedMAC := mac.Sum(nil)
expectedSignature := "sha1=" + hex.EncodeToString(expectedMAC)
signatureMatched := hmac.Equal([]byte(expectedSignature), []byte(requestSignature))
if signatureMatched {
log.Println("http.request.signature.verification.passed")
} else {
log.Println("http.request.signature.verification.failed")
}
return signatureMatched
}