-
Notifications
You must be signed in to change notification settings - Fork 36
/
hook.go
81 lines (76 loc) · 1.91 KB
/
hook.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
package main
import (
"encoding/json"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"strings"
"github.com/gorilla/mux"
)
func hookHandler(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
id := params["id"]
clientIP := getClientIP(r)
if clientIP != strings.Split(r.RemoteAddr, ":")[0] {
log.Printf("Received hook for id '%s' from %s on %s\n", id, clientIP, r.RemoteAddr)
} else {
log.Printf("Received hook for id '%s' from %s\n", id, r.RemoteAddr)
}
rb, err := NewRunBook(id)
if err != nil {
log.Println(err.Error())
http.Error(w, err.Error(), 500)
return
}
host, _, _ := net.SplitHostPort(r.RemoteAddr)
remoteIP := net.ParseIP(host)
if !rb.AddrIsAllowed(remoteIP) {
log.Printf("Hook id '%s' is not allowed from %v\n", id, r.RemoteAddr)
http.Error(w, "Not authorized.", http.StatusUnauthorized)
return
}
interoplatePOSTData(rb, r)
response, err := rb.execute()
if err != nil {
log.Println(err.Error())
http.Error(w, err.Error(), 500)
return
}
if echo {
data, err := json.MarshalIndent(response, "", " ")
if err != nil {
log.Println(err.Error())
}
w.Write(data)
}
}
func interoplatePOSTData(rb *runBook, r *http.Request) {
if r.ContentLength == 0 {
return
}
data, err := ioutil.ReadAll(r.Body)
if err != nil && err != io.EOF {
log.Fatal(err)
return
}
defer r.Body.Close()
stringData := string(data[:r.ContentLength])
for i := range rb.Scripts {
for j := range rb.Scripts[i].Args {
rb.Scripts[i].Args[j] = strings.Replace(rb.Scripts[i].Args[j], "{{POST}}", stringData, -1)
}
}
}
func getClientIP(r *http.Request) string {
remoteIP := strings.Split(r.RemoteAddr, ":")[0]
if !proxy {
return remoteIP
}
headerVal := r.Header.Get(proxyHeader)
// proxies can chain upstream client addresses- take only the closest (last) address
// http://en.wikipedia.org/wiki/X-Forwarded-For
upstreams := strings.Split(headerVal, ", ")
return upstreams[len(upstreams)-1]
}