| 1 | package cli |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "net/http/httptest" |
| 6 | "os/exec" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/ipfs/boxo/routing/http/server" |
| 11 | "github.com/ipfs/go-test/random" |
| 12 | "github.com/ipfs/kubo/config" |
| 13 | "github.com/ipfs/kubo/test/cli/harness" |
| 14 | "github.com/ipfs/kubo/test/cli/testutils/httprouting" |
| 15 | "github.com/stretchr/testify/assert" |
| 16 | ) |
| 17 | |
| 18 | // userAgentRecorder records the user agent of every HTTP request |
| 19 | type userAgentRecorder struct { |
| 20 | delegate http.Handler |
| 21 | userAgents []string |
| 22 | } |
| 23 | |
| 24 | func (r *userAgentRecorder) ServeHTTP(w http.ResponseWriter, req *http.Request) { |
| 25 | r.userAgents = append(r.userAgents, req.UserAgent()) |
| 26 | r.delegate.ServeHTTP(w, req) |
| 27 | } |
| 28 | |
| 29 | func TestContentRoutingHTTP(t *testing.T) { |
| 30 | mockRouter := &httprouting.MockHTTPContentRouter{} |
| 31 | |
| 32 | // run the content routing HTTP server |
| 33 | userAgentRecorder := &userAgentRecorder{delegate: server.Handler(mockRouter)} |
| 34 | server := httptest.NewServer(userAgentRecorder) |
| 35 | t.Cleanup(func() { server.Close() }) |
| 36 | |
| 37 | // setup the node |
| 38 | node := harness.NewT(t).NewNode().Init() |
| 39 | node.UpdateConfig(func(cfg *config.Config) { |
| 40 | // setup Kubo node to use mocked HTTP Router |
| 41 | cfg.Routing.DelegatedRouters = []string{server.URL} |
| 42 | }) |
| 43 | node.StartDaemon() |
| 44 | |
| 45 | // compute a random CID |
| 46 | randStr := string(random.Bytes(100)) |
| 47 | res := node.PipeStrToIPFS(randStr, "add", "-qn") |
| 48 | wantCIDStr := res.Stdout.Trimmed() |
| 49 | |
| 50 | t.Run("fetching an uncached block results in an HTTP lookup", func(t *testing.T) { |
| 51 | statRes := node.Runner.Run(harness.RunRequest{ |
| 52 | Path: node.IPFSBin, |
| 53 | Args: []string{"block", "stat", wantCIDStr}, |
| 54 | RunFunc: (*exec.Cmd).Start, |
| 55 | }) |
| 56 | defer func() { |
| 57 | if err := statRes.Cmd.Process.Kill(); err != nil { |
| 58 | t.Logf("error killing 'block stat' cmd: %s", err) |
| 59 | } |
| 60 | }() |
| 61 | |
| 62 | // verify the content router was called |
| 63 | assert.Eventually(t, func() bool { |
| 64 | return mockRouter.NumFindProvidersCalls() > 0 |
| 65 | }, time.Minute, 10*time.Millisecond) |
| 66 | |
| 67 | assert.NotEmpty(t, userAgentRecorder.userAgents) |
| 68 | version := node.IPFS("id", "-f", "<aver>").Stdout.Trimmed() |
| 69 | for _, userAgent := range userAgentRecorder.userAgents { |
| 70 | assert.Equal(t, version, userAgent) |
| 71 | } |
| 72 | }) |
| 73 | } |