-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin_test.go
375 lines (300 loc) · 12.5 KB
/
plugin_test.go
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
package traefiklogger_test
import (
"context"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
"github.com/fzoli/traefiklogger"
)
type TestLoggerClock struct{}
func (c *TestLoggerClock) Now() time.Time {
return time.Date(2020, time.December, 15, 13, 30, 40, 999999999, time.UTC)
}
type TestUUIDGenerator struct{}
func (g *TestUUIDGenerator) Generate() string {
return "test-id"
}
type TestLogWriter struct {
t *testing.T
expected string
}
func (w *TestLogWriter) Write(log string) error {
w.t.Helper()
if log != w.expected {
w.t.Errorf("Expected: '%s', got: '%s'", w.expected, log)
}
return nil
}
// createContext creates text context with fake time and test log writer that assert the expected log.
func createContext(t *testing.T, expectedLog string) context.Context {
t.Helper()
clock := &TestLoggerClock{}
uuidGenerator := &TestUUIDGenerator{}
logWriter := &TestLogWriter{t: t, expected: expectedLog}
return context.WithValue(context.WithValue(context.WithValue(context.Background(), traefiklogger.LogWriterContextKey, logWriter), traefiklogger.ClockContextKey, clock), traefiklogger.UUIDGeneratorContextKey, uuidGenerator)
}
// doubleTheNumber reads the request, parses it as integer then returns its double.
// So the request and the response are not the same.
func doubleTheNumber(rw http.ResponseWriter, req *http.Request) {
// Read the request body
body, err := io.ReadAll(req.Body)
if err != nil {
http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
return
}
defer func(Body io.ReadCloser) {
cerr := Body.Close()
if cerr != nil {
log.Printf("Failed to close reader: %v", cerr)
}
}(req.Body)
// Parse the request body as an integer
num, err := strconv.Atoi(string(body))
if err != nil {
http.Error(rw, "Bad Request: Request body must be an integer", http.StatusBadRequest)
return
}
// Double the number
result := num * 2
// Write the result
rw.WriteHeader(http.StatusOK)
rw.Header().Set("Content-Type", "text/plain")
fmt.Fprintf(rw, "%d", result)
}
// blackHole reads the request then it just returns HTTP OK without response body.
func blackHole(rw http.ResponseWriter, req *http.Request) {
// Read the request body (to appear in logs)
_, err := io.ReadAll(req.Body)
if err != nil {
http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
return
}
defer func(Body io.ReadCloser) {
cerr := Body.Close()
if cerr != nil {
log.Printf("Failed to close reader: %v", cerr)
}
}(req.Body)
rw.WriteHeader(http.StatusOK)
}
// alwaysError just returns HTTP 500
func alwaysError(rw http.ResponseWriter, req *http.Request) {
http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
}
// alwaysFive does not read the request, just returns HTTP OK with response body 5.
func alwaysFive(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusOK)
fmt.Fprintf(rw, "%d", 5)
}
func TestPost(t *testing.T) {
expectedLogs := map[traefiklogger.LogFormat]string{
traefiklogger.TextFormat: "127.0.0.1 POST /post: 200 OK HTTP/1.1\n\nRequest Headers:\nAccept: text/plain\nAuthorization: Bearer {\"alg\":\"HS256\",\"typ\":\"JWT\"}.{\"sub\":\"1234567890\",\"name\":\"John Doe\",\"iat\":1516239022}\n\nRequest Body:\n5\n\nResponse Headers:\nContent-Type: text/plain\n\nResponse Content Length: 2\n\nDuration: 0.000 ms\n\nResponse Body:\n10\n\n",
traefiklogger.JSONFormat: "{\"log.level\":\"info\",\"@timestamp\":\"2020-12-15T13:30:40.999Z\",\"message\":\"POST /post HTTP/1.1 200\",\"systemName\":\"HTTP\",\"remoteAddress\":\"127.0.0.1\",\"method\":\"POST\",\"path\":\"/post\",\"status\":200,\"statusText\":\"OK\",\"proto\":\"HTTP/1.1\",\"durationMs\":0,\"requestHeaders\":{\"Accept\":[\"text/plain\"],\"Authorization\":[\"Bearer {\\\"alg\\\":\\\"HS256\\\",\\\"typ\\\":\\\"JWT\\\"}.{\\\"sub\\\":\\\"1234567890\\\",\\\"name\\\":\\\"John Doe\\\",\\\"iat\\\":1516239022}\"]},\"requestBody\":\"5\",\"responseHeaders\":{\"Content-Type\":[\"text/plain\"]},\"responseContentLength\":2,\"responseBody\":\"10\",\"ecs.version\":\"1.6.0\",\"logId\":\"test-id\"}\n",
}
for logFormat, expectedLog := range expectedLogs {
cfg := traefiklogger.CreateConfig()
cfg.LogFormat = logFormat
cfg.JWTHeaders = []string{"Authorization"}
ctx := createContext(t, expectedLog)
handler, err := traefiklogger.New(ctx, http.HandlerFunc(doubleTheNumber), cfg, "logger-plugin")
if err != nil {
t.Fatal(err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "/post", strings.NewReader("5"))
if err != nil {
t.Fatal(err)
}
req.RemoteAddr = "127.0.0.1"
req.Header.Set("Accept", "text/plain")
req.Header.Set("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c")
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
// Check the response body
if recorder.Body.String() != "10" {
t.Errorf("Expected response body: '10', got: '%s'", recorder.Body.String())
}
}
}
func TestShortPost(t *testing.T) {
expectedLogs := map[traefiklogger.LogFormat]string{
traefiklogger.TextFormat: "127.0.0.1 POST /short-post: 200 OK HTTP/1.1\n\nRequest Headers:\nAccept: text/plain\nAuthorization: ██\n\nResponse Headers:\nContent-Type: text/plain\n\nResponse Content Length: 2\n\nDuration: 0.000 ms\n\n",
traefiklogger.JSONFormat: "{\"log.level\":\"info\",\"@timestamp\":\"2020-12-15T13:30:40.999Z\",\"message\":\"POST /short-post HTTP/1.1 200\",\"systemName\":\"HTTP\",\"remoteAddress\":\"127.0.0.1\",\"method\":\"POST\",\"path\":\"/short-post\",\"status\":200,\"statusText\":\"OK\",\"proto\":\"HTTP/1.1\",\"durationMs\":0,\"requestHeaders\":{\"Accept\":[\"text/plain\"],\"Authorization\":[\"██\"]},\"responseHeaders\":{\"Content-Type\":[\"text/plain\"]},\"responseContentLength\":2,\"ecs.version\":\"1.6.0\",\"logId\":\"test-id\"}\n",
}
cfgWithInterestedContentTypes := traefiklogger.CreateConfig()
cfgWithInterestedContentTypes.HeaderRedacts = []string{"Authorization"}
cfgWithInterestedContentTypes.BodyContentTypes = []string{"text/html"}
cfgWithBodyRedact := traefiklogger.CreateConfig()
cfgWithBodyRedact.HeaderRedacts = []string{"Authorization"}
cfgWithBodyRedact.RequestBodyRedact = "POST /short-post"
cfgWithBodyRedact.ResponseBodyRedact = "POST /short-post"
configs := []*traefiklogger.Config{cfgWithInterestedContentTypes, cfgWithBodyRedact}
for _, cfg := range configs {
for logFormat, expectedLog := range expectedLogs {
cfg.LogFormat = logFormat
ctx := createContext(t, expectedLog)
handler, err := traefiklogger.New(ctx, http.HandlerFunc(doubleTheNumber), cfg, "logger-plugin")
if err != nil {
t.Fatal(err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "/short-post", strings.NewReader("5"))
if err != nil {
t.Fatal(err)
}
req.RemoteAddr = "127.0.0.1"
req.Header.Set("Accept", "text/plain")
req.Header.Set("Authorization", "secret")
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
// Check the response body
if recorder.Body.String() != "10" {
t.Errorf("Expected response body: '10', got: '%s'", recorder.Body.String())
}
}
}
}
func TestEmptyPost(t *testing.T) {
cfg := traefiklogger.CreateConfig()
ctx := createContext(t, "127.0.0.1 POST /empty-post: 200 OK HTTP/1.1\n\nRequest Body:\n5\n\nResponse Content Length: 0\n\nDuration: 0.000 ms\n\n")
handler, err := traefiklogger.New(ctx, http.HandlerFunc(blackHole), cfg, "logger-plugin")
if err != nil {
t.Fatal(err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "/empty-post", strings.NewReader("5"))
if err != nil {
t.Fatal(err)
}
req.RemoteAddr = "127.0.0.1"
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
// Check the response body
if recorder.Body.String() != "" {
t.Errorf("Expected response body: '', got: '%s'", recorder.Body.String())
}
}
func TestGet(t *testing.T) {
cfg := traefiklogger.CreateConfig()
ctx := createContext(t, "127.0.0.1 GET /get: 200 OK HTTP/1.1\n\nResponse Content Length: 1\n\nDuration: 0.000 ms\n\nResponse Body:\n5\n\n")
handler, err := traefiklogger.New(ctx, http.HandlerFunc(alwaysFive), cfg, "logger-plugin")
if err != nil {
t.Fatal(err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "/get", nil)
if err != nil {
t.Fatal(err)
}
req.RemoteAddr = "127.0.0.1"
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
// Check the response body
if recorder.Body.String() != "5" {
t.Errorf("Expected response body: '5', got: '%s'", recorder.Body.String())
}
}
func TestGetWithoutLogID(t *testing.T) {
ctx := createContext(t, "{\"log.level\":\"info\",\"@timestamp\":\"2020-12-15T13:30:40.999Z\",\"message\":\"GET /get-without-log-id HTTP/1.1 200\",\"systemName\":\"HTTP\",\"remoteAddress\":\"127.0.0.1\",\"method\":\"GET\",\"path\":\"/get-without-log-id\",\"status\":200,\"statusText\":\"OK\",\"proto\":\"HTTP/1.1\",\"durationMs\":0,\"responseContentLength\":1,\"responseBody\":\"5\",\"ecs.version\":\"1.6.0\"}\n")
cfg := traefiklogger.CreateConfig()
cfg.LogFormat = traefiklogger.JSONFormat
cfg.GenerateLogID = false
handler, err := traefiklogger.New(ctx, http.HandlerFunc(alwaysFive), cfg, "logger-plugin")
if err != nil {
t.Fatal(err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "/get-without-log-id", nil)
if err != nil {
t.Fatal(err)
}
req.RemoteAddr = "127.0.0.1"
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
// Check the response body
if recorder.Body.String() != "5" {
t.Errorf("Expected response body: '5', got: '%s'", recorder.Body.String())
}
}
func TestGetError(t *testing.T) {
cfg := traefiklogger.CreateConfig()
ctx := createContext(t, "127.0.0.1 GET /get-error: 500 Internal Server Error HTTP/1.1\n\nResponse Headers:\nContent-Type: text/plain; charset=utf-8\nX-Content-Type-Options: nosniff\n\nResponse Content Length: 22\n\nDuration: 0.000 ms\n\nResponse Body:\nInternal Server Error\n\n\n")
handler, err := traefiklogger.New(ctx, http.HandlerFunc(alwaysError), cfg, "logger-plugin")
if err != nil {
t.Fatal(err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "/get-error", nil)
if err != nil {
t.Fatal(err)
}
req.RemoteAddr = "127.0.0.1"
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
// Check the response body
if recorder.Body.String() != "Internal Server Error\n" {
t.Errorf("Expected response body: 'Internal Server Error\n', got: '%s'", recorder.Body.String())
}
}
func TestGetWebsocket(t *testing.T) {
cfg := traefiklogger.CreateConfig()
ctx := createContext(t, "LogWriter should not have been called")
handler, err := traefiklogger.New(ctx, http.HandlerFunc(alwaysFive), cfg, "logger-plugin")
if err != nil {
t.Fatal(err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "/get-websocket", nil)
if err != nil {
t.Fatal(err)
}
req.RemoteAddr = "127.0.0.1"
req.Header.Set("Upgrade", "websocket")
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
// Check the response body
if recorder.Body.String() != "5" {
t.Errorf("Expected response body: '5', got: '%s'", recorder.Body.String())
}
}
func TestEmptyGet(t *testing.T) {
cfg := traefiklogger.CreateConfig()
ctx := createContext(t, "127.0.0.1 GET /empty-get: 200 OK HTTP/1.1\n\nResponse Content Length: 0\n\nDuration: 0.000 ms\n\n")
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusOK)
})
handler, err := traefiklogger.New(ctx, next, cfg, "logger-plugin")
if err != nil {
t.Fatal(err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "/empty-get", nil)
if err != nil {
t.Fatal(err)
}
req.RemoteAddr = "127.0.0.1"
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
// Check the response body
if recorder.Body.String() != "" {
t.Errorf("Expected response body: '', got: '%s'", recorder.Body.String())
}
}
func TestDisabled(t *testing.T) {
cfg := traefiklogger.CreateConfig()
cfg.Enabled = false
ctx := createContext(t, "LogWriter should not have been called")
handler, err := traefiklogger.New(ctx, http.HandlerFunc(alwaysFive), cfg, "logger-plugin")
if err != nil {
t.Fatal(err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "/disabled", nil)
if err != nil {
t.Fatal(err)
}
req.RemoteAddr = "127.0.0.1"
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
// Check the response body
if recorder.Body.String() != "5" {
t.Errorf("Expected response body: '5', got: '%s'", recorder.Body.String())
}
}