forked from remind101/conveyor
/
hookshot.go
212 lines (170 loc) · 6.15 KB
/
hookshot.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
// Copyright 2014 Eric Holmes. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package hookshot is a router that de-multiplexes and authorizes github webhooks.
package hookshot
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"crypto/subtle"
"fmt"
"io/ioutil"
"net/http"
"golang.org/x/net/context"
)
const (
// HeaderEvent is the name of the header that contains the type of event.
HeaderEvent = "X-GitHub-Event"
// HeaderSignature is the name of the header that contains the signature.
HeaderSignature = "X-Hub-Signature"
)
var (
// DefaultNotFoundHandler is the default NotFoundHandler for a Router instance.
DefaultNotFoundHandler = http.HandlerFunc(http.NotFound)
// DefaultUnauthorizedHandler is the default UnauthorizedHandler for a Router
// instance, which responds with a 403 status and a plain text body.
DefaultUnauthorizedHandler = http.HandlerFunc(unauthorized)
)
// Router demultiplexes github hooks.
type Router struct {
// NotFoundHandler is called when a handler is not found for a given GitHub event.
// The nil value for NotFoundHandler
NotFoundHandler http.Handler
routes routes
}
// NewRouter returns a new Router.
func NewRouter() *Router {
return &Router{
routes: make(routes),
}
}
// Handle maps a github event to an http.Handler.
func (r *Router) Handle(event string, h http.Handler) {
r.routes[event] = h
}
// HandleFunc maps a github event to an http.HandlerFunc.
func (r *Router) HandleFunc(event string, fn func(http.ResponseWriter, *http.Request)) {
r.Handle(event, http.HandlerFunc(fn))
}
// Handler returns the http.Handler to use for the given request. It will
// always return a non nill Handler.
func (r *Router) Handler(req *http.Request) http.Handler {
event := req.Header.Get(HeaderEvent)
if h, ok := r.routes[event]; ok {
return h
}
return r.notFoundHandler()
}
// ServeHTTP implements the http.Handler interface to route a request to an
// appropriate http.Handler, based on the value of the X-GitHub-Event header.
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.ServeHTTPContext(context.Background(), w, req)
}
// contextHandler is an http handler that can propagate a context.Context.
type contextHandler interface {
ServeHTTPContext(context.Context, http.ResponseWriter, *http.Request) error
}
// ServeHTTPContext implements the httpx.Handler interface.
func (r *Router) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
h := r.Handler(req)
if h, ok := h.(contextHandler); ok {
return h.ServeHTTPContext(ctx, w, req)
}
h.ServeHTTP(w, req)
return nil
}
func (r *Router) notFoundHandler() http.Handler {
if r.NotFoundHandler == nil {
return DefaultNotFoundHandler
}
return r.NotFoundHandler
}
// routes maps a github event to an http.Handler.
type routes map[string]http.Handler
// SecretHandler is an http.Handler that will verify the authenticity of the
// request.
type SecretHandler struct {
// The secret to use to verify the request.
Secret string
// SetHeader controls what happens when the X-Hub-Signature header value does
// not match the calculated signature. Setting this value to true will set
// the X-Calculated-Signature header in the response.
//
// It's recommended that you only enable this for debugging purposes.
SetHeader bool
// Handler is the http.Handler that will be called if the request is
// authorized.
Handler http.Handler
// Unauthorized is the http.Handler that will be called if the request
// is not authorized.
Unauthorized http.Handler
}
// Authorize wraps an http.Handler to verify the authenticity of the request
// using the provided secret.
func Authorize(h http.Handler, secret string) *SecretHandler {
return &SecretHandler{Handler: h, Secret: secret}
}
// ServeHTTP implements the http.Handler interface.
func (h *SecretHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
h.ServeHTTPContext(context.Background(), w, req)
return
}
func (h *SecretHandler) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
if h.Unauthorized == nil {
h.Unauthorized = DefaultUnauthorizedHandler
}
// If a secret is provided, ensure that the request is verified.
if h.Secret != "" {
sig, ok := IsAuthorized(req, h.Secret)
if h.SetHeader {
w.Header().Set("X-Calculated-Signature", sig)
}
if !ok {
h.Unauthorized.ServeHTTP(w, req)
return nil
}
}
if handler, ok := h.Handler.(contextHandler); ok {
return handler.ServeHTTPContext(ctx, w, req)
}
h.Handler.ServeHTTP(w, req)
return nil
}
// Signature calculates the SHA1 HMAC signature of body, signed by the secret.
//
// When github-services makes a POST request, it includes a SHA1 HMAC signature
// of the request body, signed with the secret provided in the webhook configuration.
// See http://goo.gl/Oe4WwR.
func Signature(body []byte, secret string) string {
mac := hmac.New(sha1.New, []byte(secret))
mac.Write(body)
return fmt.Sprintf("%x", mac.Sum(nil))
}
// IsAuthorized checks that the calculated signature for the request matches the provided signature in
// the request headers. Returns the calculated signature, and a boolean value
// indicating whether or not the calculated signature matches the
// X-Hub-Signature value.
func IsAuthorized(r *http.Request, secret string) (string, bool) {
raw, er := ioutil.ReadAll(r.Body)
if er != nil {
return "", false
}
// Since we're reading the request from the network, r.Body will return EOF if any
// downstream http.Handler attempts to read it. We set it to a new io.ReadCloser
// that will read from the bytes in memory.
r.Body = ioutil.NopCloser(bytes.NewReader(raw))
sig := "sha1=" + Signature(raw, secret)
return sig, compareStrings(r.Header.Get(HeaderSignature), sig)
}
// compareStrings compares two strings in constant time.
func compareStrings(a, b string) bool {
if len(a) != len(b) {
return false
}
return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
}
// unauthorized is the default UnauthorizedHandler.
func unauthorized(w http.ResponseWriter, r *http.Request) {
http.Error(w, "The provided signature in the "+HeaderSignature+" header does not match.", 403)
}