-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmiddleware_test.go
More file actions
312 lines (264 loc) · 8.34 KB
/
middleware_test.go
File metadata and controls
312 lines (264 loc) · 8.34 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
package treblle
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/go-chi/chi"
"github.com/stretchr/testify/suite"
)
type TestSuite struct {
suite.Suite
testServer *httptest.Server
router *chi.Mux
treblleMockMux *http.ServeMux
treblleMockServer *httptest.Server
}
func TestTreblleTestSuite(t *testing.T) {
suite.Run(t, new(TestSuite))
}
func (s *TestSuite) SetupTest() {
s.router = chi.NewRouter()
s.router.Use(Middleware)
s.testServer = httptest.NewServer(s.router)
s.treblleMockMux = http.NewServeMux()
s.treblleMockServer = httptest.NewServer(s.treblleMockMux)
Configure(Configuration{
SDK_TOKEN: "test-sdk-token",
API_KEY: "test-api-key",
DefaultFieldsToMask: []string{
"password",
"api_key",
"credit_card",
"authorization",
},
})
}
func (s *TestSuite) TearDownTest() {
if s.testServer != nil {
s.testServer.Close()
}
if s.treblleMockServer != nil {
s.treblleMockServer.Close()
}
}
func (s *TestSuite) TestJsonFormat() {
sampleData := map[string]interface{}{
"api_key": "",
"project_id": "",
"version": 0.6,
"sdk": "laravel",
"data": map[string]interface{}{
"server": map[string]interface{}{
"ip": "18.194.223.176",
"timezone": "UTC",
"software": "Apache",
"signature": "Apache/2.4.2",
"protocol": "HTTP/1.1",
"os": map[string]interface{}{
"name": "Linux",
"release": "4.14.186-110.268.amzn1.x86_64",
"architecture": "x86_64",
},
},
},
}
content, err := json.Marshal(sampleData)
s.Require().NoError(err)
var treblleMetadata MetaData
err = json.Unmarshal(content, &treblleMetadata)
s.Require().NoError(err)
}
func (s *TestSuite) testRequest(method, path, body string, headers map[string]string) (*http.Response, string) {
var bodyReader *bytes.Reader
if body != "" {
bodyReader = bytes.NewReader([]byte(body))
}
req, err := http.NewRequest(method, s.testServer.URL+path, bodyReader)
s.Require().NoError(err)
for k, v := range headers {
req.Header.Add(k, v)
}
resp, err := http.DefaultClient.Do(req)
s.Require().NoError(err)
respBody, err := ioutil.ReadAll(resp.Body)
s.Require().NoError(err)
resp.Body.Close()
return resp, string(respBody)
}
func (s *TestSuite) TestCRUDMasking() {
s.router.Post("/users", func(w http.ResponseWriter, r *http.Request) {
var requestBody map[string]interface{}
err := json.NewDecoder(r.Body).Decode(&requestBody)
s.Require().NoError(err)
// Mask sensitive data in response
response := map[string]interface{}{
"id": 1,
"password": maskValue("should-be-masked", "password"),
"api_key": maskValue("should-be-masked", "api_key"),
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(response)
})
// Test POST request with sensitive data
resp, body := s.testRequest("POST", "/users", `{
"username": "test",
"password": "secret123",
"api_key": "key123"
}`, map[string]string{
"Content-Type": "application/json",
})
s.Require().Equal(http.StatusCreated, resp.StatusCode)
var responseBody map[string]interface{}
err := json.Unmarshal([]byte(body), &responseBody)
s.Require().NoError(err)
s.Require().Equal("*********", responseBody["password"])
s.Require().Equal("*********", responseBody["api_key"])
}
func (s *TestSuite) TestMiddleware() {
testCases := map[string]struct {
requestJson string
responseJson string
requestHeaderKey string
requestHeaderValue string
respHeaderKey string
respHeaderValue string
status int
treblleCalled bool
}{
"happy-path": {
requestJson: `{"id":1}`,
responseJson: `{"id":1}`,
status: http.StatusOK,
treblleCalled: true,
},
"invalid-request-json": {
requestJson: `{"id":`,
responseJson: `{"error":"bad request"}`,
status: http.StatusBadRequest,
treblleCalled: true,
},
"non-json-response": {
requestJson: `{"id":5}`,
responseJson: `Hello, World!`,
status: http.StatusOK,
treblleCalled: true,
},
}
for tn, tc := range testCases {
s.SetupTest()
treblleMuxCalled := false
mockURL := s.treblleMockServer.URL
log.Printf("Test case: %s, Mock URL: %s", tn, mockURL)
Configure(Configuration{
SDK_TOKEN: "test-sdk-token",
API_KEY: "test-api-key",
DefaultFieldsToMask: []string{"password"},
Endpoint: mockURL,
})
s.treblleMockMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Printf("Mock server received request to: %s", r.URL.String())
var treblleMetadata MetaData
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&treblleMetadata)
if err != nil {
log.Printf("Error decoding request body in mock server: %v", err)
return
}
log.Printf("Received metadata - SDK Token: %s, API Key: %s", treblleMetadata.ApiKey, treblleMetadata.ProjectID)
s.Require().Equal("test-sdk-token", treblleMetadata.ApiKey)
s.Require().Equal("test-api-key", treblleMetadata.ProjectID)
if tn == "non-json-response" {
// For non-JSON responses, the body should be a JSON string
expectedBody, _ := json.Marshal("Hello, World!")
s.Require().Equal(string(expectedBody), string(treblleMetadata.Data.Response.Body))
}
treblleMuxCalled = true
w.WriteHeader(http.StatusOK)
})
s.router.Use(Middleware)
s.router.Get("/test", func(w http.ResponseWriter, r *http.Request) {
log.Printf("Request headers: %+v", r.Header)
if tc.requestHeaderKey != "" {
s.Require().Equal(tc.requestHeaderValue, r.Header.Get(tc.requestHeaderKey))
}
if tc.respHeaderKey != "" {
w.Header().Set(tc.respHeaderKey, tc.respHeaderValue)
}
if tn == "non-json-response" {
w.Header().Set("Content-Type", "text/plain")
} else {
w.Header().Set("Content-Type", "application/json")
}
w.WriteHeader(tc.status)
w.Write([]byte(tc.responseJson))
})
requestHeaders := map[string]string{}
if tc.requestHeaderKey != "" {
requestHeaders[tc.requestHeaderKey] = tc.requestHeaderValue
}
requestHeaders["Content-Type"] = "application/json"
resp, body := s.testRequest(http.MethodGet, "/test", tc.requestJson, requestHeaders)
log.Printf("Response status: %d, body: %s", resp.StatusCode, body)
s.Require().Equal(tc.status, resp.StatusCode, tn)
s.Require().Equal(tc.responseJson, body, tn)
if tc.respHeaderKey != "" {
s.Require().Equal(tc.respHeaderValue, resp.Header.Get(tc.respHeaderKey), tn)
}
// Wait for the async Treblle call to finish
time.Sleep(1 * time.Second)
log.Printf("After sleep - treblleMuxCalled: %v, expected: %v", treblleMuxCalled, tc.treblleCalled)
s.Require().Equal(tc.treblleCalled, treblleMuxCalled, tn)
s.TearDownTest()
}
}
func (s *TestSuite) TestProtocolDetection() {
s.SetupTest()
// Create a channel to receive the detected protocol
protocolChan := make(chan string, 1)
// Setup the mock Treblle server to capture the protocol
mockURL := s.treblleMockServer.URL
Configure(Configuration{
SDK_TOKEN: "test-sdk-token",
API_KEY: "test-api-key",
DefaultFieldsToMask: []string{"password"},
Endpoint: mockURL,
})
s.treblleMockMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
var treblleMetadata MetaData
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&treblleMetadata)
if err != nil {
s.Fail("Failed to decode Treblle metadata", err)
return
}
// Send the detected protocol to the channel
protocolChan <- treblleMetadata.Data.Server.Protocol
w.WriteHeader(http.StatusOK)
})
s.router.Use(Middleware)
s.router.Get("/test-protocol", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status":"ok"}`))
})
// Make a request to the test server with a valid JSON body
resp, _ := s.testRequest(http.MethodGet, "/test-protocol", `{"test":"data"}`, map[string]string{
"Content-Type": "application/json",
})
s.Require().Equal(http.StatusOK, resp.StatusCode)
// Wait for the async Treblle call to finish and capture the protocol
select {
case protocol := <-protocolChan:
// HTTP/1.1 is expected in test environment
s.Require().Equal("HTTP/1.1", protocol, "Protocol detection failed")
case <-time.After(2 * time.Second):
s.Fail("Timeout waiting for Treblle metadata")
}
s.TearDownTest()
}