Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: improved webhook verification logic #35

Merged
merged 2 commits into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 54 additions & 44 deletions webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"errors"
"fmt"
"hash"
"io"
"net/http"
"strconv"
"strings"
"time"
Expand All @@ -27,6 +29,7 @@ var (
DefaultTolerance = 300 * time.Second
DefaultEncoding EncodingType = HexEncoding
DefaultHash = "SHA256"
DefaultSigHeader = "X-Convoy-Signature"
)

type signedHeader struct {
Expand All @@ -36,23 +39,15 @@ type signedHeader struct {
}

type Webhook struct {
Payload []byte
SigHeader string
Secret string
IsAdvanced bool
Encoding EncodingType
Hash string
Tolerance time.Duration
opts *WebhookOpts
}

type ConfigOpts struct {
Payload []byte
SigHeader string
Secret string
IsAdvanced bool
Encoding EncodingType
Hash string
Tolerance time.Duration
type WebhookOpts struct {
SigHeader string
Secret string
Encoding EncodingType
Hash string
Tolerance time.Duration
}

type EncodingType string
Expand All @@ -62,43 +57,58 @@ const (
HexEncoding EncodingType = "hex"
)

func NewWebhook(data *ConfigOpts) *Webhook {
w := &Webhook{
Payload: data.Payload,
SigHeader: data.SigHeader,
Secret: data.Secret,
Hash: data.Hash,
Encoding: data.Encoding,
Tolerance: data.Tolerance,
func NewWebhook(opts *WebhookOpts) *Webhook {

if isStringEmpty(opts.Hash) {
opts.Hash = DefaultHash
}

if w.Hash == "" {
w.Hash = DefaultHash
if isStringEmpty(string(opts.Encoding)) {
opts.Encoding = DefaultEncoding
}

if w.Encoding == "" {
w.Encoding = DefaultEncoding
if opts.Tolerance == 0 {
opts.Tolerance = DefaultTolerance
}

if w.Tolerance == 0 {
w.Tolerance = DefaultTolerance
if isStringEmpty(opts.SigHeader) {
opts.SigHeader = DefaultSigHeader
}

return w
return &Webhook{opts}
}

func (w *Webhook) VerifyRequest(r *http.Request) error {
body, err := io.ReadAll(r.Body)
if err != nil {
return err
}

header := r.Header.Get(w.opts.SigHeader)
if isStringEmpty(header) {
fmt.Println("MAL")
return ErrInvalidHeader
}

return w.verify(body, header)
}

func (w *Webhook) VerifyPayload(b []byte, header string) error {
return w.verify(b, header)
}

func (w *Webhook) Verify() error {
header, err := w.parseSignatureHeader()
func (w *Webhook) verify(body []byte, header string) error {
sh, err := w.parseSignatureHeader(header)
if err != nil {
return err
}

expectedSignature, err := w.generateSignature(header)
expectedSignature, err := w.generateSignature(sh, body)
if err != nil {
return err
}

for _, sig := range header.signatures {
for _, sig := range sh.signatures {
// Check all signatures for a match
if hmac.Equal(expectedSignature, sig) {
return nil
Expand All @@ -108,22 +118,22 @@ func (w *Webhook) Verify() error {
return ErrInvalidSignature
}

func (w *Webhook) parseSignatureHeader() (*signedHeader, error) {
func (w *Webhook) parseSignatureHeader(header string) (*signedHeader, error) {
var err error
sh := &signedHeader{}

if w.SigHeader == "" {
if isStringEmpty(header) {
return sh, ErrInvalidSignatureHeader
}

pairs := strings.Split(w.SigHeader, ",")
pairs := strings.Split(header, ",")
if len(pairs) > 1 {
sh, err = w.decodeAdvanced(sh, pairs)
if err != nil {
return sh, err
}
} else {
sh, err = w.decodeSimple(sh, w.SigHeader)
sh, err = w.decodeSimple(sh, header)
if err != nil {
return sh, err
}
Expand All @@ -136,20 +146,20 @@ func (w *Webhook) parseSignatureHeader() (*signedHeader, error) {
return sh, nil
}

func (w *Webhook) generateSignature(sh *signedHeader) ([]byte, error) {
fn, err := w.getHashFunction(w.Hash)
func (w *Webhook) generateSignature(sh *signedHeader, body []byte) ([]byte, error) {
fn, err := w.getHashFunction(w.opts.Hash)
if err != nil {
return nil, err
}

h := hmac.New(fn, []byte(w.Secret))
h := hmac.New(fn, []byte(w.opts.Secret))

if sh.isAdvanced {
h.Write([]byte(fmt.Sprintf("%d", sh.timestamp.Unix())))
h.Write([]byte(","))
}

h.Write(w.Payload)
h.Write(body)
return h.Sum(nil), nil
}

Expand Down Expand Up @@ -192,7 +202,7 @@ func (w *Webhook) decodeAdvanced(sh *signedHeader, pairs []string) (*signedHeade
}
}

expiredTimestamp := time.Since(sh.timestamp) > w.Tolerance
expiredTimestamp := time.Since(sh.timestamp) > w.opts.Tolerance
if expiredTimestamp {
return nil, ErrTimestampExpired
}
Expand All @@ -212,7 +222,7 @@ func (w *Webhook) decodeSimple(sh *signedHeader, value string) (*signedHeader, e
}

func (w *Webhook) decodeString(value string) ([]byte, error) {
switch w.Encoding {
switch w.opts.Encoding {
case HexEncoding:
sig, err := hex.DecodeString(value)
return sig, err
Expand Down
139 changes: 99 additions & 40 deletions webhook_test.go
Original file line number Diff line number Diff line change
@@ -1,90 +1,149 @@
package convoy_go

import (
"bytes"
"net/http"
"testing"

"github.com/stretchr/testify/require"
)

func Test_Webhook_Verifier(t *testing.T) {
func Test_Webhook_VerifyRequest(t *testing.T) {
tests := map[string]struct {
data *ConfigOpts
opts *WebhookOpts
req func() *http.Request
expectedError error
}{
"invalid_signature": {
data: &ConfigOpts{
"invalid_header": {
opts: &WebhookOpts{
SigHeader: "",
Payload: []byte("test payload"),
Secret: "random_secret",
},
expectedError: ErrInvalidSignatureHeader,
req: func() *http.Request {
body := bytes.NewBuffer([]byte(``))
req, err := http.NewRequest(http.MethodPost, "localhost:5005", body)
require.NoError(t, err)

return req
},
expectedError: ErrInvalidHeader,
},
"should_verify_simple_hex_signature": {
data: &ConfigOpts{
SigHeader: "666060cbe1348bbc7ec98f4e93dda8eaaf11bbf283d6a2dd56e841b2ef12fcd465c846903f709942473e1442604798186746f04848702c44a773f80672de7b21",
Payload: []byte(`{"email":"test@gmail.com","first_name":"test","last_name":"test"}`),
Secret: "8IX9njirDG",
Hash: "SHA512",
Encoding: "hex",
opts: &WebhookOpts{
Secret: "8IX9njirDG",
Hash: "SHA512",
Encoding: "hex",
},
req: func() *http.Request {
body := bytes.NewBuffer([]byte(`{"email":"test@gmail.com","first_name":"test","last_name":"test"}`))
req, err := http.NewRequest(http.MethodPost, "localhost:5005", body)
require.NoError(t, err)

req.Header.Add(DefaultSigHeader,
"666060cbe1348bbc7ec98f4e93dda8eaaf11bbf283d6a2dd56e841b2ef12fcd465c846903f709942473e1442604798186746f04848702c44a773f80672de7b21")

return req
},
expectedError: nil,
},
"should_verify_simple_base64_signature": {
data: &ConfigOpts{
SigHeader: "ZmBgy+E0i7x+yY9Ok92o6q8Ru/KD1qLdVuhBsu8S/NRlyEaQP3CZQkc+FEJgR5gYZ0bwSEhwLESnc/gGct57IQ==",
Payload: []byte(`{"email":"test@gmail.com","first_name":"test","last_name":"test"}`),
Secret: "8IX9njirDG",
Hash: "SHA512",
Encoding: "base64",
opts: &WebhookOpts{
Secret: "8IX9njirDG",
Hash: "SHA512",
Encoding: "base64",
},
req: func() *http.Request {
body := bytes.NewBuffer([]byte(`{"email":"test@gmail.com","first_name":"test","last_name":"test"}`))
req, err := http.NewRequest(http.MethodPost, "localhost:5005", body)
require.NoError(t, err)

req.Header.Add(DefaultSigHeader,
"ZmBgy+E0i7x+yY9Ok92o6q8Ru/KD1qLdVuhBsu8S/NRlyEaQP3CZQkc+FEJgR5gYZ0bwSEhwLESnc/gGct57IQ==")

return req
},
expectedError: nil,
},
"invalid_signature_header": {
data: &ConfigOpts{
SigHeader: "d33C9sJXVO4CnE1hisHHQzUf0inr5KWJH7T8+zvgATTWEgAq5vErZR/xihDXqtok5ubv77xGP/RE++NphZnWLg==",
Payload: []byte(`{"email":"test@gmail.com","first_name":"test","last_name":"test"}`),
Secret: "8IX9njirDG",
Hash: "SHA512",
Encoding: "base64",
opts: &WebhookOpts{
Secret: "8IX9njirDG",
Hash: "SHA512",
Encoding: "base64",
},
req: func() *http.Request {
body := bytes.NewBuffer([]byte(`{"email":"test@gmail.com","first_name":"test","last_name":"test"}`))
req, err := http.NewRequest(http.MethodPost, "localhost:5005", body)
require.NoError(t, err)

req.Header.Add(DefaultSigHeader,
"d33C9sJXVO4CnE1hisHHQzUf0inr5KWJH7T8+zvgATTWEgAq5vErZR/xihDXqtok5ubv77xGP/RE++NphZnWLg==")

return req
},
expectedError: ErrInvalidSignature,
},
"should_verify_advanced_hex_signature": {
data: &ConfigOpts{
SigHeader: "t=2048976161,v1=c6c39e1bd410fc1dc4db90e97039f006d088c950a275296767595d330195088f,v1=6594ee0713f1cc1f54c3f713d06a60718cd10949c7684412f159034d49621e07",
Payload: []byte(`{"email":"test@gmail.com"}`),
Secret: "Convoy",
Hash: "SHA256",
Encoding: "hex",
opts: &WebhookOpts{
Secret: "Convoy",
Hash: "SHA256",
Encoding: "hex",
},
req: func() *http.Request {
body := bytes.NewBuffer([]byte(`{"email":"test@gmail.com"}`))
req, err := http.NewRequest(http.MethodPost, "localhost:5005", body)
require.NoError(t, err)

req.Header.Add(DefaultSigHeader,
"t=2048976161,v1=c6c39e1bd410fc1dc4db90e97039f006d088c950a275296767595d330195088f,v1=6594ee0713f1cc1f54c3f713d06a60718cd10949c7684412f159034d49621e07")

return req
},
expectedError: nil,
},
"should_verify_advanced_base64_signature": {
data: &ConfigOpts{
SigHeader: "t=2048976161,v1=afdb90313acfa15a3fc425755ae651a204947710315bb2a90bccaa87fce88998,v1=fLBDCBUiX5iIs0L5zfNq45h23EkX1HAMpFF+2lHrnes=",
Payload: []byte(`{"email":"test@gmail.com"}`),
Secret: "8IX9njirDG",
Hash: "SHA256",
Encoding: "base64",
opts: &WebhookOpts{
Secret: "8IX9njirDG",
Hash: "SHA256",
Encoding: "base64",
},
req: func() *http.Request {
body := bytes.NewBuffer([]byte(`{"email":"test@gmail.com"}`))

req, err := http.NewRequest(http.MethodPost, "localhost:5005", body)
require.NoError(t, err)

req.Header.Add(DefaultSigHeader,
"t=2048976161,v1=afdb90313acfa15a3fc425755ae651a204947710315bb2a90bccaa87fce88998,v1=fLBDCBUiX5iIs0L5zfNq45h23EkX1HAMpFF+2lHrnes=")

return req
},
},
"invalid_timestamp_header": {
data: &ConfigOpts{
opts: &WebhookOpts{
SigHeader: "t=2202-1-1,v1=U5yBiZmFYHiom0A5hEnfLPCoQzndno4ocR45W/zkO+w=",
Payload: []byte(`{"email":"test@gmail.com"}`),
Secret: "8IX9njirDG",
Hash: "SHA256",
Encoding: "base64",
},
req: func() *http.Request {
body := bytes.NewBuffer([]byte(`{"email":"test@gmail.com"}`))
req, err := http.NewRequest(http.MethodPost, "localhost:5005", body)
require.NoError(t, err)

req.Header.Add(DefaultSigHeader,
"t=2202-1-1,v1=U5yBiZmFYHiom0A5hEnfLPCoQzndno4ocR45W/zkO+w=")

return req
},
expectedError: ErrInvalidHeader,
},
}

for name, tc := range tests {
t.Run(name, func(t *testing.T) {
w := NewWebhook(tc.data)
w := NewWebhook(tc.opts)

err := w.Verify()
err := w.VerifyRequest(tc.req())

require.ErrorIs(t, err, tc.expectedError)
})
Expand Down
Loading