-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebhook.go
79 lines (64 loc) · 1.68 KB
/
webhook.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
package main
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
"os"
"strings"
"sync"
"github.com/uptrace/bunrouter"
"go.elara.ws/logger/log"
"lure.sh/lure/pkg/repos"
)
func registerWebhook(ctx context.Context, mux *bunrouter.Router) {
g := mux.WithMiddleware(apiErrorHandler)
g.POST("/webhook", func(w http.ResponseWriter, req bunrouter.Request) error {
if req.Header.Get("X-GitHub-Event") != "push" {
return HTTPError{http.StatusBadRequest, "only push events are accepted by this bot"}
}
err := verifySecure(req.Request)
if err != nil {
return err
}
go pullRepos(ctx)
return nil
})
}
func verifySecure(req *http.Request) error {
sigStr := req.Header.Get("X-Hub-Signature-256")
sig, err := hex.DecodeString(strings.TrimPrefix(sigStr, "sha256="))
if err != nil {
return HTTPError{http.StatusBadRequest, "invalid hmac value"}
}
secretStr, ok := os.LookupEnv("LURE_WEB_GITHUB_SECRET")
if !ok {
return HTTPError{http.StatusInternalServerError, "LURE_WEB_GITHUB_SECRET must be set to the secret used for setting up the github webhook"}
}
secret := []byte(secretStr)
h := hmac.New(sha256.New, secret)
_, err = io.Copy(h, req.Body)
if err != nil {
return err
}
if !hmac.Equal(h.Sum(nil), sig) {
log.Warn("Insecure webhook request").
Str("from", req.RemoteAddr).
Bytes("sig", sig).
Bytes("hmac", h.Sum(nil)).
Send()
return HTTPError{http.StatusUnauthorized, "insecure webhook request"}
}
return nil
}
var pullMtx sync.Mutex
func pullRepos(ctx context.Context) {
pullMtx.Lock()
defer pullMtx.Unlock()
err := repos.Pull(ctx, nil)
if err != nil {
log.Warn("Error while pulling repositories").Err(err).Send()
}
}