-
Notifications
You must be signed in to change notification settings - Fork 2
/
hook-handler.go
126 lines (107 loc) · 2.52 KB
/
hook-handler.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package main
import (
"bytes"
"fmt"
"log"
"net"
"net/http"
"os/exec"
"strings"
"text/template"
)
var templateFuncs = template.FuncMap{
"after": func(find, s string) string {
idx := strings.LastIndex(s, find)
if idx == -1 {
return s
}
return s[idx+len(find):]
},
}
type HookHandler struct {
Config Config
}
func (h HookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !h.isValidIp(r.RemoteAddr) {
fmt.Fprint(w, "Rejected!!!")
return
}
payload, err := parsePayload(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
go h.handlePayload(payload)
fmt.Fprint(w, "WebHook Received")
}
func (h HookHandler) handlePayload(payload Payload) {
//check if payload matches any of the rules
Rule:
for _, rule := range h.Config.Rules {
for _, criteria := range rule.Criteria {
if !payload.IsMatch(criteria) {
continue Rule
}
//we have a matching rule, run the command
output, err := runCommand(rule.Command, payload)
if err != nil {
fmt.Printf("Command Error:\n %s\n", err)
}
//format the output
outputStr := string(output)
if strings.HasSuffix(outputStr, "\n") {
outputStr = outputStr[:len(outputStr)-1]
}
outputStr = " " + strings.Replace(string(outputStr), "\n", "\n ", -1) + "\n"
fmt.Printf("Command output:\n%s", outputStr)
}
}
}
func runCommand(cmd string, payload Payload) (output []byte, err error) {
parsed, err := parseCommand(cmd, payload)
if err != nil {
return
}
parts := strings.Fields(parsed)
head := parts[0]
parts = parts[1:len(parts)]
output, err = exec.Command(head, parts...).CombinedOutput()
return
}
func parseCommand(cmd string, payload Payload) (string, error) {
tmpl, err := template.New(cmd).Funcs(templateFuncs).Parse(cmd)
if err != nil {
return "", err
}
out := bytes.NewBuffer(make([]byte, 0))
err = tmpl.Execute(out, payload)
if err != nil {
return "", err
}
return out.String(), nil
}
func parseCIDRs(cidrs []string) []*net.IPNet {
if len(cidrs) == 0 {
log.Fatal("No CIDRs specified")
}
cidrNet := make([]*net.IPNet, 0)
for _, cidr := range cidrs {
_, netCidr, err := net.ParseCIDR(cidr)
if err != nil {
log.Fatal(err)
}
cidrNet = append(cidrNet, netCidr)
}
return cidrNet
}
func (h HookHandler) isValidIp(addr string) bool {
ipParts := strings.Split(addr, ":")
ip := net.ParseIP(ipParts[0])
for _, cidr := range h.Config.CIDRs {
if cidr.Contains(ip) {
return true
}
fmt.Printf("IP %s is not in Github CIDR: %s\n", ip, cidr.String())
}
return false
}