-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathresponse_test.go
84 lines (68 loc) · 2.22 KB
/
response_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
package caddywaf
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"go.uber.org/zap/zaptest"
)
type contextKey string
type CustomResponse struct {
StatusCode int
Body string
Headers map[string]string
}
func TestBlockRequest(t *testing.T) {
logger := zaptest.NewLogger(t)
t.Run("handles custom response", func(t *testing.T) {
m := &Middleware{
logger: logger,
CustomResponses: map[int]CustomBlockResponse{
http.StatusForbidden: {
StatusCode: http.StatusForbidden,
Body: "Blocked",
Headers: map[string]string{"X-Test": "true"},
},
},
}
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/test", nil)
state := &WAFState{}
m.blockRequest(w, r, state, http.StatusForbidden, "test reason", "rule1", "match1")
assert.Equal(t, http.StatusForbidden, w.Code)
assert.Equal(t, "Blocked", w.Body.String())
assert.Equal(t, "true", w.Header().Get("X-Test"))
assert.True(t, state.Blocked)
})
t.Run("handles default blocking", func(t *testing.T) {
m := &Middleware{
logger: logger,
}
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/test", nil)
const logIDKey contextKey = "logID"
ctx := context.WithValue(r.Context(), logIDKey, "test-id")
r = r.WithContext(ctx)
state := &WAFState{}
m.blockRequest(w, r, state, http.StatusForbidden, "test reason", "rule1", "match1")
assert.Equal(t, http.StatusForbidden, w.Code)
assert.True(t, state.Blocked)
})
t.Run("skips if response already written", func(t *testing.T) {
m := &Middleware{
logger: logger,
}
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/test", nil)
state := &WAFState{
ResponseWritten: true,
StatusCode: http.StatusOK,
}
recorder := NewResponseRecorder(w)
m.blockRequest(recorder, r, state, http.StatusForbidden, "test reason", "rule1", "match1")
assert.Equal(t, http.StatusForbidden, recorder.StatusCode()) // Check the Recorder status code instead
assert.True(t, state.ResponseWritten) // Check that the ResponseWritten flag is set
assert.True(t, state.Blocked) // Verify block is set to true
})
}