-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
102 lines (86 loc) · 2.52 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
package caddy_module_github_webhook
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"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"
"io"
"net/http"
"strings"
)
func init() {
caddy.RegisterModule(Middleware{})
httpcaddyfile.RegisterHandlerDirective("validate_github_webhook_payload", parseCaddyfile)
}
// Middleware implements an HTTP handler.
type Middleware struct {
Secret string `json:"secret,omitempty"`
}
// CaddyModule returns the Caddy module information.
func (Middleware) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.github_webhook_validation_payload",
New: func() caddy.Module { return new(Middleware) },
}
}
// Validate implements caddy.Validator.
func (m *Middleware) Validate() error {
if m.Secret == "" {
return fmt.Errorf("github webhook secret is empty")
}
return nil
}
// ServeHTTP implements caddyhttp.MiddlewareHandler.
func (m Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
var buffer bytes.Buffer
r.Body = io.NopCloser(io.TeeReader(r.Body, &buffer))
payloadBytes, err := io.ReadAll(r.Body)
if err != nil {
// bad request in case of payload error
w.WriteHeader(400)
_, err = w.Write(nil)
return err
}
r.Body = io.NopCloser(&buffer)
actual := []byte(strings.TrimPrefix(r.Header.Get("X-Hub-Signature-256"), "sha256="))
mac := hmac.New(sha256.New, []byte(m.Secret))
mac.Write(payloadBytes)
expected := []byte(hex.EncodeToString(mac.Sum(nil)))
if !hmac.Equal(actual, expected) {
// unauthorized in case of invalid signature
w.WriteHeader(401)
_, err = w.Write(nil)
return err
}
// pass to the next handler
return next.ServeHTTP(w, r)
}
// UnmarshalCaddyfile implements caddyfile.Unmarshaler.
func (m *Middleware) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
// consume directive name
d.Next()
// require an argument
if !d.NextArg() {
return d.ArgErr()
}
// store the argument
m.Secret = d.Val()
return nil
}
// parseCaddyfile unmarshals tokens from h into a new Middleware.
func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
var m Middleware
err := m.UnmarshalCaddyfile(h.Dispenser)
return m, err
}
// Interface guards
var (
_ caddy.Validator = (*Middleware)(nil)
_ caddyhttp.MiddlewareHandler = (*Middleware)(nil)
_ caddyfile.Unmarshaler = (*Middleware)(nil)
)