Debian Codegraph @

http/http_test.go

raw
1 // Copyright (c) 2025 Arnaud Rebillout
2 // Licensed under the MIT license
3
4 package http
5
6 import (
7 "errors"
8 "net"
9 "net/http"
10 "net/http/httptest"
11 "net/http/httputil"
12 "os"
13 "path"
14 "reflect"
15 "strings"
16 "syscall"
17 "testing"
18
19 . "github.com/etix/mirrorbits/config"
20 "github.com/etix/mirrorbits/core"
21 "github.com/etix/mirrorbits/mirrors"
22 . "github.com/etix/mirrorbits/testing"
23 "github.com/rafaeljusto/redigomock"
24 )
25
26 var (
27 fallbackURL = "http://fallback.mirror/"
28 mirrorURL = "http://example.mirror/"
29 testFile = "/testy.tgz"
30 testFileSize = "48"
31 testFileModTime = "2025-06-01 06:00:00.123456789 +0000 UTC"
32 testFileSha256 = "1235a5b376903794b373d84ed615bb36013e70ed6aebf30b2f4823321d5182ec"
33 testFileLastModified = "Sun, 01 Jun 2025 06:00:00 GMT"
34 )
35
36 // Join URL and a path
37 func urlJoinPath(url, filepath string) string {
38 return url + strings.TrimLeft(filepath, "/")
39 }
40
41 // Create an empty file within a directory, fail if it already exists
42 func makeEmptyFile(dir, filename string) error {
43 filePath := path.Join(dir, filename)
44 fileFlags := os.O_CREATE|os.O_EXCL|os.O_WRONLY
45 f, err := os.OpenFile(filePath, fileFlags, 0644)
46 if err != nil {
47 return err
48 }
49 return f.Close()
50 }
51
52 // Make a request
53 func makeRequest(method, url string, headers map[string]string) *http.Request {
54 req := httptest.NewRequest(method, url, nil)
55 for k, v := range headers {
56 req.Header.Set(k, v)
57 }
58 return req
59 }
60
61 // Make a response, as returned by mirrorbits
62 func makeResponse(code int, headers map[string]string) *http.Response {
63 var resp http.Response
64
65 switch code {
66 case 302:
67 resp = http.Response{
68 Status: "302 Found",
69 StatusCode: 302,
70 Proto: "HTTP/1.1",
71 ProtoMajor: 1,
72 ProtoMinor: 1,
73 Header: http.Header{
74 "Cache-Control": {"private, no-cache"},
75 "Content-Type": {"text/html; charset=utf-8"},
76 "Server": {"Mirrorbits/"+core.VERSION},
77 },
78 ContentLength: -1,
79 }
80 case 304:
81 resp = http.Response{
82 Status: "304 Not Modified",
83 StatusCode: 304,
84 Proto: "HTTP/1.1",
85 ProtoMajor: 1,
86 ProtoMinor: 1,
87 Header: http.Header{
88 "Server": {"Mirrorbits/"+core.VERSION},
89 },
90 ContentLength: -1,
91 }
92 case 403:
93 resp = http.Response{
94 Status: "403 Forbidden",
95 StatusCode: 403,
96 Proto: "HTTP/1.1",
97 ProtoMajor: 1,
98 ProtoMinor: 1,
99 Header: http.Header{
100 "Content-Type": {"text/plain; charset=utf-8"},
101 "Server": {"Mirrorbits/"+core.VERSION},
102 "X-Content-Type-Options": {"nosniff"},
103 },
104 ContentLength: -1,
105 }
106 case 404:
107 resp = http.Response{
108 Status: "404 Not Found",
109 StatusCode: 404,
110 Proto: "HTTP/1.1",
111 ProtoMajor: 1,
112 ProtoMinor: 1,
113 Header: http.Header{
114 "Content-Type": {"text/plain; charset=utf-8"},
115 "Server": {"Mirrorbits/"+core.VERSION},
116 "X-Content-Type-Options": {"nosniff"},
117 },
118 ContentLength: -1,
119 }
120 default:
121 resp = http.Response{}
122 }
123
124 for k, v := range headers {
125 resp.Header.Set(k, v)
126 }
127
128 return &resp
129 }
130
131 // Do a request and return the response
132 func doRequest(h *HTTP, method string, url string, headers map[string]string) (*http.Response) {
133 req := makeRequest(method, url, headers)
134 recorder := httptest.NewRecorder()
135 // Note: requestDispatcher calls mirrorHandler
136 h.requestDispatcher(recorder, req)
137 return recorder.Result()
138 }
139
140 // Check if two http.Response are equal, excluding the body
141 func respEqual(r1 *http.Response, r2 *http.Response) bool {
142 r1Body, r2Body := r1.Body, r2.Body
143 r1.Body, r2.Body = nil, nil
144 res := reflect.DeepEqual(r1, r2)
145 r1.Body, r2.Body = r1Body, r2Body
146 return res
147 }
148
149 // Dump a response, excluding the body, no error checking
150 func dump(resp *http.Response) string {
151 dump, _ := httputil.DumpResponse(resp, false)
152 return string(dump)
153 }
154
155 // Return the following error:
156 // dial tcp 127.0.0.1:6379: connect: connection refused
157 func connectionRefusedError() error {
158 ip := net.ParseIP("127.0.0.1")
159 tcpAddr := &net.TCPAddr{IP: ip, Port: 6379}
160 var addr net.Addr = tcpAddr
161 syscallErr := os.NewSyscallError("connect", syscall.ECONNREFUSED)
162 return &net.OpError{Op: "dial", Net: "tcp", Addr: addr, Err: syscallErr}
163 }
164
165 // Return the following error:
166 // LOADING Redis is loading the dataset in memory
167 func redisIsLoadingError() error {
168 return errors.New("LOADING Redis is loading the dataset in memory")
169 }
170
171 // A pair consisting of a redis command, and its expected result
172 type mockedCmd struct {
173 Cmd []string
174 Res any
175 }
176
177 // Register a list of mocked redis commands
178 func mockCommands(mock *redigomock.Conn, commands []mockedCmd) {
179 for _, item := range commands {
180 // Craft arguments for mock.Command, then mock
181 args := []any{}
182 for _, arg := range item.Cmd[1:] {
183 args = append(args, arg)
184 }
185 cmd := mock.Command(item.Cmd[0], args...)
186
187 // Add an expectation
188 switch item.Res.(type) {
189 case error:
190 cmd.ExpectError(item.Res.(error))
191 case []string:
192 cmd.ExpectStringSlice(item.Res.([]string)...)
193 case map[string]string:
194 cmd.ExpectMap(item.Res.(map[string]string))
195 default:
196 // unknown type? that's a programming error
197
198 }
199 }
200 }
201
202 // Wrapper around redigomock.ExpectationsWereMet() to return a slice of errors
203 func getMockErrors(mock *redigomock.Conn) (result []error) {
204 err := mock.ExpectationsWereMet()
205 if err != nil {
206 lines := strings.Split(err.Error(), "\n")
207 for _, line := range lines {
208 line := strings.TrimSpace(line)
209 if line == "" {
210 continue
211 }
212 // A PING command might or might not have been sent during
213 // the tests (due to `ConnectPubsub()` I believe). Since we
214 // don't mock it, we must filter it out from the errors.
215 if strings.HasPrefix(line, "command PING ") &&
216 strings.HasSuffix(line, " not registered in redigomock library") {
217 continue
218 }
219 result = append(result, errors.New(line))
220 }
221 }
222 return
223 }
224
225 // Context for a test
226 type testContext struct {
227 TestDir string
228 RepoDir string
229 MockedConn *redigomock.Conn
230 MirrorCache *mirrors.Cache
231 Server *HTTP
232 }
233
234 // Prepare a test, return the context
235 func prepareTest(t *testing.T, filenames []string) (testContext, error) {
236 // Create a temporary directory for test data
237 testDir := t.TempDir()
238
239 // Create the repo directory, along with dummy files
240 repoDir := testDir + "/repo"
241 err := os.Mkdir(repoDir, 0755)
242 if err != nil {
243 return testContext{}, err
244 }
245
246 for _, f := range filenames {
247 err = makeEmptyFile(repoDir, f)
248 if err != nil {
249 return testContext{}, err
250 }
251 }
252
253 // Create the templates directory, along with dummy templates
254 templatesDir := testDir + "/templates"
255 err = os.Mkdir(templatesDir, 0755)
256 if err != nil {
257 return testContext{}, err
258 }
259
260 templates := []string{"base.html", "mirrorlist.html", "mirrorstats.html"}
261 for _, f := range templates {
262 err = makeEmptyFile(templatesDir, f)
263 if err != nil {
264 return testContext{}, err
265 }
266 }
267
268 // Set mirrorbits configuration
269 SetConfiguration(&Configuration{
270 Repository: repoDir,
271 Templates: templatesDir,
272 OutputMode: "redirect",
273 MaxLinkHeaders: 5,
274 Fallbacks: []Fallback{
275 {URL: fallbackURL},
276 },
277 })
278
279 // Reset the default server before each test. Must be done before
280 // creating a HTTPServer instance, otherwise we run into:
281 //
282 // panic: http: multiple registrations for /
283 //
284 // Cf. https://stackoverflow.com/a/40790728/
285 http.DefaultServeMux = new(http.ServeMux)
286
287 // Setup HTTP server
288 mock, conn := PrepareRedisTest()
289 conn.ConnectPubsub()
290 cache := mirrors.NewCache(conn)
291 h := HTTPServer(conn, cache)
292
293 // Ready for testing!
294 return testContext {
295 TestDir: testDir,
296 RepoDir: repoDir,
297 MockedConn: mock,
298 MirrorCache: cache,
299 Server: h,
300 }, nil
301 }
302
303 // Test 4xx return codes from MirrorHandler.
304 //
305 // Those HTTP codes are triggered when the file requested doesn't even exist in
306 // the local repo. Mirrorbits doesn't query the database in those cases, so
307 // there's no need to mock redis commands.
308 func TestMirrorHandler4xx(t *testing.T) {
309 // Prepare
310 ctx, err := prepareTest(t, []string{})
311 if err != nil {
312 t.Fatal(err)
313 }
314
315 noHeader := map[string]string{}
316
317 // Request a file that doesn't exist on the local repo
318 // -> return 404 "Not Found"
319 resp := doRequest(ctx.Server, "GET", "/foobar", noHeader)
320 want := makeResponse(404, noHeader)
321 if !respEqual(want, resp) {
322 t.Fatalf("Expected: %v, got: %v", want, resp)
323 }
324
325 // Request a file outside of the local repo
326 // -> return 403 "Forbidden"
327 resp = doRequest(ctx.Server, "GET", "/../foobar", noHeader)
328 want = makeResponse(403, noHeader)
329 if !respEqual(want, resp) {
330 t.Fatalf("Expected: %v, got: %v", want, resp)
331 }
332
333 // Request a file while the repo directory doesn't even exist
334 // -> return 404 "Not Found"
335 if err = os.Remove(ctx.RepoDir); err != nil {
336 t.Fatal(err)
337 }
338 resp = doRequest(ctx.Server, "GET", "/foobar", noHeader)
339 want = makeResponse(404, noHeader)
340 if !respEqual(want, resp) {
341 t.Fatalf("Expected: %v, got: %v", want, resp)
342 }
343 }
344
345 var mockedCmds302Fallback = [][]mockedCmd{
346 // Database is unreachable (redis error "connection refused")
347 {
348 {
349 Cmd: []string{"HMGET", "FILE_"+testFile, "size", "modTime", "sha1", "sha256", "md5"},
350 Res: connectionRefusedError(),
351 },
352 },
353 // Database is loading
354 {
355 {
356 Cmd: []string{"HMGET", "FILE_"+testFile, "size", "modTime", "sha1", "sha256", "md5"},
357 Res: redisIsLoadingError(),
358 },
359 },
360 // Database is reachable. File exists in the local repo, but is not
361 // found in the database (in real-life, it means that the local repo
362 // was updated with new files, but mirrorbits didn't rescan it yet)
363 {
364 {
365 Cmd: []string{"HMGET", "FILE_"+testFile, "size", "modTime", "sha1", "sha256", "md5"},
366 Res: []string{"", "", "", "", "", ""},
367 },
368 },
369 // Database is reachable, file exists in the local repo, and is also
370 // present in the database, however no mirror have this file yet
371 {
372 {
373 Cmd: []string{"HMGET", "FILE_"+testFile, "size", "modTime", "sha1", "sha256", "md5"},
374 Res: []string{testFileSize, testFileModTime, "", testFileSha256, ""},
375 },
376 {
377 Cmd: []string{"SMEMBERS", "FILEMIRRORS_"+testFile},
378 Res: []string{},
379 },
380 },
381 }
382
383 var mockedCmds302Mirror = [][]mockedCmd{
384 // Database is reachable, file exists in the local repo, is also
385 // present in the database, and is found on a mirror.
386 //
387 // Note: At startup, mirrorbits says "Can't load the GeoIP databases,
388 // all requests will be served by the fallback mirrors". Well it
389 // doesn't seem to be true, as this test case shows.
390 {
391 {
392 Cmd: []string{"HMGET", "FILE_"+testFile, "size", "modTime", "sha1", "sha256", "md5"},
393 Res: []string{testFileSize, testFileModTime, "", testFileSha256, ""},
394 },
395 {
396 Cmd: []string{"SMEMBERS", "FILEMIRRORS_"+testFile},
397 Res: []string{"42"},
398 },
399 {
400 Cmd: []string{"HGETALL", "MIRROR_42"},
401 Res: map[string]string{
402 "ID": "42",
403 "http": mirrorURL,
404 "enabled": "true",
405 "httpUp": "true",
406 },
407 },
408 {
409 Cmd: []string{"HMGET", "FILEINFO_42_"+testFile, "size", "modTime", "sha1", "sha256", "md5"},
410 Res: []string{testFileSize, testFileModTime, "", "", ""},
411 },
412 },
413 }
414
415 var mockedCmds304 = [][]mockedCmd{
416 // File exists in the database, and is older than the If-Modified-Since
417 // request header, so mirrorbits returns early and doesn't even check
418 // if mirrors have the file.
419 {
420 {
421 Cmd: []string{"HMGET", "FILE_"+testFile, "size", "modTime", "sha1", "sha256", "md5"},
422 Res: []string{testFileSize, testFileModTime, "", testFileSha256, ""},
423 },
424 },
425 }
426
427 // Test 3xx status codes.
428 //
429 // Mocking redis can be tricky. If we forget to mock a command, we'll get an
430 // error of the type:
431 //
432 // command [...] not registered in redigomock library
433 //
434 // However a redis error makes mirrorbits bail out early from mirror selection,
435 // and in turns it triggers a fallback redirection. So from the outside, all we
436 // know is that yes, mirrorbits returned a fallback redirect, and maybe that's
437 // what we expect, so the test pass, but in fact it passed _because_ we forgot
438 // to mock a redis command!
439 //
440 // That's why it's not enough to just check if mocked commands were called, we
441 // also need to make sure that redigomock didn't return any error that were
442 // unexpected.
443 func TestMirrorHandler3xx(t *testing.T) {
444 // Prepare
445 ctx, err := prepareTest(t, []string{testFile})
446 if err != nil {
447 t.Fatal(err)
448 }
449
450 // Define tests
451 tests := map[string]struct {
452 MockedCommands [][]mockedCmd
453 RequestHeaders map[string]string
454 Response *http.Response
455 } {
456 // Test various scenarios that lead to a fallback redirection
457 "fallback_redirect": {
458 MockedCommands: mockedCmds302Fallback,
459 Response: makeResponse(302, map[string]string{
460 "Location": urlJoinPath(fallbackURL, testFile),
461 }),
462 },
463 // Same as above, but this time passing a If-Modified-Since
464 // header, set to an old date, so no consequence on the result
465 "fallback_redirect_old_if_modified_since": {
466 MockedCommands: mockedCmds302Fallback,
467 RequestHeaders: map[string]string{
468 "If-Modified-Since": "Tue, 01 Jun 1999 00:00:00 GMT",
469 },
470 Response: makeResponse(302, map[string]string{
471 "Location": urlJoinPath(fallbackURL, testFile),
472 }),
473 },
474 // Test mirror redirection
475 "mirror_redirect": {
476 MockedCommands: mockedCmds302Mirror,
477 Response: makeResponse(302, map[string]string{
478 "Location": urlJoinPath(mirrorURL, testFile),
479 }),
480 },
481 // Same as above, but with a old If-Modified-Since
482 "mirror_redirect_old_if_modified_since": {
483 MockedCommands: mockedCmds302Mirror,
484 RequestHeaders: map[string]string{
485 "If-Modified-Since": "Tue, 01 Jun 1999 00:00:00 GMT",
486 },
487 Response: makeResponse(302, map[string]string{
488 "Location": urlJoinPath(mirrorURL, testFile),
489 }),
490 },
491 // Test "304 Not Modified" by setting a If-Modified-Since header
492 // that is newer that the test file modification time
493 "not_modified": {
494 MockedCommands: mockedCmds304,
495 RequestHeaders: map[string]string{
496 "If-Modified-Since": "Wed, 04 Jun 2025 02:12:35 GMT",
497 },
498 Response: makeResponse(304, map[string]string{
499 "Last-Modified": testFileLastModified,
500 }),
501 },
502 }
503
504 // Run tests
505 for name, tt := range tests {
506 t.Run(name, func(t *testing.T) {
507 for i, commands := range tt.MockedCommands {
508 // Register mocked commands
509 mockCommands(ctx.MockedConn, commands)
510
511 // Request the file
512 resp := doRequest(ctx.Server, "GET", testFile, tt.RequestHeaders)
513
514 // Check that mocking went fine
515 for _, err := range getMockErrors(ctx.MockedConn) {
516 t.Errorf("#%d: %s", i, err)
517 }
518
519 // Check that response is as expected
520 if !respEqual(tt.Response, resp) {
521 //t.Errorf("#%d: Expected: %v, got: %v", i, tt.Response, resp)
522 t.Errorf("#%d: Expected:\n%sGot:\n%s", i, dump(tt.Response), dump(resp))
523 }
524
525 // Cleanup
526 ctx.MockedConn.Clear()
527 ctx.MirrorCache.Clear()
528 }
529 })
530 }
531 }