This repository has been archived by the owner on Jan 20, 2023. It is now read-only.
/
main.go
197 lines (171 loc) · 5.66 KB
/
main.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
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"hash"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/ngmiller/fabrik/secure"
"github.com/ngmiller/fabrik/types"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
)
const (
// sha1Prefix is the prefix used by GitHub before the HMAC hexdigest.
sha1Prefix = "sha1"
// sha256Prefix and sha512Prefix are provided for future compatibility.
sha256Prefix = "sha256"
sha512Prefix = "sha512"
// HTTP request headers
signatureHeader = "X-Hub-Signature"
deliveryHeader = "X-GitHub-Delivery"
eventHeader = "X-GitHub-Event"
)
func main() {
lambda.Start(Handler)
}
// Handler captures the incoming webhook from GitHub, verifies its integrity with HMAC,
// and pushes the event onto a queue for processing.
func Handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
// AWS session
sess := session.Must(session.NewSession())
// Get HMAC key
secureStore := secure.NewAWSSecureStore(sess)
hmacKey, err := secureStore.Get(types.KeyHmac)
if err != nil {
fmt.Println("could not read hmac key: ", err.Error())
return events.APIGatewayProxyResponse{StatusCode: http.StatusInternalServerError}, nil
}
// Validate the request
signature := request.Headers[signatureHeader]
err = Validate(signature, []byte(request.Body), []byte(hmacKey))
if err != nil {
fmt.Println(err.Error())
return events.APIGatewayProxyResponse{StatusCode: http.StatusUnauthorized}, nil
}
// Push event into dynamo for further processing
id := request.Headers[deliveryHeader]
eventType := request.Headers[eventHeader]
payload := request.Body
item := EventItem(os.Getenv("EVENT_TABLE"), id, eventType, payload)
dbService := dynamodb.New(sess)
_, err = dbService.PutItem(item)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case dynamodb.ErrCodeConditionalCheckFailedException:
fmt.Println(dynamodb.ErrCodeConditionalCheckFailedException, aerr.Error())
case dynamodb.ErrCodeProvisionedThroughputExceededException:
fmt.Println(dynamodb.ErrCodeProvisionedThroughputExceededException, aerr.Error())
case dynamodb.ErrCodeResourceNotFoundException:
fmt.Println(dynamodb.ErrCodeResourceNotFoundException, aerr.Error())
case dynamodb.ErrCodeItemCollectionSizeLimitExceededException:
fmt.Println(dynamodb.ErrCodeItemCollectionSizeLimitExceededException, aerr.Error())
case dynamodb.ErrCodeInternalServerError:
fmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return events.APIGatewayProxyResponse{Body: "event write error", StatusCode: 500}, nil
}
return events.APIGatewayProxyResponse{Body: "ok", StatusCode: 200}, nil
}
// Validate returns an error if the signature does not match
// the payload. Returns nil if signature check is successful.
func Validate(sig string, payload, key []byte) error {
messageMAC, hashFunc, err := messageMAC(sig)
if err != nil {
return err
}
if !checkMAC(payload, messageMAC, key, hashFunc) {
return errors.New("signature check failed")
}
return nil
}
func EventItem(table, id, eventType, payload string) *dynamodb.PutItemInput {
// trim json payload
var p string
buf := new(bytes.Buffer)
if err := json.Compact(buf, []byte(payload)); err != nil {
// pass through, no trim
p = payload
} else {
p = buf.String()
}
now := time.Now().Unix()
expire := time.Now().Add(time.Hour * 24 * 30).Unix() // now + 30 days
return &dynamodb.PutItemInput{
TableName: aws.String(table),
Item: map[string]*dynamodb.AttributeValue{
"id": {S: aws.String(id)},
"type": {S: aws.String(eventType)},
"timestamp": {S: aws.String(strconv.FormatInt(now, 10))},
"payload": {S: aws.String(p)},
"ttl": {N: aws.String(strconv.FormatInt(expire, 10))},
},
}
}
//
// HMAC Helpers
// Shamelessly stolen from google/go-github's source.
// Their `ValidatePayload` function expects an incoming http.Request,
// whereas we have API Gateway requests.
//
// genMAC generates the HMAC signature for a message provided
// the secret key and hashFunc.
func genMAC(message, key []byte, hashFunc func() hash.Hash) []byte {
mac := hmac.New(hashFunc, key)
mac.Write(message)
return mac.Sum(nil)
}
// checkMAC reports whether messageMAC is a valid HMAC tag for message.
func checkMAC(message, messageMAC, key []byte, hashFunc func() hash.Hash) bool {
expectedMAC := genMAC(message, key, hashFunc)
return hmac.Equal(messageMAC, expectedMAC)
}
// messageMAC returns the hex-decoded HMAC tag from the signature and its
// corresponding hash function.
func messageMAC(signature string) ([]byte, func() hash.Hash, error) {
if signature == "" {
return nil, nil, errors.New("missing signature")
}
sigParts := strings.SplitN(signature, "=", 2)
if len(sigParts) != 2 {
return nil, nil, fmt.Errorf("error parsing signature %q", signature)
}
var hashFunc func() hash.Hash
switch sigParts[0] {
case sha1Prefix:
hashFunc = sha1.New
case sha256Prefix:
hashFunc = sha256.New
case sha512Prefix:
hashFunc = sha512.New
default:
return nil, nil, fmt.Errorf("unknown hash type prefix: %q", sigParts[0])
}
buf, err := hex.DecodeString(sigParts[1])
if err != nil {
return nil, nil, fmt.Errorf("error decoding signature %q: %v", signature, err)
}
return buf, hashFunc, nil
}