-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathcache-redis_test.go
More file actions
329 lines (278 loc) · 8.51 KB
/
cache-redis_test.go
File metadata and controls
329 lines (278 loc) · 8.51 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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package rdns
import (
"fmt"
"net"
"sync"
"testing"
"time"
"github.com/miekg/dns"
)
// The Redis cache key must distinguish CD=0 from CD=1 (RFC 4035 §4.7 /
// RFC 6840 §5.9) and ECS responses with a different source-prefix length.
func TestRedisKeyFromQuery(t *testing.T) {
b := &redisBackend{}
queryCD := func(cd bool) *dns.Msg {
q := new(dns.Msg)
q.SetQuestion("example.com.", dns.TypeA)
q.CheckingDisabled = cd
return q
}
if b.keyFromQuery(queryCD(false)) == b.keyFromQuery(queryCD(true)) {
t.Fatal("CD=0 and CD=1 queries produced the same Redis cache key")
}
queryECS := func(mask uint8) *dns.Msg {
q := new(dns.Msg)
q.SetQuestion("example.com.", dns.TypeA)
q.SetEdns0(4096, false)
ecs := new(dns.EDNS0_SUBNET)
ecs.Code = dns.EDNS0SUBNET
ecs.Family = 1
ecs.SourceNetmask = mask
ecs.Address = net.IP{192, 0, 2, 0}
q.IsEdns0().Option = append(q.IsEdns0().Option, ecs)
return q
}
if b.keyFromQuery(queryECS(24)) == b.keyFromQuery(queryECS(16)) {
t.Fatal("ECS queries with different source-prefix lengths produced the same Redis cache key")
}
}
func TestEncodeDecode(t *testing.T) {
// Create a test DNS message
msg := new(dns.Msg)
msg.SetQuestion("example.com.", dns.TypeA)
msg.Response = true
msg.Rcode = dns.RcodeSuccess
// Add an answer
rr, err := dns.NewRR("example.com. 300 IN A 192.0.2.1")
if err != nil {
t.Fatalf("failed to create RR: %v", err)
}
msg.Answer = append(msg.Answer, rr)
// Create a cacheAnswer
now := time.Now()
original := &cacheAnswer{
Timestamp: now,
PrefetchEligible: true,
Msg: msg,
}
// Encode
encoded, err := encodeCacheAnswer(original)
if err != nil {
t.Fatalf("encodeCacheAnswer failed: %v", err)
}
// Verify format
if len(encoded) < headerSize {
t.Fatalf("encoded data too short: %d bytes", len(encoded))
}
// Check version byte
if encoded[0] != binaryFormatVersion {
t.Errorf("version byte = %d, want %d", encoded[0], binaryFormatVersion)
}
// Check flags byte
expectedFlags := byte(flagPrefetchBit)
if encoded[1] != expectedFlags {
t.Errorf("flags byte = %d, want %d", encoded[1], expectedFlags)
}
// Decode
decoded, err := decodeCacheAnswer(encoded)
if err != nil {
t.Fatalf("decodeCacheAnswer failed: %v", err)
}
// Verify fields
if decoded.Timestamp.Unix() != original.Timestamp.Unix() {
t.Errorf("timestamp = %v, want %v", decoded.Timestamp, original.Timestamp)
}
if decoded.PrefetchEligible != original.PrefetchEligible {
t.Errorf("prefetchEligible = %v, want %v", decoded.PrefetchEligible, original.PrefetchEligible)
}
// Verify DNS message
if len(decoded.Msg.Answer) != len(original.Msg.Answer) {
t.Errorf("answer count = %d, want %d", len(decoded.Msg.Answer), len(original.Msg.Answer))
}
if decoded.Msg.Question[0].Name != original.Msg.Question[0].Name {
t.Errorf("question name = %s, want %s", decoded.Msg.Question[0].Name, original.Msg.Question[0].Name)
}
if decoded.Msg.Question[0].Qtype != original.Msg.Question[0].Qtype {
t.Errorf("question type = %d, want %d", decoded.Msg.Question[0].Qtype, original.Msg.Question[0].Qtype)
}
}
func TestEncodeDecodeNoPrefetch(t *testing.T) {
// Create a test DNS message
msg := new(dns.Msg)
msg.SetQuestion("test.example.", dns.TypeAAAA)
msg.Response = true
// Create a cacheAnswer with prefetch disabled
original := &cacheAnswer{
Timestamp: time.Unix(1234567890, 0),
PrefetchEligible: false,
Msg: msg,
}
// Encode
encoded, err := encodeCacheAnswer(original)
if err != nil {
t.Fatalf("encodeCacheAnswer failed: %v", err)
}
// Check flags byte (should be 0)
if encoded[1] != 0 {
t.Errorf("flags byte = %d, want 0", encoded[1])
}
// Decode
decoded, err := decodeCacheAnswer(encoded)
if err != nil {
t.Fatalf("decodeCacheAnswer failed: %v", err)
}
if decoded.PrefetchEligible != false {
t.Errorf("prefetchEligible = %v, want false", decoded.PrefetchEligible)
}
}
func TestDecodeInvalidData(t *testing.T) {
tests := []struct {
name string
data []byte
}{
{"too short", []byte{0x01, 0x00}},
{"wrong version", []byte{0x99, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
{"invalid DNS", []byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := decodeCacheAnswer(tt.data)
if err == nil {
t.Error("expected error, got nil")
}
})
}
}
func TestEncodeDecodePooling(t *testing.T) {
// Test that pooling works correctly across multiple encode operations
msg := new(dns.Msg)
msg.SetQuestion("pool.test.", dns.TypeA)
msg.Response = true
item := &cacheAnswer{
Timestamp: time.Now(),
PrefetchEligible: true,
Msg: msg,
}
// Encode multiple times to test pool reuse
for i := range 100 {
encoded, err := encodeCacheAnswer(item)
if err != nil {
t.Fatalf("iteration %d: encodeCacheAnswer failed: %v", i, err)
}
// Verify first byte is always version
if encoded[0] != binaryFormatVersion {
t.Errorf("iteration %d: version byte = %d, want %d", i, encoded[0], binaryFormatVersion)
}
// Decode to verify correctness
decoded, err := decodeCacheAnswer(encoded)
if err != nil {
t.Fatalf("iteration %d: decodeCacheAnswer failed: %v", i, err)
}
if decoded.Msg.Question[0].Name != "pool.test." {
t.Errorf("iteration %d: corrupted data", i)
}
}
}
func TestEncodeReturnsIndependentSlice(t *testing.T) {
// Verify that encoded bytes are independent of the pool and mutations don't affect subsequent encodes
msg := new(dns.Msg)
msg.SetQuestion("independent.test.", dns.TypeA)
msg.Response = true
item := &cacheAnswer{
Timestamp: time.Unix(1234567890, 0),
PrefetchEligible: true,
Msg: msg,
}
// First encode
encoded1, err := encodeCacheAnswer(item)
if err != nil {
t.Fatalf("first encode failed: %v", err)
}
// Save a copy of the original encoded data
original := make([]byte, len(encoded1))
copy(original, encoded1)
// Mutate the returned slice to verify it's independent of the pool
for i := range encoded1 {
encoded1[i] = 0xFF
}
// Verify the mutated buffer is now garbage and fails to decode
_, err = decodeCacheAnswer(encoded1)
if err == nil {
t.Error("expected decode of mutated buffer to fail, but it succeeded")
}
// Second encode - should succeed and produce the same result as the first
encoded2, err := encodeCacheAnswer(item)
if err != nil {
t.Fatalf("second encode failed: %v", err)
}
// Verify second encode matches the original (not corrupted by mutation)
if len(encoded2) != len(original) {
t.Fatalf("length mismatch: got %d, want %d", len(encoded2), len(original))
}
for i := range original {
if encoded2[i] != original[i] {
t.Errorf("byte %d: got %02x, want %02x (mutation leaked into pool)", i, encoded2[i], original[i])
}
}
// Verify we can still decode the second result
decoded, err := decodeCacheAnswer(encoded2)
if err != nil {
t.Fatalf("decode after mutation failed: %v", err)
}
if decoded.Msg.Question[0].Name != "independent.test." {
t.Errorf("decoded name = %s, want independent.test.", decoded.Msg.Question[0].Name)
}
}
func TestEncodeConcurrent(t *testing.T) {
// Test concurrent encoding to catch pool-related race conditions
// Each goroutine gets its own dns.Msg to avoid racing on shared message internals
const numGoroutines = 50
const numIterations = 100
errs := make(chan error, numGoroutines)
var wg sync.WaitGroup
wg.Add(numGoroutines)
for g := range numGoroutines {
go func(gid int) {
defer wg.Done()
msg := new(dns.Msg)
msg.SetQuestion("concurrent.test.", dns.TypeA)
msg.Response = true
rr, err := dns.NewRR("concurrent.test. 300 IN A 192.0.2.1")
if err != nil {
errs <- err
return
}
msg.Answer = append(msg.Answer, rr)
item := &cacheAnswer{
Timestamp: time.Now(),
PrefetchEligible: true,
Msg: msg,
}
for i := range numIterations {
encoded, err := encodeCacheAnswer(item)
if err != nil {
errs <- err
return
}
if encoded[0] != binaryFormatVersion {
errs <- fmt.Errorf("goroutine %d iteration %d: invalid version byte %d", gid, i, encoded[0])
return
}
decoded, err := decodeCacheAnswer(encoded)
if err != nil {
errs <- err
return
}
if decoded.Msg.Question[0].Name != "concurrent.test." {
errs <- fmt.Errorf("goroutine %d iteration %d: corrupted data, got name %s", gid, i, decoded.Msg.Question[0].Name)
return
}
}
}(g)
}
wg.Wait()
close(errs)
for err := range errs {
t.Fatalf("concurrent encode/decode failed: %v", err)
}
}