|
| 1 | +/* |
| 2 | +Package signature_jwt implements signature verification for MessageBird webhooks. |
| 3 | +
|
| 4 | +To use define a new validator using your MessageBird Signing key. Can be |
| 5 | +retrieved from https://dashboard.messagebird.com/developers/settings. |
| 6 | +This is NOT your API key. |
| 7 | +
|
| 8 | +You can use the ValidateRequest method, just pass the request and base url as parameters: |
| 9 | +
|
| 10 | + validator := signature_jwt.NewValidator([]byte("your signing key")) |
| 11 | + baseUrl := "https://yourdomain.com" |
| 12 | + if err := validator.ValidateRequest(r, baseUrl); err != nil { |
| 13 | + // handle error |
| 14 | + } |
| 15 | +
|
| 16 | +Or use the handler as a middleware for your server: |
| 17 | +
|
| 18 | + http.Handle("/path", validator.Validate(YourHandler, baseUrl)) |
| 19 | +
|
| 20 | +It will reject the requests that contain invalid signatures. |
| 21 | +
|
| 22 | +For more information, see https://developers.messagebird.com/docs/verify-http-requests |
| 23 | +*/ |
| 24 | +package signature_jwt |
| 25 | + |
| 26 | +import ( |
| 27 | + "bytes" |
| 28 | + "crypto/sha256" |
| 29 | + "encoding/hex" |
| 30 | + "fmt" |
| 31 | + "io/ioutil" |
| 32 | + "net/http" |
| 33 | + "net/url" |
| 34 | + "time" |
| 35 | + |
| 36 | + "github.com/golang-jwt/jwt" |
| 37 | +) |
| 38 | + |
| 39 | +const signatureHeader = "MessageBird-Signature-JWT" |
| 40 | + |
| 41 | +// TimeFunc provides the current time same as time.Now but can be overridden for testing. |
| 42 | +var TimeFunc = time.Now |
| 43 | + |
| 44 | +// allowedMethods lists the signing methods that we accept. We only allow symmetric-key |
| 45 | +// algorithms as our customer signing keys are currently all simple byte strings. HMAC is |
| 46 | +// also the only symkey signature method that is required by the RFC7518 Section 3.1 and |
| 47 | +// thus should be supported by all JWT implementations. |
| 48 | +var allowedMethods = []string{ |
| 49 | + jwt.SigningMethodHS256.Name, |
| 50 | + jwt.SigningMethodHS384.Name, |
| 51 | + jwt.SigningMethodHS512.Name, |
| 52 | +} |
| 53 | + |
| 54 | +// Validator type represents a MessageBird signature validator. |
| 55 | +type Validator struct { |
| 56 | + parser jwt.Parser |
| 57 | + keyFn jwt.Keyfunc |
| 58 | + |
| 59 | + skipURLValidation bool |
| 60 | +} |
| 61 | + |
| 62 | +type ValidatorOption func(*Validator) |
| 63 | + |
| 64 | +// SkipURLValidation instructs Validator to not validate url_hash claim. |
| 65 | +// It is recommended to not skip URL validation to ensure high security. |
| 66 | +// but the ability to skip URL validation is necessary in some cases, e.g. |
| 67 | +// your service is behind proxy or when you want to validate it yourself. |
| 68 | +// Note that if enabled, no query parameters should be trusted. |
| 69 | +func SkipURLValidation() ValidatorOption { |
| 70 | + return func(c *Validator) { |
| 71 | + c.skipURLValidation = true |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +// NewValidator returns a signature validator object. |
| 76 | +// Signing key can be retrieved from |
| 77 | +// https://dashboard.messagebird.com/developers/settings. |
| 78 | +// Note that this is NOT your API key. |
| 79 | +func NewValidator(signingKey string, opts ...ValidatorOption) *Validator { |
| 80 | + validator := &Validator{ |
| 81 | + parser: jwt.Parser{ |
| 82 | + ValidMethods: allowedMethods, |
| 83 | + }, |
| 84 | + keyFn: func(*jwt.Token) (interface{}, error) { return []byte(signingKey), nil }, |
| 85 | + } |
| 86 | + |
| 87 | + for _, opt := range opts { |
| 88 | + opt(validator) |
| 89 | + } |
| 90 | + |
| 91 | + return validator |
| 92 | +} |
| 93 | + |
| 94 | +// ValidateSignature returns the signature token claims when the signature |
| 95 | +// is validated successfully. Otherwise, an error is returned. |
| 96 | +// The provided url is the raw url including the protocol, hostname and |
| 97 | +// query string, e.g. https://example.com/?example=42. |
| 98 | +func (v *Validator) ValidateSignature(signature, url string, payload []byte) (jwt.Claims, error) { |
| 99 | + claims := Claims{ |
| 100 | + receivedTime: TimeFunc(), |
| 101 | + skipURLValidation: v.skipURLValidation, |
| 102 | + } |
| 103 | + |
| 104 | + if !v.skipURLValidation && url != "" { |
| 105 | + claims.correctURLHash = sha256Hash([]byte(url)) |
| 106 | + } |
| 107 | + if payload != nil && len(payload) != 0 { |
| 108 | + claims.correctPayloadHash = sha256Hash(payload) |
| 109 | + } |
| 110 | + |
| 111 | + if token, err := v.parser.ParseWithClaims(signature, &claims, v.keyFn); err != nil { |
| 112 | + return nil, fmt.Errorf("invalid jwt: %w", err) |
| 113 | + } else { |
| 114 | + return token.Claims, nil |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +// ValidateRequest is a method that takes care of the signature validation of |
| 119 | +// incoming requests. |
| 120 | +func (v *Validator) ValidateRequest(r *http.Request, baseURL string) error { |
| 121 | + signature := r.Header.Get(signatureHeader) |
| 122 | + if signature == "" { |
| 123 | + return fmt.Errorf("signature not found") |
| 124 | + } |
| 125 | + |
| 126 | + var fullURL string |
| 127 | + if !v.skipURLValidation && baseURL != "" { |
| 128 | + base, err := url.Parse(baseURL) |
| 129 | + if err != nil { |
| 130 | + return fmt.Errorf("error parsing base url: %v", err) |
| 131 | + } |
| 132 | + fullURL = base.ResolveReference(r.URL).String() |
| 133 | + } |
| 134 | + |
| 135 | + b, _ := ioutil.ReadAll(r.Body) |
| 136 | + if _, err := v.ValidateSignature(signature, fullURL, b); err != nil { |
| 137 | + return fmt.Errorf("invalid signature: %s", err.Error()) |
| 138 | + } |
| 139 | + r.Body = ioutil.NopCloser(bytes.NewBuffer(b)) |
| 140 | + return nil |
| 141 | +} |
| 142 | + |
| 143 | +// Validate is a handler wrapper that takes care of the signature validation of |
| 144 | +// incoming requests and rejects them if invalid or pass them on to your handler |
| 145 | +// otherwise. |
| 146 | +func (v *Validator) Validate(h http.Handler, baseURL string) http.Handler { |
| 147 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 148 | + if err := v.ValidateRequest(r, baseURL); err != nil { |
| 149 | + http.Error(w, "", http.StatusUnauthorized) |
| 150 | + return |
| 151 | + } |
| 152 | + h.ServeHTTP(w, r) |
| 153 | + }) |
| 154 | +} |
| 155 | + |
| 156 | +func sha256Hash(data []byte) string { |
| 157 | + h := sha256.Sum256(data) |
| 158 | + return hex.EncodeToString(h[:]) |
| 159 | +} |
0 commit comments