Repository navigation
Expand file tree
/
Copy pathmiddleware.go
More file actions
85 lines (73 loc) · 2.76 KB
/
Copy pathmiddleware.go
File metadata and controls
85 lines (73 loc) · 2.76 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
package swt
import (
"bytes"
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
)
type tokenContextKeyType struct{}
var tokenContextKey = tokenContextKeyType{}
// ContextWithToken returns a new context with the validated SecureWebhookToken attached.
func ContextWithToken(ctx context.Context, token *SecureWebhookToken) context.Context {
return context.WithValue(ctx, tokenContextKey, token)
}
// FromContext extracts a SecureWebhookToken from the context, if present.
// Returns the token and true if found, or nil and false otherwise.
func FromContext(ctx context.Context) (*SecureWebhookToken, bool) {
if ctx == nil {
return nil, false
}
tok, ok := ctx.Value(tokenContextKey).(*SecureWebhookToken)
return tok, ok && tok != nil
}
// Middleware returns an HTTP middleware function compatible with standard Go HTTP routers
// (e.g., standard library net/http, Chi, Gorilla, Echo, Gin wrappers).
//
// The middleware validates incoming POST requests according to SWT Draft-03 specifications:
// - Verifies the Authorization Bearer JWT token signature and expiration (with clock skew).
// - Validates required claims (iss, aud, jti, event).
// - Protects against replay attacks if opts.ReplayChecker is configured.
// - Validates the request body payload against the hash claim via streaming verification.
// - Restores r.Body so subsequent downstream handlers can read the request payload.
// - Injects the validated *SecureWebhookToken into r.Context() (accessible via FromContext).
//
// If validation fails, an HTTP error response is sent and downstream handlers are NOT called.
func Middleware(secret []byte, opts *HandlerOptions) (func(http.Handler) http.Handler, error) {
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")
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(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, body, ok := validateWebhookRequest(w, r, secret, opts, logger, sendError)
if !ok {
return
}
// Restore request body so downstream handlers can read it
r.Body = io.NopCloser(bytes.NewReader(body))
// Pass token to downstream handlers via request context
ctx := ContextWithToken(r.Context(), token)
next.ServeHTTP(w, r.WithContext(ctx))
})
}, nil
}