Repository navigation
Expand file tree
/
Copy pathhook.go
More file actions
65 lines (57 loc) · 1.43 KB
/
Copy pathhook.go
File metadata and controls
65 lines (57 loc) · 1.43 KB
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
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"fmt"
"hash"
"log"
"net/http"
"os/exec"
"strings"
)
type hook struct {
Repository, Secret string
Command struct {
Workdir, Exec string
}
}
func (h *hook) authorized(req *http.Request, payload []byte) error {
signature := strings.Split(req.Header.Get("X-Hub-Signature"), "=")
if len(signature) != 2 {
return fmt.Errorf("signature header is not provided, or is not valid: %s", signature)
}
var hasher func() hash.Hash
switch signature[0] {
case "sha1":
hasher = sha1.New
default:
return fmt.Errorf("unidentified hash method provided: %s", signature[0])
}
mac := hmac.New(hasher, []byte(h.Secret))
_, err := mac.Write(payload)
if err != nil {
return fmt.Errorf("failed to write hmac payload: %s", err)
}
expected := hex.EncodeToString(mac.Sum(nil))
if !hmac.Equal([]byte(signature[1]), []byte(expected)) {
return fmt.Errorf("could not match signatures")
}
return nil
}
func (h *hook) run(p *payload) error {
args := []string{
p.Pusher.Username,
p.Pusher.Email,
p.Commit.ID,
p.Commit.Message,
p.Commit.Timestamp,
}
cmd := exec.Command(h.Command.Exec, args...)
cmd.Dir = h.Command.Workdir
info := fmt.Sprintf(`run hook "%s" workdir "%s" command: %s`, h.Repository, cmd.Dir, h.Command.Exec)
log.Println(info, strings.Join(args, " "))
out, err := cmd.CombinedOutput()
log.Println("command output:", string(out))
return err
}