Repository navigation
Expand file tree
/
Copy pathmiddleware.go
More file actions
220 lines (187 loc) · 5.17 KB
/
Copy pathmiddleware.go
File metadata and controls
220 lines (187 loc) · 5.17 KB
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
package validate
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strings"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/layer8co/caddy-validate-github/matcher"
"go.uber.org/zap"
)
var (
_ caddy.Module = (*Middleware)(nil)
_ caddy.Provisioner = (*Middleware)(nil)
_ caddy.Validator = (*Middleware)(nil)
_ caddyfile.Unmarshaler = (*Middleware)(nil)
_ caddyhttp.MiddlewareHandler = (*Middleware)(nil)
)
func init() {
caddy.RegisterModule(Middleware{})
// Setting the Caddyfile's syntax directive name, and its parser.
httpcaddyfile.RegisterHandlerDirective("validate_github_webhook", parseCaddyfileHandler)
}
type Middleware struct {
Secret string `json:"secret,omitempty"`
// Match contains JSON paths and their expected string values.
// All conditions must match.
Match map[string]string `json:"match,omitempty"`
logger *zap.SugaredLogger
secret []byte
}
// CaddyModule returns the Caddy module information.
func (Middleware) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.validate_github_webhook",
New: func() caddy.Module { return new(Middleware) },
}
}
// Provision implements the caddy.Provisioner interface.
func (m *Middleware) Provision(ctx caddy.Context) error {
if m.logger == nil {
m.logger = ctx.Logger(m).Sugar()
}
if m.Match == nil {
m.Match = make(map[string]string)
}
return nil
}
// ServeHTTP implements the caddy.Handler interface.
func (m Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request,
next caddyhttp.Handler) error {
b, err := io.ReadAll(r.Body)
if err != nil {
m.logger.Errorf("reading request body: %v", err)
http.Error(w, "invalid signature", http.StatusForbidden)
return nil
}
_ = r.Body.Close()
if len(b) == 0 {
m.logger.Debug("cannot validate an empty request body")
http.Error(w, "invalid signature", http.StatusForbidden)
return nil
}
s := strings.TrimPrefix(r.Header.Get("X-Hub-Signature-256"), "sha256=")
if s == "" {
m.logger.Debug("missing X-Hub-Signature-256 header in request")
http.Error(w, "invalid signature", http.StatusForbidden)
return nil
}
sig, err := hex.DecodeString(s)
if err != nil {
m.logger.Debugf("error hex-decoding signature '%s': %v", s, err)
http.Error(w, "invalid signature", http.StatusForbidden)
return nil
}
// Check to see if github really knows the secret or not.
mac := hmac.New(sha256.New, m.secret)
mac.Write(b)
if sum := mac.Sum(nil); !hmac.Equal(sum, sig) { // constant time comparison
m.logger.Debugf("signature: expected '%x'; received '%s'", sum, s)
http.Error(w, "invalid signature", http.StatusForbidden)
return nil
}
// Now, Checking for the match conditions (If any)
if len(m.Match) != 0 {
yes, err := matcher.MatchesPayload(b, m.Match)
if err != nil {
m.logger.Debugf("Error when checking the match conditions: %s", err)
return nil
}
if !yes {
m.logger.Debugf("The match condition aren't met with the request from %s", r.RemoteAddr)
return nil
}
}
m.logger.Infof("successful github webhook invocation from %s", r.RemoteAddr)
// Reconstruct the consumed body, the next caddy directive might need the information.
r.Body = io.NopCloser(bytes.NewBuffer(b))
return next.ServeHTTP(w, r)
}
func (m *Middleware) Validate() error {
if m.Secret == "" {
return fmt.Errorf("empty secret")
}
m.secret = []byte(m.Secret)
return nil
}
// https://caddyserver.com/docs/extending-caddy/caddyfile
//
// # UnmarshalCaddyfile implements caddyfile.Unmarshaler
//
// First Syntax:
//
// validate_github_webhook <secret>
//
// Second Syntax:
// validate_github_webhook {
// secret <secret>
//
// match {
// workflow_run.status completed
// }
func (m *Middleware) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
// Consume the directive name!: validate_github_webhook
if !d.Next() {
return d.ArgErr()
}
// Legacy single-argument form: validate_github_webhook <secret>
if d.NextArg() {
m.Secret = d.Val()
if d.NextArg() {
return d.ArgErr() // too many arguments
}
return nil
}
// Block form
for nesting := d.Nesting(); d.NextBlock(nesting); {
switch d.Val() {
case "secret":
if !d.NextArg() {
return d.ArgErr()
}
m.Secret = d.Val()
if d.NextArg() {
return d.ArgErr()
}
case "match":
if m.Match == nil {
m.Match = make(map[string]string)
}
for nest := d.Nesting(); d.NextBlock(nest); {
path := d.Val()
if !d.NextArg() {
return d.ArgErr()
}
value := d.Val()
if d.NextArg() {
return d.ArgErr()
}
if _, exists := m.Match[path]; exists {
return d.Errf("duplicate match condition: %q", path)
}
m.Match[path] = value
}
default:
return d.Errf("unknown subdirective %q", d.Val())
}
}
if m.Secret == "" {
return d.Err("secret is required")
}
return nil
}
func parseCaddyfileHandler(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler,
error) {
m := new(Middleware)
if err := m.UnmarshalCaddyfile(h.Dispenser); err != nil {
return nil, err
}
return m, nil
}