Repository navigation
Expand file tree
/
Copy pathswt.go
More file actions
862 lines (757 loc) · 25.4 KB
/
Copy pathswt.go
File metadata and controls
862 lines (757 loc) · 25.4 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
package swt
import (
"context"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/sha256"
"crypto/sha3"
"crypto/sha512"
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
"hash"
"io"
"log/slog"
"net/http"
"strings"
"sync"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
)
const (
defaultExpiration = 5 * time.Minute
defaultHashAlgorithm = "sha-256"
defaultMaxBodySize = 32 << 20 // 32MB
jwtHeaderTyp = "SWT" // Custom type for identifying an JWT as a Secure Webhook Token
webhookClaim = "webhook"
// Supported hash algorithms
SHA256 = "sha-256"
SHA384 = "sha-384"
SHA512 = "sha-512"
SHA3_256 = "sha3-256"
SHA3_384 = "sha3-384"
SHA3_512 = "sha3-512"
)
var (
ErrInvalidToken = errors.New("invalid token - please use New or NewWithClaims to properly initialize token")
ErrMissingClaims = errors.New("missing claims")
ErrInvalidOption = errors.New("invalid option")
ErrInvalidData = errors.New("invalid data")
ErrInvalidTokenHandler = errors.New("invalid token handler function")
ErrInvalidHeaderClaim = errors.New("invalid token header claim")
ErrUnsupportedHashAlgorithm = errors.New("unsupported hash algorithm")
ErrDuplicateToken = errors.New("duplicate token detected")
ErrMissingSecret = errors.New("missing secret key or KeyProvider")
// validSigningMethods defines the allowed signing methods.
// Draft-03 allows both symmetric (HMAC) and asymmetric (RSA, ECDSA, EdDSA) methods.
validSigningMethods = []string{
"HS256", "HS384", "HS512",
"RS256", "RS384", "RS512",
"ES256", "ES384", "ES512",
"EdDSA",
"PS256", "PS384", "PS512",
}
// Ensure Claims implements WebhookClaims
_ Claims = (*WebhookClaims)(nil)
)
// New creates a SecureWebhookToken with the given issuer, event name, and data.
// Can be further customized with additional Option parameters.
// See Option for available functional parameters.
// Returns an error if claims or options are invalid.
func New(issuer, event string, hash *Hash, opts ...Option) (*SecureWebhookToken, error) {
claims := NewWebhookClaims(issuer, event)
claims.Webhook.Hash = hash
return NewWithClaims(&claims, opts...)
}
// NewWithClaims creates a new SecureWebhookToken with the given Claims object.
// Must be a pointer to an instance of WebhookClaims or a custom Claims instance, which embeds the WebhookClaims.
// Returns an error if claims are nil, options are invalid, or signing method is "none".
func NewWithClaims(c Claims, opts ...Option) (*SecureWebhookToken, error) {
if c == nil {
return nil, ErrMissingClaims
}
swt := &SecureWebhookToken{token: &jwt.Token{Claims: c}}
for _, opt := range opts {
if opt == nil {
return nil, ErrInvalidOption
}
opt(swt)
}
// In case the signingMethod was set to nil via WithSigningMethod.
if swt.token.Method == nil {
swt.token.Method = jwt.SigningMethodHS256
}
// Disallow "none" JWT signing algorithm.
if swt.token.Method.Alg() == "none" {
return nil, jwt.NoneSignatureTypeDisallowedError
}
savedHeader := swt.token.Header
method := swt.token.Method
// Create the JWT
swt.token = jwt.NewWithClaims(method, swt.token.Claims)
for k, v := range savedHeader {
swt.token.Header[k] = v
}
// Set the SWT specific Typ on the JWT Header
swt.token.Header["typ"] = jwtHeaderTyp
return swt, nil
}
// NewWebhookClaims creates WebhookClaims with a given issuer, event name and hash, and the default registered claims.
func NewWebhookClaims(issuer, event string) WebhookClaims {
return WebhookClaims{
Webhook: Webhook{
Event: event,
},
RegisteredClaims: newRegClaims(issuer),
}
}
// ReplayChecker is an interface for checking and recording token IDs to prevent replay attacks.
// Implementations should store the jti (JWT ID) claim and reject tokens with previously seen IDs.
type ReplayChecker interface {
// CheckAndRecord checks if a token ID has been seen before and records it if not.
// Returns an error if the token has already been processed (replay attack detected).
CheckAndRecord(ctx context.Context, jti string) error
}
// MemoryReplayChecker is an in-memory, thread-safe implementation of ReplayChecker.
// It tracks seen JWT IDs (jti) with an expiration timestamp and automatically purges expired entries.
type MemoryReplayChecker struct {
mu sync.Mutex
entries map[string]time.Time
ttl time.Duration
nowFunc func() time.Time
}
// NewMemoryReplayChecker creates a new in-memory ReplayChecker with the specified TTL.
// If ttl <= 0, defaultExpiration (5 minutes) is used.
func NewMemoryReplayChecker(ttl time.Duration) *MemoryReplayChecker {
return NewMemoryReplayCheckerWithClock(ttl, nil)
}
// NewMemoryReplayCheckerWithClock creates an in-memory ReplayChecker using a custom clock function.
// If nowFunc is nil, time.Now is used.
func NewMemoryReplayCheckerWithClock(ttl time.Duration, nowFunc func() time.Time) *MemoryReplayChecker {
if ttl <= 0 {
ttl = defaultExpiration
}
if nowFunc == nil {
nowFunc = time.Now
}
return &MemoryReplayChecker{
entries: make(map[string]time.Time),
ttl: ttl,
nowFunc: nowFunc,
}
}
// CheckAndRecord checks if a token ID has been seen before and records it if not.
// Returns ErrDuplicateToken if the token has already been recorded and not expired.
func (m *MemoryReplayChecker) CheckAndRecord(_ context.Context, jti string) error {
if jti == "" {
return errors.New("empty jti")
}
m.mu.Lock()
defer m.mu.Unlock()
nowFn := m.nowFunc
if nowFn == nil {
nowFn = time.Now
}
now := nowFn()
// Periodic purge of expired entries
if len(m.entries) > 500 {
for id, exp := range m.entries {
if now.After(exp) {
delete(m.entries, id)
}
}
}
if exp, exists := m.entries[jti]; exists && now.Before(exp) {
return fmt.Errorf("%w: %s", ErrDuplicateToken, jti)
}
m.entries[jti] = now.Add(m.ttl)
return nil
}
type HandlerOptions struct {
MaxBodySize int64 // Maximum allowed request body size (default: 32MB)
Logger *slog.Logger // Custom logger (default: slog.Default())
ReturnErrorDetails bool // Return JSON error details in response body (default: false)
ReplayChecker ReplayChecker // Optional replay attack protection
ExpectedIssuer string // Optional expected issuer claim (iss)
ExpectedAudience string // Recommended expected audience claim (aud) per Draft-03 Section 11/12
ClockSkew time.Duration // Clock skew tolerance for time-based claims validation (default: 1 minute per Draft-03)
KeyProvider func(token *jwt.Token) (any, error) // Dynamic key provider for key rotation and JWKS (overrides secret)
NowFunc func() time.Time // Optional clock override for deterministic verification (defaults to time.Now)
}
// NewHandlerFunc Creates a new http.HandlerFunc which will process an incoming
// webhook request and pass the token, if valid, to the given handleFn.
// Returns an error if handleFn is nil.
func NewHandlerFunc(secret []byte, handleFn func(token *SecureWebhookToken, data []byte) error, opts *HandlerOptions) (http.HandlerFunc, error) {
if handleFn == nil {
return nil, ErrInvalidTokenHandler
}
if opts == nil {
opts = &HandlerOptions{
MaxBodySize: defaultMaxBodySize,
}
}
if len(secret) == 0 && opts.KeyProvider == nil {
return nil, ErrMissingSecret
}
logger := opts.Logger
if logger == nil {
logger = slog.Default()
}
logger = logger.With("package", "github.com/SecureWebhookToken/swt")
// Helper for sending error responses
sendError := func(w http.ResponseWriter, status int, message string) {
if opts.ReturnErrorDetails {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]string{"error": message})
return
}
w.WriteHeader(status)
}
return func(w http.ResponseWriter, r *http.Request) {
token, body, ok := validateWebhookRequest(w, r, secret, opts, logger, sendError)
if !ok {
return
}
// Pass the valid token to the handler function
if err := handleFn(token, body); err != nil {
logger.Error("handleFn error!", "error", err, "jti", token.ID())
sendError(w, http.StatusBadRequest, err.Error())
return
}
w.WriteHeader(http.StatusNoContent)
}, nil
}
// validateWebhookRequest performs common HTTP request validation, JWT token extraction,
// signature verification, claim checks, and streaming body hash verification.
func validateWebhookRequest(
w http.ResponseWriter,
r *http.Request,
secret []byte,
opts *HandlerOptions,
logger *slog.Logger,
sendError func(http.ResponseWriter, int, string),
) (*SecureWebhookToken, []byte, bool) {
if r.Method != http.MethodPost {
logger.Warn("method not allowed", "method", r.Method, "path", r.URL.Path)
w.WriteHeader(http.StatusMethodNotAllowed)
return nil, nil, false
}
authHeader := r.Header.Get("Authorization")
if !strings.HasPrefix(authHeader, "Bearer ") {
logger.Warn("invalid authorization header scheme", "path", r.URL.Path)
sendError(w, http.StatusBadRequest, "invalid authorization header")
return nil, nil, false
}
tokenStr := strings.TrimSpace(strings.TrimPrefix(authHeader, "Bearer "))
if tokenStr == "" {
logger.Warn("empty bearer token", "path", r.URL.Path)
sendError(w, http.StatusBadRequest, "invalid authorization header")
return nil, nil, false
}
var key any = secret
if opts.KeyProvider != nil {
key = jwt.Keyfunc(opts.KeyProvider)
}
clockSkew := opts.ClockSkew
if clockSkew == 0 {
clockSkew = time.Minute
}
parseOpts := []ParseOption{WithLeeway(clockSkew)}
if opts.NowFunc != nil {
parseOpts = append(parseOpts, WithTimeFunc(opts.NowFunc))
}
token, err := Parse(tokenStr, key, parseOpts...)
if err != nil {
logger.Warn("parse token error", "error", err, "path", r.URL.Path)
sendError(w, http.StatusBadRequest, "invalid or expired token")
return nil, nil, false
}
// Check expected issuer if provided (Draft-03 Section 12)
if opts.ExpectedIssuer != "" && token.Issuer() != opts.ExpectedIssuer {
logger.Warn("issuer mismatch", "got", token.Issuer(), "expected", opts.ExpectedIssuer, "path", r.URL.Path)
sendError(w, http.StatusForbidden, "invalid issuer")
return nil, nil, false
}
// Check expected audience if provided (Draft-03 Section 11/12)
if opts.ExpectedAudience != "" {
auds := token.Audience()
matched := false
for _, aud := range auds {
if aud == opts.ExpectedAudience {
matched = true
break
}
}
if !matched {
logger.Warn("audience mismatch", "expected", opts.ExpectedAudience, "got", auds, "path", r.URL.Path)
sendError(w, http.StatusForbidden, "invalid audience")
return nil, nil, false
}
}
// Check for replay attacks if replay checker is provided
if opts.ReplayChecker != nil {
jti, _ := token.Claims().GetID()
if jti == "" {
logger.Warn("missing jti claim with replay protection enabled", "path", r.URL.Path)
sendError(w, http.StatusBadRequest, "missing jti claim")
return nil, nil, false
}
if err = opts.ReplayChecker.CheckAndRecord(r.Context(), jti); err != nil {
logger.Warn("replay attack detected", "jti", jti, "error", err)
sendError(w, http.StatusBadRequest, "duplicate token detected")
return nil, nil, false
}
}
if r.ContentLength == -1 {
logger.Error("unknown content length", "path", r.URL.Path)
sendError(w, http.StatusBadRequest, "unknown content length")
return nil, nil, false
}
maxBodySize := opts.MaxBodySize
if maxBodySize <= 0 {
maxBodySize = defaultMaxBodySize
}
if r.ContentLength > maxBodySize {
logger.Error("max request size reached", "content_length", r.ContentLength, "max_size", maxBodySize, "path", r.URL.Path)
sendError(w, http.StatusBadRequest, "max request size reached")
return nil, nil, false
}
wh, _ := token.Claims().GetWebhook()
// Stream body into hasher if hash claim is present for single-pass verification
var hasher hash.Hash
if wh.Hash != nil {
var errHash error
hasher, errHash = NewHasher(wh.Hash.Algorithm())
if errHash != nil {
logger.Error("unsupported hash algorithm in token", "error", errHash, "path", r.URL.Path)
sendError(w, http.StatusBadRequest, "unsupported hash algorithm")
return nil, nil, false
}
}
var reader io.Reader = http.MaxBytesReader(w, r.Body, maxBodySize)
if hasher != nil {
reader = io.TeeReader(reader, hasher)
}
body, err := io.ReadAll(reader)
var maxBytesError *http.MaxBytesError
if errors.As(err, &maxBytesError) {
logger.Error("max request size reached", "error", err)
sendError(w, http.StatusBadRequest, "max request size reached")
return nil, nil, false
}
if err != nil {
logger.Error("failed to read request body", "error", err)
sendError(w, http.StatusBadRequest, "failed to read request body")
return nil, nil, false
}
if len(body) > 0 {
if wh.Hash == nil {
logger.Error("webhook claim missing hash for non-empty body")
sendError(w, http.StatusBadRequest, "failed to validate request body")
return nil, nil, false
}
computedSum := fmt.Sprintf("%x", hasher.Sum(nil))
if subtle.ConstantTimeCompare([]byte(computedSum), []byte(wh.Hash.Sum())) != 1 {
logger.Error("failed to validate request body: hash mismatch")
sendError(w, http.StatusBadRequest, "failed to validate request body")
return nil, nil, false
}
} else if wh.Hash != nil {
// Draft-03 Section 11: If the request body is empty, the webhook claim MUST NOT contain a hash field.
logger.Error("webhook claim contains hash but request body is empty")
sendError(w, http.StatusBadRequest, "hash claim not allowed for empty body")
return nil, nil, false
}
return token, body, true
}
type parseConfig struct {
leeway time.Duration
timeFunc func() time.Time
}
// ParseOption configures token parsing behavior.
type ParseOption func(*parseConfig)
// WithLeeway sets the clock skew leeway tolerance for time-based claims (exp, nbf, iat).
// Draft-03 Section 11 recommends allowing a small clock skew (e.g. 60 seconds).
func WithLeeway(leeway time.Duration) ParseOption {
return func(c *parseConfig) {
c.leeway = leeway
}
}
// WithTimeFunc sets a custom clock function used during JWT time claim validation.
func WithTimeFunc(fn func() time.Time) ParseOption {
return func(c *parseConfig) {
c.timeFunc = fn
}
}
// Parse parses a given token string, verifies it and returns a SecureWebhookToken if successful.
func Parse(tokenStr string, key any, opts ...ParseOption) (*SecureWebhookToken, error) {
return ParseWithClaims(tokenStr, &WebhookClaims{}, key, opts...)
}
// ParseWithClaims parses a given token string and given claims, verifies it and returns a SecureWebhookToken if successful.
func ParseWithClaims(tokenStr string, claims Claims, key any, opts ...ParseOption) (*SecureWebhookToken, error) {
var (
swt = &SecureWebhookToken{}
err error
)
if claims == nil {
return nil, jwt.ErrTokenInvalidClaims
}
cfg := &parseConfig{}
for _, opt := range opts {
if opt != nil {
opt(cfg)
}
}
keyFunc := func(token *jwt.Token) (any, error) {
if kf, ok := key.(jwt.Keyfunc); ok {
return kf(token)
}
// Prevent algorithm confusion attacks: verify that token signing method matches key type.
switch k := key.(type) {
case []byte:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("%w: expected HMAC signing method for shared secret key, got %v", jwt.ErrTokenUnverifiable, token.Header["alg"])
}
return k, nil
case *rsa.PublicKey:
switch token.Method.(type) {
case *jwt.SigningMethodRSA, *jwt.SigningMethodRSAPSS:
return k, nil
default:
return nil, fmt.Errorf("%w: expected RSA signing method for RSA public key, got %v", jwt.ErrTokenUnverifiable, token.Header["alg"])
}
case *ecdsa.PublicKey:
if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok {
return nil, fmt.Errorf("%w: expected ECDSA signing method for ECDSA public key, got %v", jwt.ErrTokenUnverifiable, token.Header["alg"])
}
return k, nil
case ed25519.PublicKey:
if _, ok := token.Method.(*jwt.SigningMethodEd25519); !ok {
return nil, fmt.Errorf("%w: expected EdDSA signing method for Ed25519 public key, got %v", jwt.ErrTokenUnverifiable, token.Header["alg"])
}
return k, nil
default:
return key, nil
}
}
jwtParserOpts := []jwt.ParserOption{
jwt.WithValidMethods(validSigningMethods),
jwt.WithExpirationRequired(),
jwt.WithIssuedAt(),
}
if cfg.leeway > 0 {
jwtParserOpts = append(jwtParserOpts, jwt.WithLeeway(cfg.leeway))
}
if cfg.timeFunc != nil {
jwtParserOpts = append(jwtParserOpts, jwt.WithTimeFunc(cfg.timeFunc))
}
if swt.token, err = jwt.ParseWithClaims(
tokenStr,
claims,
keyFunc,
jwtParserOpts...,
); err != nil {
return nil, err
}
if typ, ok := swt.token.Header["typ"]; !ok || typ != jwtHeaderTyp {
return nil, fmt.Errorf("%w: header claim typ=SWT expected", ErrInvalidHeaderClaim)
}
return swt, nil
}
// ParseWithContext parses a given token string with context support, verifies it and returns a SecureWebhookToken if successful.
// The context can be used for cancellation and timeout control.
func ParseWithContext(ctx context.Context, tokenStr string, key any, opts ...ParseOption) (*SecureWebhookToken, error) {
return ParseWithClaimsContext(ctx, tokenStr, &WebhookClaims{}, key, opts...)
}
// ParseWithClaimsContext parses a given token string and given claims with context support, verifies it and returns a SecureWebhookToken if successful.
// The context can be used for cancellation and timeout control.
func ParseWithClaimsContext(ctx context.Context, tokenStr string, claims Claims, key any, opts ...ParseOption) (*SecureWebhookToken, error) {
// Check context before doing any work
if err := ctx.Err(); err != nil {
return nil, err
}
return ParseWithClaims(tokenStr, claims, key, opts...)
}
// SecureWebhookToken is a structure for secure webhook tokens.
type SecureWebhookToken struct {
token *jwt.Token
}
// Algorithm returns the used SigningMethod algorithm.
func (swt *SecureWebhookToken) Algorithm() string {
if swt == nil || swt.token == nil || swt.token.Method == nil {
panic(ErrInvalidToken)
}
return swt.token.Method.Alg()
}
// Claims return all token Claims.
// If no custom WebhookClaims have been set with NewWithClaims(), then the underlying type will be *WebhookClaims.
func (swt *SecureWebhookToken) Claims() Claims {
if swt == nil || swt.token == nil {
panic(ErrInvalidToken)
}
c, _ := swt.token.Claims.(Claims)
return c
}
// ID convenient method for accessing the ID of the SecureWebhookToken.
func (swt *SecureWebhookToken) ID() string {
if swt == nil || swt.token == nil {
return ""
}
c := swt.Claims()
if c == nil {
return ""
}
if id, err := c.GetID(); err == nil && id != "" {
return id
}
if wc := c.wc(); wc != nil {
return wc.ID
}
return ""
}
// Issuer convenient method for accessing the Issuer claim of the SecureWebhookToken.
func (swt *SecureWebhookToken) Issuer() string {
if swt == nil || swt.token == nil {
return ""
}
c := swt.Claims()
if c == nil {
return ""
}
if wc := c.wc(); wc != nil {
return wc.Issuer
}
return ""
}
// Audience convenient method for accessing the Audience claim of the SecureWebhookToken.
func (swt *SecureWebhookToken) Audience() []string {
if swt == nil || swt.token == nil {
return nil
}
c := swt.Claims()
if c == nil || c.wc() == nil {
return nil
}
return c.wc().Audience
}
// Webhook convenient method for accessing the Webhook claim of the SecureWebhookToken.
func (swt *SecureWebhookToken) Webhook() Webhook {
if swt == nil || swt.token == nil {
return Webhook{}
}
c := swt.Claims()
if c == nil {
return Webhook{}
}
if wh, err := c.GetWebhook(); err == nil {
return wh
}
if wc := c.wc(); wc != nil {
return wc.Webhook
}
return Webhook{}
}
// SignedString returns the encoded and signed SecureWebhookToken as a JWT string.
func (swt *SecureWebhookToken) SignedString(key any) (string, error) {
if swt.token == nil {
return "", ErrInvalidToken
}
// Validate claims before signing
if err := swt.Validate(); err != nil {
return "", err
}
return swt.token.SignedString(key)
}
// Valid returns true only if the SecureWebhookToken has been created
// via Parse method and successfully been validated.
func (swt *SecureWebhookToken) Valid() bool {
if swt.token == nil {
return false
}
return swt.token.Valid
}
// Validate validates the Claims of the SecureWebhookToken.
func (swt *SecureWebhookToken) Validate() error {
v := jwt.NewValidator(
jwt.WithValidMethods(validSigningMethods),
jwt.WithExpirationRequired(),
jwt.WithIssuedAt(),
)
return v.Validate(swt.Claims())
}
// String implements the Stringer interface for returning the SecureWebhookToken as a JSON string.
func (swt *SecureWebhookToken) String() string {
if swt == nil || swt.token == nil {
return ""
}
tokenData := struct {
Header map[string]any `json:"header"`
Payload jwt.Claims `json:"payload"`
Signature string `json:"signature"`
Validated bool `json:"validated"`
}{
Header: swt.token.Header,
Payload: swt.token.Claims,
Signature: swt.token.EncodeSegment(swt.token.Signature),
Validated: swt.token.Valid,
}
out, _ := json.Marshal(tokenData)
return string(out)
}
type Webhook struct {
Event string `json:"event"` // Event name. Should have the form EVENT_NAME.ACTIVITY (e.g., user.created or pull_request.merged)
Hash *Hash `json:"hash,omitempty"`
RetryCount uint `json:"retry_count,omitempty"`
}
type Hash string
func NewHash(alg string, data []byte) (*Hash, error) {
if alg == "" {
alg = defaultHashAlgorithm
}
if data != nil {
hSum, err := HashSum(alg, data)
if err != nil {
return nil, err
}
h := Hash(strings.ToLower(alg) + ":" + hSum)
return &h, nil
}
return nil, nil
}
func NewHashFromString(input string) *Hash {
h := Hash(strings.ToLower(input))
return &h
}
func (h *Hash) parts() (algo, sum string) {
res := strings.Split(string(*h), ":")
if len(res) != 2 {
return "", ""
}
return res[0], res[1]
}
func (h *Hash) Algorithm() string {
alg, _ := h.parts()
return alg
}
func (h *Hash) Sum() string {
_, sum := h.parts()
return sum
}
func (h *Hash) String() string {
alg, sum := h.parts()
if alg == "" && sum == "" {
return ""
}
return alg + ":" + sum
}
type Claims interface {
GetID() (string, error)
GetWebhook() (Webhook, error)
wc() *WebhookClaims
jwt.Claims
}
type WebhookClaims struct {
Webhook Webhook `json:"webhook"`
jwt.RegisteredClaims
}
// the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7
func (wc *WebhookClaims) GetID() (string, error) {
return wc.ID, nil
}
// the `webhook` (SWT) claim. See https://www.ietf.org/archive/id/draft-knauer-secure-webhook-token-03.html#name-json-web-token-claims-regis
func (wc *WebhookClaims) GetWebhook() (Webhook, error) {
return wc.Webhook, nil
}
// MapClaims will convert a WebhookClaims object into jwt.MapClaims
// Can easily be used with the golang-jwt package for creating JWTs directly if desired.
func (wc *WebhookClaims) MapClaims() jwt.MapClaims {
mc := map[string]any{
"aud": wc.Audience,
"sub": wc.Subject,
"jti": wc.ID,
"iss": wc.Issuer,
"webhook": wc.Webhook,
}
if wc.ExpiresAt != nil {
mc["exp"] = float64(wc.ExpiresAt.Unix())
}
if wc.IssuedAt != nil {
mc["iat"] = float64(wc.IssuedAt.Unix())
}
if wc.NotBefore != nil {
mc["nbf"] = float64(wc.NotBefore.Unix())
}
return mc
}
// Validate implements the jwt.ClaimsValidator interface to perform further required validation on specific claims.
func (wc *WebhookClaims) Validate() error {
if wc.Issuer == "" {
return fmt.Errorf("%w: iss must not be empty", jwt.ErrTokenInvalidIssuer)
}
if wc.IssuedAt == nil {
return fmt.Errorf("%w: iat", jwt.ErrTokenRequiredClaimMissing)
}
if wc.ExpiresAt == nil {
return fmt.Errorf("%w: exp", jwt.ErrTokenRequiredClaimMissing)
}
if wc.NotBefore == nil {
return fmt.Errorf("%w: nbf", jwt.ErrTokenRequiredClaimMissing)
}
if wc.Webhook.Event == "" {
return fmt.Errorf("%w: %s must contain an event", jwt.ErrTokenInvalidClaims, webhookClaim)
}
if wc.ID == "" {
return fmt.Errorf("%w: jti must not be empty! a uuid or similar is recommended", jwt.ErrTokenInvalidId)
}
return nil
}
// wc is a helper method for overriding the default claims with functional options.
func (wc *WebhookClaims) wc() *WebhookClaims {
return wc
}
// NewHasher returns a new hash.Hash instance for the supported hash algorithm name.
func NewHasher(hashAlg string) (hash.Hash, error) {
if hashAlg == "" {
hashAlg = defaultHashAlgorithm
}
switch strings.ToLower(hashAlg) {
case SHA256:
return sha256.New(), nil
case SHA384:
return sha512.New384(), nil
case SHA512:
return sha512.New(), nil
case SHA3_256:
return sha3.New256(), nil
case SHA3_384:
return sha3.New384(), nil
case SHA3_512:
return sha3.New512(), nil
default:
return nil, fmt.Errorf("%w: %s", ErrUnsupportedHashAlgorithm, hashAlg)
}
}
// HashSum computes the hash sum for a given hashAlg and the body to be sent via http.MethodPost request.
func HashSum(hashAlg string, body []byte) (string, error) {
h, err := NewHasher(hashAlg)
if err != nil {
return "", err
}
_, _ = h.Write(body)
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
// newRegClaims creates jwt.RegisteredClaims with sensible defaults and the required issuer (iss) claim.
func newRegClaims(issuer string) jwt.RegisteredClaims {
now := time.Now()
return jwt.RegisteredClaims{
ID: uuid.NewString(),
Issuer: issuer,
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(defaultExpiration)),
NotBefore: jwt.NewNumericDate(now),
}
}