Debian Codegraph @

dnscrypt-proxy/sources_test.go

raw symbols SCIP
1 package main
2
3 import (
4 "bytes"
5 "fmt"
6 "net/http"
7 "net/http/httptest"
8 "net/url"
9 "os"
10 "path/filepath"
11 "strconv"
12 "strings"
13 "testing"
14 "time"
15
16 "github.com/hectane/go-acl"
17 "github.com/jedisct1/dlog"
18 "github.com/jedisct1/go-minisign"
19 "github.com/powerman/check"
20 )
21
22 type SourceFixture struct {
23 suffix string
24 content []byte
25 length string // HTTP Content-Length header
26 perms os.FileMode
27 mtime time.Time
28 }
29 type SourceTestState uint8
30
31 const (
32 TestStateCorrect SourceTestState = iota // valid files
33 TestStateExpired // modification time of files set in distant past (cache only)
34 TestStatePartial // incomplete files
35 TestStatePartialSig // incomplete .minisig
36 TestStateMissing // non-existent files
37 TestStateMissingSig // non-existent .minisig
38 TestStateReadErr // I/O error on reading files (download only)
39 TestStateReadSigErr // I/O error on reading .minisig (download only)
40 TestStateOpenErr // I/O error on opening files
41 TestStateOpenSigErr // I/O error on opening .minisig
42 TestStatePathErr // unparsable path to files (download only)
43 )
44
45 type SourceTestData struct {
46 n int // subtest counter
47 xTransport *XTransport
48 key *minisign.PublicKey
49 keyStr, tempDir string
50 sources []string
51 fixtures map[SourceTestState]map[string]SourceFixture
52 timeNow, timeOld, timeUpd time.Time
53 server *httptest.Server
54 reqActual, reqExpect map[string]uint
55 cacheTests map[string]SourceTestState
56 downloadTests map[string][]SourceTestState
57 }
58
59 type SourceTestExpect struct {
60 success bool
61 err, cachePath string
62 cache []SourceFixture
63 mtime time.Time
64 urls []string
65 Source *Source
66 delay time.Duration
67 prefix string
68 }
69
70 func readFixture(t *testing.T, name string) []byte {
71 bin, err := os.ReadFile(filepath.Join("testdata", name))
72 if err != nil {
73 t.Fatalf("Unable to read test fixture %s: %v", name, err)
74 }
75 return bin
76 }
77
78 func writeSourceCache(t *testing.T, e *SourceTestExpect) {
79 for _, f := range e.cache {
80 if f.content == nil {
81 continue
82 }
83 path := e.cachePath + f.suffix
84 perms := f.perms
85 if perms == 0 {
86 perms = 0o644
87 }
88 if err := os.WriteFile(path, f.content, perms); err != nil {
89 t.Fatalf("Unable to write cache file %s: %v", path, err)
90 }
91 if err := acl.Chmod(path, perms); err != nil {
92 t.Fatalf("Unable to set permissions on cache file %s: %v", path, err)
93 }
94 if f.suffix != "" {
95 continue
96 }
97 mtime := f.mtime
98 if f.mtime.IsZero() {
99 mtime = e.mtime
100 }
101 if err := os.Chtimes(path, mtime, mtime); err != nil {
102 t.Fatalf("Unable to touch cache file %s to %v: %v", path, f.mtime, err)
103 }
104 }
105 }
106
107 func checkSourceCache(c *check.C, e *SourceTestExpect) {
108 for _, f := range e.cache {
109 path := e.cachePath + f.suffix
110 _ = acl.Chmod(path, 0o644) // don't worry if this fails, reading it will catch the same problem
111 got, err := os.ReadFile(path)
112 c.DeepEqual(got, f.content, "Unexpected content for cache file '%s', err %v", path, err)
113 if f.suffix != "" {
114 continue
115 }
116 if fi, err := os.Stat(path); err == nil { // again, if this failed it was already caught above
117 mtime := f.mtime
118 if f.mtime.IsZero() {
119 mtime = e.mtime
120 }
121 c.EQ(fi.ModTime(), mtime, "Unexpected timestamp for cache file '%s'", path)
122 }
123 }
124 }
125
126 func loadSnakeoil(t *testing.T, d *SourceTestData) {
127 key, err := minisign.NewPublicKeyFromFile(filepath.Join("testdata", "snakeoil.pub"))
128 if err != nil {
129 t.Fatalf("Unable to load snakeoil key: %v", err)
130 }
131 d.keyStr = string(bytes.SplitN(readFixture(t, "snakeoil.pub"), []byte("\n"), 2)[1])
132 d.key = &key
133 }
134
135 func loadTestSourceNames(t *testing.T, d *SourceTestData) {
136 files, err := os.ReadDir(filepath.Join("testdata", "sources"))
137 if err != nil {
138 t.Fatalf("Unable to load list of test sources: %v", err)
139 }
140 for _, file := range files {
141 if !file.IsDir() && strings.HasSuffix(file.Name(), ".minisig") {
142 d.sources = append(d.sources, strings.TrimSuffix(file.Name(), ".minisig"))
143 }
144 }
145 }
146
147 func generateFixtureState(_ *testing.T, d *SourceTestData, suffix, file string, state SourceTestState) {
148 if _, ok := d.fixtures[state]; !ok {
149 d.fixtures[state] = map[string]SourceFixture{}
150 }
151 if suffix != ".minisig" {
152 switch state {
153 case TestStatePartialSig, TestStateMissingSig, TestStateReadSigErr, TestStateOpenSigErr:
154 d.fixtures[state][file] = d.fixtures[TestStateCorrect][file]
155 return
156 }
157 }
158 f := SourceFixture{suffix: suffix}
159 switch state {
160 case TestStateExpired:
161 f.content, f.mtime = d.fixtures[TestStateCorrect][file].content, d.timeOld
162 case TestStatePartial, TestStatePartialSig:
163 f.content = d.fixtures[TestStateCorrect][file].content[:1]
164 case TestStateReadErr, TestStateReadSigErr:
165 f.content, f.length = []byte{}, "1"
166 case TestStateOpenErr, TestStateOpenSigErr:
167 f.content, f.perms = d.fixtures[TestStateCorrect][file].content[:1], 0o200
168 }
169 d.fixtures[state][file] = f
170 }
171
172 func loadFixtures(t *testing.T, d *SourceTestData) {
173 d.fixtures = map[SourceTestState]map[string]SourceFixture{TestStateCorrect: {}}
174 for _, source := range d.sources {
175 for _, suffix := range [...]string{"", ".minisig"} {
176 file := source + suffix
177 d.fixtures[TestStateCorrect][file] = SourceFixture{
178 suffix: suffix,
179 content: readFixture(t, filepath.Join("sources", file)),
180 }
181 for _, state := range [...]SourceTestState{
182 TestStateExpired,
183 TestStatePartial,
184 TestStateReadErr,
185 TestStateOpenErr,
186 TestStatePartialSig,
187 TestStateMissingSig,
188 TestStateReadSigErr,
189 TestStateOpenSigErr,
190 } {
191 generateFixtureState(t, d, suffix, file, state)
192 }
193 }
194 }
195 }
196
197 func makeTempDir(t *testing.T, d *SourceTestData) {
198 name, err := os.MkdirTemp("", "sources_test.go."+t.Name())
199 if err != nil {
200 t.Fatalf("Unable to create temporary directory: %v", err)
201 }
202 d.tempDir = name
203 }
204
205 func makeTestServer(t *testing.T, d *SourceTestData) {
206 d.reqActual, d.reqExpect = map[string]uint{}, map[string]uint{}
207 d.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
208 var data []byte = nil
209 d.reqActual[r.URL.Path]++
210 pathParts := strings.SplitN(strings.TrimPrefix(r.URL.Path, "/"), "/", 2)
211 state, _ := strconv.ParseUint(pathParts[0], 10, 8)
212 if fixture, ok := d.fixtures[SourceTestState(state)][pathParts[1]]; ok {
213 if len(fixture.length) > 0 {
214 w.Header().Set("Content-Length", fixture.length) // client will return unexpected EOF
215 }
216 data = fixture.content
217 }
218 if data != nil {
219 if _, err := w.Write(data); err != nil {
220 t.Logf("Error writing HTTP response for request [%s]: %v", r.URL.Path, err)
221 }
222 } else {
223 w.WriteHeader(http.StatusNotFound)
224 }
225 }))
226 }
227
228 func checkTestServer(c *check.C, d *SourceTestData) {
229 c.DeepEqual(d.reqActual, d.reqExpect, "Unexpected HTTP request log")
230 d.reqActual, d.reqExpect = map[string]uint{}, map[string]uint{}
231 }
232
233 func setupSourceTest(t *testing.T) (func(), *SourceTestData) {
234 d := &SourceTestData{n: -1, xTransport: NewXTransport()}
235 d.cacheTests = map[string]SourceTestState{ // determines cache files written to disk before each call
236 "correct": TestStateCorrect,
237 "expired": TestStateExpired,
238 "partial": TestStatePartial,
239 "partial-sig": TestStatePartialSig,
240 "missing": TestStateMissing,
241 "missing-sig": TestStateMissingSig,
242 "open-err": TestStateOpenErr,
243 "open-sig-err": TestStateOpenSigErr,
244 }
245 d.downloadTests = map[string][]SourceTestState{ // determines the list of URLs passed in each call and how they will respond
246 "correct": {TestStateCorrect},
247 "partial": {TestStatePartial},
248 "partial-sig": {TestStatePartialSig},
249 "missing": {TestStateMissing},
250 "missing-sig": {TestStateMissingSig},
251 "read-err": {TestStateReadErr},
252 "read-sig-err": {TestStateReadSigErr},
253 "open-err": {TestStateOpenErr},
254 "open-sig-err": {TestStateOpenSigErr},
255 "path-err": {TestStatePathErr},
256 "partial,correct": {TestStatePartial, TestStateCorrect},
257 "partial-sig,correct": {TestStatePartialSig, TestStateCorrect},
258 "missing,correct": {TestStateMissing, TestStateCorrect},
259 "missing-sig,correct": {TestStateMissingSig, TestStateCorrect},
260 "read-err,correct": {TestStateReadErr, TestStateCorrect},
261 "read-sig-err,correct": {TestStateReadSigErr, TestStateCorrect},
262 "open-err,correct": {TestStateOpenErr, TestStateCorrect},
263 "open-sig-err,correct": {TestStateOpenSigErr, TestStateCorrect},
264 "path-err,correct": {TestStatePathErr, TestStateCorrect},
265 "no-urls": {},
266 }
267 d.xTransport.rebuildTransport()
268 d.timeNow = time.Now().AddDate(0, 0, 0).Truncate(time.Second)
269 d.timeOld = d.timeNow.Add(DefaultPrefetchDelay * -4)
270 d.timeUpd = d.timeNow.Add(DefaultPrefetchDelay)
271 timeNow = func() time.Time { return d.timeNow } // originally defined in sources.go, replaced during testing to ensure consistent results
272 makeTempDir(t, d)
273 makeTestServer(t, d)
274 loadSnakeoil(t, d)
275 loadTestSourceNames(t, d)
276 loadFixtures(t, d)
277 return func() {
278 os.RemoveAll(d.tempDir)
279 d.server.Close()
280 }, d
281 }
282
283 func prepSourceTestCache(t *testing.T, d *SourceTestData, e *SourceTestExpect, source string, state SourceTestState) {
284 e.cache = []SourceFixture{d.fixtures[state][source], d.fixtures[state][source+".minisig"]}
285 switch state {
286 case TestStateCorrect:
287 e.Source.bin, e.success = e.cache[0].content, true
288 case TestStateExpired:
289 e.Source.bin = e.cache[0].content
290 case TestStatePartial, TestStatePartialSig:
291 e.err = "signature"
292 case TestStateMissing, TestStateMissingSig, TestStateOpenErr, TestStateOpenSigErr:
293 e.err = "open"
294 }
295 writeSourceCache(t, e)
296 }
297
298 func prepSourceTestDownload(
299 _ *testing.T,
300 d *SourceTestData,
301 e *SourceTestExpect,
302 source string,
303 downloadTest []SourceTestState,
304 ) {
305 if len(downloadTest) == 0 {
306 return
307 }
308 for _, state := range downloadTest {
309 path := "/" + strconv.FormatUint(uint64(state), 10) + "/" + source
310 serverURL := d.server.URL
311 switch state {
312 case TestStateMissing, TestStateMissingSig:
313 e.err = "404 Not Found"
314 case TestStatePartial, TestStatePartialSig:
315 e.err = "signature"
316 case TestStateReadErr, TestStateReadSigErr:
317 e.err = "unexpected EOF"
318 case TestStateOpenErr, TestStateOpenSigErr:
319 if u, err := url.Parse(serverURL + path); err == nil {
320 host, port := ExtractHostAndPort(u.Host, -1)
321 u.Host = fmt.Sprintf(
322 "%s:%d",
323 host,
324 port|0x10000,
325 ) // high numeric port is parsed but then fails to connect
326 serverURL = u.String()
327 }
328 e.err = "invalid port"
329 case TestStatePathErr:
330 path = "..." + path // non-numeric port fails URL parsing
331 }
332 if u, err := url.Parse(serverURL + path); err == nil {
333 e.Source.urls = append(e.Source.urls, u)
334 }
335 e.urls = append(e.urls, serverURL+path)
336 if e.success {
337 continue
338 }
339 switch state {
340 case TestStateCorrect:
341 e.cache = []SourceFixture{d.fixtures[state][source], d.fixtures[state][source+".minisig"]}
342 e.Source.bin, e.success = e.cache[0].content, true
343 fallthrough
344 case TestStateMissingSig, TestStatePartial, TestStatePartialSig, TestStateReadSigErr:
345 d.reqExpect[path+".minisig"]++
346 fallthrough
347 case TestStateMissing, TestStateReadErr:
348 d.reqExpect[path]++
349 }
350 }
351 if e.success {
352 e.err = ""
353 e.delay = DefaultPrefetchDelay * 3 // matches cacheTTL/prefetchDelay set in setupSourceTestCase
354 } else {
355 e.delay = MinimumPrefetchInterval
356 }
357 if len(e.Source.urls) > 0 {
358 e.Source.refresh = d.timeNow.Add(e.delay)
359 } else {
360 e.success = false
361 }
362 }
363
364 func setupSourceTestCase(t *testing.T, d *SourceTestData, i int,
365 cacheTest *SourceTestState, downloadTest []SourceTestState,
366 ) (id string, e *SourceTestExpect) {
367 id = strconv.Itoa(d.n) + "-" + strconv.Itoa(i)
368 e = &SourceTestExpect{
369 cachePath: filepath.Join(d.tempDir, id),
370 mtime: d.timeNow,
371 }
372 e.Source = &Source{
373 name: id, urls: []*url.URL{}, format: SourceFormatV2, minisignKey: d.key,
374 cacheFile: e.cachePath, cacheTTL: DefaultPrefetchDelay * 3, prefetchDelay: DefaultPrefetchDelay * 3,
375 }
376 if cacheTest != nil {
377 prepSourceTestCache(t, d, e, d.sources[i], *cacheTest)
378 i = (i + 1) % len(d.sources) // make the cached and downloaded fixtures different
379 }
380 prepSourceTestDownload(t, d, e, d.sources[i], downloadTest)
381 return id, e
382 }
383
384 func TestNewSource(t *testing.T) {
385 if testing.Verbose() {
386 dlog.SetLogLevel(dlog.SeverityDebug)
387 dlog.UseSyslog(false)
388 }
389 teardown, d := setupSourceTest(t)
390 defer teardown()
391 checkResult := func(t *testing.T, e *SourceTestExpect, got *Source, err error) {
392 c := check.T(t)
393 if len(e.err) > 0 {
394 c.Match(err, e.err, "Unexpected error")
395 } else {
396 c.Nil(err, "Unexpected error")
397 }
398 c.DeepEqual(got, e.Source, "Unexpected return")
399 checkTestServer(c, d)
400 checkSourceCache(c, e)
401 }
402 d.n++
403 for _, tt := range []struct {
404 v, key string
405 refreshDelay, cacheTTL time.Duration
406 e *SourceTestExpect
407 }{
408 {"", "", 0, 0, &SourceTestExpect{err: " ", Source: &Source{name: "short refresh delay", urls: []*url.URL{}, cacheTTL: DefaultPrefetchDelay, prefetchDelay: DefaultPrefetchDelay, prefix: ""}}},
409 {"v1", d.keyStr, DefaultPrefetchDelay * 2, DefaultPrefetchDelay * 2, &SourceTestExpect{err: "Unsupported source format", Source: &Source{name: "old format", urls: []*url.URL{}, cacheTTL: DefaultPrefetchDelay * 2, prefetchDelay: DefaultPrefetchDelay * 2}}},
410 {"v2", "", DefaultPrefetchDelay * 3, DefaultPrefetchDelay * 3, &SourceTestExpect{err: "Invalid encoded public key", Source: &Source{name: "invalid public key", urls: []*url.URL{}, cacheTTL: DefaultPrefetchDelay * 3, prefetchDelay: DefaultPrefetchDelay * 3}}},
411 } {
412 t.Run(tt.e.Source.name, func(t *testing.T) {
413 got, err := NewSource(
414 tt.e.Source.name,
415 d.xTransport,
416 tt.e.urls,
417 tt.key,
418 tt.e.cachePath,
419 tt.v,
420 tt.refreshDelay,
421 tt.cacheTTL,
422 tt.e.prefix,
423 )
424 checkResult(t, tt.e, got, err)
425 })
426 }
427 for cacheTestName, cacheTest := range d.cacheTests {
428 for downloadTestName, downloadTest := range d.downloadTests {
429 d.n++
430 for i := range d.sources {
431 id, e := setupSourceTestCase(t, d, i, &cacheTest, downloadTest)
432 t.Run("cache "+cacheTestName+", download "+downloadTestName+"/"+id, func(t *testing.T) {
433 got, err := NewSource(
434 id,
435 d.xTransport,
436 e.urls,
437 d.keyStr,
438 e.cachePath,
439 "v2",
440 DefaultPrefetchDelay*3,
441 DefaultPrefetchDelay*3,
442 "",
443 )
444 checkResult(t, e, got, err)
445 })
446 }
447 }
448 }
449 }
450
451 func TestPrefetchSources(t *testing.T) {
452 if testing.Verbose() {
453 dlog.SetLogLevel(dlog.SeverityDebug)
454 dlog.UseSyslog(false)
455 }
456 teardown, d := setupSourceTest(t)
457 defer teardown()
458 checkResult := func(t *testing.T, expects []*SourceTestExpect, got time.Duration) {
459 c := check.T(t)
460 expectDelay := MinimumPrefetchInterval
461 for _, e := range expects {
462 if e.delay >= MinimumPrefetchInterval && (expectDelay == MinimumPrefetchInterval || expectDelay > e.delay) {
463 expectDelay = e.delay
464 }
465 }
466 c.InDelta(got, expectDelay, time.Second, "Unexpected return")
467 checkTestServer(c, d)
468 for _, e := range expects {
469 checkSourceCache(c, e)
470 }
471 }
472 timeNow = func() time.Time { return d.timeUpd } // since the fixtures are prepared using real now, make the tested code think it's the future
473 for downloadTestName, downloadTest := range d.downloadTests {
474 d.n++
475 sources := []*Source{}
476 expects := []*SourceTestExpect{}
477 for i := range d.sources {
478 _, e := setupSourceTestCase(t, d, i, nil, downloadTest)
479 e.mtime = d.timeUpd
480 s := &Source{
481 name: e.Source.name,
482 urls: e.Source.urls,
483 format: e.Source.format,
484 minisignKey: e.Source.minisignKey,
485 cacheFile: e.Source.cacheFile,
486 cacheTTL: e.Source.cacheTTL,
487 prefetchDelay: e.Source.prefetchDelay,
488 refresh: d.timeUpd, // Set to trigger prefetch (source.refresh.After(now) will be false)
489 prefix: e.Source.prefix,
490 // bin is intentionally left nil
491 }
492 sources = append(sources, s)
493 expects = append(expects, e)
494 }
495 t.Run("download "+downloadTestName, func(t *testing.T) {
496 got := PrefetchSources(d.xTransport, sources)
497 checkResult(t, expects, got)
498 })
499 }
500 }
501
502 func TestMain(m *testing.M) { check.TestMain(m) }