Repository navigation
Expand file tree
/
Copy pathmiddleware_test.go
More file actions
153 lines (124 loc) · 4.26 KB
/
Copy pathmiddleware_test.go
File metadata and controls
153 lines (124 loc) · 4.26 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
package swt_test
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/SecureWebhookToken/swt"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestContextWithTokenAndFromContext(t *testing.T) {
t.Run("nil context returns false", func(t *testing.T) {
//nolint:staticcheck // intentional test for nil context defense
tok, ok := swt.FromContext(nil)
assert.False(t, ok)
assert.Nil(t, tok)
})
t.Run("empty context returns false", func(t *testing.T) {
tok, ok := swt.FromContext(context.Background())
assert.False(t, ok)
assert.Nil(t, tok)
})
t.Run("token found in context", func(t *testing.T) {
token, err := swt.New("test-issuer", "test.event", nil)
require.NoError(t, err)
ctx := swt.ContextWithToken(context.Background(), token)
extracted, ok := swt.FromContext(ctx)
assert.True(t, ok)
assert.Equal(t, token, extracted)
})
}
func TestMiddlewareCreation(t *testing.T) {
t.Run("missing secret and key provider fails", func(t *testing.T) {
mw, err := swt.Middleware(nil, nil)
assert.ErrorIs(t, err, swt.ErrMissingSecret)
assert.Nil(t, mw)
})
t.Run("valid secret succeeds", func(t *testing.T) {
mw, err := swt.Middleware([]byte("my-secret-key"), nil)
assert.NoError(t, err)
assert.NotNil(t, mw)
})
}
func TestMiddlewareLifecycle(t *testing.T) {
secret := []byte("very-secure-secret-key-32-bytes!!")
payload := []byte(`{"event":"order.completed","amount":99.95}`)
h, err := swt.NewHash(swt.SHA256, payload)
require.NoError(t, err)
token, err := swt.New("payment-gateway", "order.completed", h,
swt.WithAudience("https://api.example.com/webhooks"),
swt.WithExpiresAt(time.Now().Add(5*time.Minute)),
)
require.NoError(t, err)
signedToken, err := token.SignedString(secret)
require.NoError(t, err)
mw, err := swt.Middleware(secret, &swt.HandlerOptions{
ExpectedIssuer: "payment-gateway",
ExpectedAudience: "https://api.example.com/webhooks",
})
require.NoError(t, err)
var downstreamCalled bool
var downstreamBody []byte
var downstreamToken *swt.SecureWebhookToken
handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
downstreamCalled = true
var ok bool
downstreamToken, ok = swt.FromContext(r.Context())
if !ok {
http.Error(w, "token not in context", http.StatusInternalServerError)
return
}
var readErr error
downstreamBody, readErr = io.ReadAll(r.Body)
if readErr != nil {
http.Error(w, "cannot read body", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("processed"))
}))
t.Run("valid request passes through, preserves body and token", func(t *testing.T) {
downstreamCalled = false
downstreamBody = nil
downstreamToken = nil
req := httptest.NewRequest(http.MethodPost, "/webhooks", bytes.NewReader(payload))
req.Header.Set("Authorization", "Bearer "+signedToken)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
assert.Equal(t, http.StatusOK, rec.Code)
assert.True(t, downstreamCalled)
assert.Equal(t, payload, downstreamBody)
assert.NotNil(t, downstreamToken)
assert.Equal(t, "payment-gateway", downstreamToken.Issuer())
})
t.Run("invalid method rejected and downstream not called", func(t *testing.T) {
downstreamCalled = false
req := httptest.NewRequest(http.MethodGet, "/webhooks", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
assert.Equal(t, http.StatusMethodNotAllowed, rec.Code)
assert.False(t, downstreamCalled)
})
t.Run("missing authorization rejected", func(t *testing.T) {
downstreamCalled = false
req := httptest.NewRequest(http.MethodPost, "/webhooks", bytes.NewReader(payload))
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
assert.Equal(t, http.StatusBadRequest, rec.Code)
assert.False(t, downstreamCalled)
})
t.Run("corrupted body rejected", func(t *testing.T) {
downstreamCalled = false
tamperedPayload := []byte(`{"event":"order.completed","amount":0.01}`)
req := httptest.NewRequest(http.MethodPost, "/webhooks", bytes.NewReader(tamperedPayload))
req.Header.Set("Authorization", "Bearer "+signedToken)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
assert.Equal(t, http.StatusBadRequest, rec.Code)
assert.False(t, downstreamCalled)
})
}