/
handlers.go
252 lines (202 loc) · 7.35 KB
/
handlers.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package frontend
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/aws/aws-lambda-go/events"
"github.com/tidwall/gjson"
"github.com/heupr/heupr/backend"
)
// APIResponse generates required output for proxy integrations
func APIResponse(code int, msg string) (events.APIGatewayProxyResponse, error) {
log.Printf("response code: %d, message: %s\n", code, msg)
resp := events.APIGatewayProxyResponse{
StatusCode: code,
Body: msg,
IsBase64Encoded: false,
}
if msg == "success" || msg == "query already exists" {
return resp, nil
}
return resp, errors.New(msg)
}
type installConfig struct {
AppID int64 `json:"id"`
FullName string `json:"full_name"`
PEM string `json:"pem"`
WebhookSecret string `json:"webhook_secret"`
InstallationID int64 `json:"installation_id"`
}
var post = func(req *http.Request) (*http.Response, error) {
client := &http.Client{}
return client.Do(req)
}
// Install configures a new repo installation for the Heupr app
func Install(request events.APIGatewayProxyRequest, db Database) (events.APIGatewayProxyResponse, error) {
log.Printf("install request: %+v\n", request)
code := request.QueryStringParameters["code"]
if code == "" {
return APIResponse(http.StatusBadRequest, "no code received")
}
log.Printf("request code: %s\n", code)
b := new(bytes.Buffer)
req, err := http.NewRequest("POST", "https://api.github.com/app-manifests/"+code+"/conversions", b)
if err != nil {
return APIResponse(http.StatusInternalServerError, "error creating response: "+err.Error())
}
req.Header.Set("Accept", "application/vnd.github.fury-preview+json")
resp, err := post(req)
if err != nil {
return APIResponse(http.StatusInternalServerError, "error converting code: "+err.Error())
}
defer resp.Body.Close()
log.Printf("manifest response: %+v\n", resp)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return APIResponse(http.StatusInternalServerError, "error reading conversion body")
}
log.Printf("request body: %s\n", body)
config := installConfig{}
if err := json.Unmarshal(body, &config); err != nil {
return APIResponse(http.StatusInternalServerError, "error parsing conversion body")
}
log.Printf("installation config: %+v\n", config)
if err := db.Put(config); err != nil {
return APIResponse(http.StatusInternalServerError, "error putting app config: "+err.Error())
}
log.Println("successful install handler invocation")
return events.APIGatewayProxyResponse{
StatusCode: 302,
Headers: map[string]string{
"Location": "https://heupr.github.io/success",
},
Body: "success",
IsBase64Encoded: false,
}, nil
}
type webhookEvent struct {
Name string `yaml:"name"`
Actions []string `yaml:"actions"`
}
type backendObj struct {
Name string `yaml:"name"`
Events []webhookEvent `yaml:"events"`
Location string `yaml:"location"`
}
type configObj struct {
Backends []backendObj `yaml:"backends"`
}
type payload struct {
B []byte
T string
C []byte
}
func (p *payload) Bytes() []byte {
return p.B
}
func (p *payload) Type() string {
return p.T
}
func (p *payload) Config() []byte {
return p.C
}
// Event processes webhook events received by Heupr app repo installations
func Event(request events.APIGatewayProxyRequest, db Database, bknds []backend.Backend) (events.APIGatewayProxyResponse, error) {
log.Printf("event request: %+v\n", request)
eventType := request.Headers["X-GitHub-Event"]
signature := request.Headers["X-Hub-Signature"]
log.Printf("event type: %s, signature: %s\n", eventType, signature)
body := []byte(request.Body)
switch eventType {
case "installation", "integration_installation", "installation_repositories", "integration_installation_repositories": // NOTE: Last two kept for GitHub inconsistency
appID := gjson.Get(request.Body, "installation.app_id").Int()
installationID := gjson.Get(request.Body, "installation.id").Int()
log.Printf("app id: %d, installation id: %d\n", appID, installationID)
installConfig, err := db.Get(appID)
if err != nil {
return APIResponse(http.StatusInternalServerError, "error getting config: "+err.Error())
}
if err := validateEvent(installConfig.WebhookSecret, signature, body); err != nil {
return APIResponse(http.StatusInternalServerError, "error validating event: "+err.Error())
}
repos := gjson.Result{}
if !strings.Contains(eventType, "repositories") {
repos = gjson.Get(request.Body, "repositories.#.full_name")
} else {
repos = gjson.Get(request.Body, "repositories_added.#.full_name")
}
log.Printf("repositories: %v\n", repos)
for _, repo := range repos.Array() {
fullName := repo.String()
log.Printf("repository: %s\n", fullName)
installConfig.FullName = fullName
installConfig.InstallationID = installationID
client, err := newClient(installConfig.AppID, installConfig.InstallationID, installConfig.PEM)
if err != nil {
return APIResponse(http.StatusInternalServerError, "error creating client: "+err.Error())
}
if err := db.Put(installConfig); err != nil {
return APIResponse(http.StatusInternalServerError, "error putting app config: "+err.Error())
}
fullNameSplit := strings.Split(fullName, "/")
file, err := getContent(client, fullNameSplit[0], fullNameSplit[1], ".heupr.yml")
if err != nil {
return APIResponse(http.StatusInternalServerError, "error getting repo config file: "+err.Error())
}
log.Printf("file content: %s\n", file)
backendPayload := &payload{
T: eventType,
B: body,
C: []byte(file),
}
for _, bknd := range bknds {
bknd.Configure(client)
if err := bknd.Prepare(backendPayload); err != nil {
return APIResponse(http.StatusInternalServerError, "error calling backend prepare: "+err.Error())
}
}
}
case "issues", "pull_request", "project", "project_card", "project_column":
fullName := gjson.Get(request.Body, "repository.full_name").String()
installConfig, err := db.Get(fullName)
if err != nil {
return APIResponse(http.StatusInternalServerError, "error getting config: "+err.Error())
}
log.Printf("installation config: %+v\n", installConfig)
if err := validateEvent(installConfig.WebhookSecret, signature, body); err != nil {
return APIResponse(http.StatusInternalServerError, "error validating event: "+err.Error())
}
client, err := newClient(installConfig.AppID, installConfig.InstallationID, installConfig.PEM)
if err != nil {
return APIResponse(http.StatusInternalServerError, "error creating client: "+err.Error())
}
fullNameSplit := strings.Split(fullName, "/")
file, err := getContent(client, fullNameSplit[0], fullNameSplit[1], ".heupr.yml")
if err != nil {
return APIResponse(http.StatusInternalServerError, "error getting repo config file: "+err.Error())
}
log.Printf("file content: %s\n", file)
backendPayload := &payload{
T: eventType,
B: body,
C: []byte(file),
}
for _, bknd := range bknds {
bknd.Configure(client)
if err := bknd.Act(backendPayload); err != nil {
return APIResponse(http.StatusInternalServerError, "error calling backend act: "+err.Error())
}
}
default:
message := fmt.Sprintf("event type %s not supported", eventType)
log.Println(message)
return APIResponse(http.StatusInternalServerError, message)
}
log.Println("successful event handler invocation")
return APIResponse(http.StatusOK, "success")
}