forked from projectdiscovery/nuclei
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhosterrorscache_test.go
More file actions
268 lines (229 loc) · 8.03 KB
/
Copy pathhosterrorscache_test.go
File metadata and controls
268 lines (229 loc) · 8.03 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
package hosterrorscache
import (
"context"
"errors"
"sync"
"sync/atomic"
"testing"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/contextargs"
"github.com/projectdiscovery/utils/errkit"
"github.com/stretchr/testify/require"
)
const (
protoType = "http"
)
func TestCacheCheck(t *testing.T) {
cache := New(3, DefaultMaxHostsCount, nil)
err := errors.New("net/http: timeout awaiting response headers")
t.Run("increment host error", func(t *testing.T) {
ctx := newCtxArgs(t.Name())
for i := 1; i < 3; i++ {
cache.MarkFailed(protoType, ctx, err)
got := cache.Check(protoType, ctx)
require.Falsef(t, got, "got %v in iteration %d", got, i)
}
})
t.Run("flagged", func(t *testing.T) {
ctx := newCtxArgs(t.Name())
for i := 1; i <= 3; i++ {
cache.MarkFailed(protoType, ctx, err)
}
got := cache.Check(protoType, ctx)
require.True(t, got)
})
t.Run("mark failed or remove", func(t *testing.T) {
ctx := newCtxArgs(t.Name())
cache.MarkFailedOrRemove(protoType, ctx, nil) // nil error should remove the host from cache
got := cache.Check(protoType, ctx)
require.False(t, got)
})
}
func TestCacheCheckTimeout(t *testing.T) {
// A host that consistently times out (request deadline exceeded) is
// unresponsive and must be skipped once MaxHostError consecutive timeouts
// are recorded. Production surfaces these as ErrKindNetworkTemporary.
cache := New(3, DefaultMaxHostsCount, nil)
err := errkit.New("context deadline exceeded (Client.Timeout exceeded while awaiting headers)").
SetKind(errkit.ErrKindNetworkTemporary)
t.Run("flagged after threshold", func(t *testing.T) {
ctx := newCtxArgs(t.Name())
for i := 1; i <= 3; i++ {
cache.MarkFailed(protoType, ctx, err)
}
require.True(t, cache.Check(protoType, ctx), "host with repeated timeouts must be skipped")
})
t.Run("reset on success keeps a live host", func(t *testing.T) {
ctx := newCtxArgs(t.Name())
cache.MarkFailed(protoType, ctx, err)
cache.MarkFailed(protoType, ctx, err)
cache.MarkFailedOrRemove(protoType, ctx, nil) // a successful response resets the host
require.False(t, cache.Check(protoType, ctx), "a host that responded must not be skipped")
})
}
func TestCacheCheckRawHTTPTimeout(t *testing.T) {
// rawhttp/unsafe templates surface read timeouts as a plain-string error
// ("ReadStatusLine: ... i/o timeout") that errkit cannot classify, so it
// reaches the regex fallback. A host that produces these on every request
// must still be skipped.
cache := New(3, DefaultMaxHostsCount, nil)
err := errors.New("ReadStatusLine: read tcp 127.0.0.1:60087->127.0.0.1:18080: i/o timeout")
ctx := newCtxArgs(t.Name())
for i := 1; i <= 3; i++ {
cache.MarkFailed(protoType, ctx, err)
}
require.True(t, cache.Check(protoType, ctx), "host with repeated rawhttp i/o timeouts must be skipped")
}
func TestMarkSkipsParentContextCancellation(t *testing.T) {
// A failure that happens because the caller's (parent scan) context was
// cancelled or hit its deadline is not the host's fault and must not be
// counted. context.DeadlineExceeded otherwise classifies as a temporary
// network error and would wrongly accumulate.
cache := New(3, DefaultMaxHostsCount, nil)
parent, cancel := context.WithCancel(context.Background())
cancel()
ctx := contextargs.NewWithInput(parent, "cancelled-host")
timeout := errkit.New("context deadline exceeded").SetKind(errkit.ErrKindNetworkTemporary)
for i := 0; i < 5; i++ {
cache.MarkFailedOrRemove(protoType, ctx, timeout)
}
require.False(t, cache.Check(protoType, ctx), "failures under a cancelled parent context must not mark the host")
}
func TestNonConsecutiveTimeoutsDoNotSkip(t *testing.T) {
// A live host that times out intermittently but succeeds in between must not
// be skipped: a success resets the count so only consecutive failures reach
// the threshold. Guards the property the HTTP path relies on.
cache := New(3, DefaultMaxHostsCount, nil)
ctx := newCtxArgs(t.Name())
timeout := errkit.New("i/o timeout").SetKind(errkit.ErrKindNetworkTemporary)
cache.MarkFailedOrRemove(protoType, ctx, timeout)
cache.MarkFailedOrRemove(protoType, ctx, timeout)
cache.MarkFailedOrRemove(protoType, ctx, nil) // successful response resets the host
cache.MarkFailedOrRemove(protoType, ctx, timeout)
require.False(t, cache.Check(protoType, ctx), "a success between timeouts must reset the count")
}
func TestTrackErrors(t *testing.T) {
cache := New(3, DefaultMaxHostsCount, []string{"custom error"})
for i := 0; i < 100; i++ {
cache.MarkFailed(protoType, newCtxArgs("custom"), errors.New("got: nested: custom error"))
got := cache.Check(protoType, newCtxArgs("custom"))
if i < 2 {
// till 3 the host is not flagged to skip
require.False(t, got)
} else {
// above 3 it must remain flagged to skip
require.True(t, got)
}
}
value := cache.Check(protoType, newCtxArgs("custom"))
require.Equal(t, true, value, "could not get checked value")
}
func TestCacheItemDo(t *testing.T) {
var (
count int
item cacheItem
)
wg := sync.WaitGroup{}
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
item.Do(func() {
count++
})
}()
}
wg.Wait()
// ensures the increment happened only once regardless of the multiple call
require.Equal(t, count, 1)
}
func TestRemove(t *testing.T) {
cache := New(3, DefaultMaxHostsCount, nil)
ctx := newCtxArgs(t.Name())
err := errors.New("net/http: timeout awaiting response headers")
for i := 0; i < 100; i++ {
cache.MarkFailed(protoType, ctx, err)
}
require.True(t, cache.Check(protoType, ctx))
cache.Remove(ctx)
require.False(t, cache.Check(protoType, ctx))
}
func TestCacheMarkFailed(t *testing.T) {
cache := New(3, DefaultMaxHostsCount, nil)
tests := []struct {
host string
expected int32
}{
{"http://example.com:80", 1},
{"example.com:80", 2},
// earlier if port is not provided then port was omitted
// but from now it will default to appropriate http scheme based port with 80 as default
{"example.com:443", 1},
}
for _, test := range tests {
normalizedCacheValue := cache.GetKeyFromContext(newCtxArgs(test.host), nil)
cache.MarkFailed(protoType, newCtxArgs(test.host), errors.New("no address found for host"))
failedTarget, err := cache.failedTargets.Get(normalizedCacheValue)
require.Nil(t, err)
require.NotNil(t, failedTarget)
require.EqualValues(t, test.expected, failedTarget.errors.Load())
}
}
func TestCacheMarkFailedConcurrent(t *testing.T) {
cache := New(3, DefaultMaxHostsCount, nil)
tests := []struct {
host string
expected int32
}{
{"http://example.com:80", 200},
{"example.com:80", 200},
{"example.com:443", 100},
}
// the cache is not atomic during items creation, so we pre-create them with counter to zero
for _, test := range tests {
normalizedValue := cache.NormalizeCacheValue(test.host)
newItem := &cacheItem{errors: atomic.Int32{}}
newItem.errors.Store(0)
_ = cache.failedTargets.Set(normalizedValue, newItem)
}
wg := sync.WaitGroup{}
for _, test := range tests {
currentTest := test
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
cache.MarkFailed(protoType, newCtxArgs(currentTest.host), errors.New("net/http: timeout awaiting response headers"))
}()
}
}
wg.Wait()
for _, test := range tests {
require.True(t, cache.Check(protoType, newCtxArgs(test.host)))
normalizedCacheValue := cache.NormalizeCacheValue(test.host)
failedTarget, err := cache.failedTargets.Get(normalizedCacheValue)
require.Nil(t, err)
require.NotNil(t, failedTarget)
require.EqualValues(t, test.expected, failedTarget.errors.Load())
}
}
func TestCacheCheckConcurrent(t *testing.T) {
cache := New(3, DefaultMaxHostsCount, nil)
ctx := newCtxArgs(t.Name())
wg := sync.WaitGroup{}
for i := 1; i <= 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
cache.MarkFailed(protoType, ctx, errors.New("no address found for host"))
if i >= 3 {
got := cache.Check(protoType, ctx)
require.True(t, got)
}
}()
}
wg.Wait()
}
func newCtxArgs(value string) *contextargs.Context {
ctx := contextargs.NewWithInput(context.TODO(), value)
return ctx
}