github.com/janotchain/janota@v0.0.0-20220824112012-93ea4c5dee78/swarm/api/http/server_test.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package http_test
    18  
    19  import (
    20  	"bytes"
    21  	"errors"
    22  	"fmt"
    23  	"io/ioutil"
    24  	"net/http"
    25  	"strings"
    26  	"sync"
    27  	"testing"
    28  
    29  	"github.com/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/swarm/api"
    31  	swarm "github.com/ethereum/go-ethereum/swarm/api/client"
    32  	"github.com/ethereum/go-ethereum/swarm/storage"
    33  	"github.com/ethereum/go-ethereum/swarm/testutil"
    34  )
    35  
    36  func TestBzzrGetPath(t *testing.T) {
    37  
    38  	var err error
    39  
    40  	testmanifest := []string{
    41  		`{"entries":[{"path":"a/","hash":"674af7073604ebfc0282a4ab21e5ef1a3c22913866879ebc0816f8a89896b2ed","contentType":"application/bzz-manifest+json","status":0}]}`,
    42  		`{"entries":[{"path":"a","hash":"011b4d03dd8c01f1049143cf9c4c817e4b167f1d1b83e5c6f0f10d89ba1e7bce","contentType":"","status":0},{"path":"b/","hash":"0a87b1c3e4bf013686cdf107ec58590f2004610ee58cc2240f26939f691215f5","contentType":"application/bzz-manifest+json","status":0}]}`,
    43  		`{"entries":[{"path":"b","hash":"011b4d03dd8c01f1049143cf9c4c817e4b167f1d1b83e5c6f0f10d89ba1e7bce","contentType":"","status":0},{"path":"c","hash":"011b4d03dd8c01f1049143cf9c4c817e4b167f1d1b83e5c6f0f10d89ba1e7bce","contentType":"","status":0}]}`,
    44  	}
    45  
    46  	testrequests := make(map[string]int)
    47  	testrequests["/"] = 0
    48  	testrequests["/a/"] = 1
    49  	testrequests["/a/b/"] = 2
    50  	testrequests["/x"] = 0
    51  	testrequests[""] = 0
    52  
    53  	expectedfailrequests := []string{"", "/x"}
    54  
    55  	reader := [3]*bytes.Reader{}
    56  
    57  	key := [3]storage.Key{}
    58  
    59  	srv := testutil.NewTestSwarmServer(t)
    60  	defer srv.Close()
    61  
    62  	wg := &sync.WaitGroup{}
    63  
    64  	for i, mf := range testmanifest {
    65  		reader[i] = bytes.NewReader([]byte(mf))
    66  		key[i], err = srv.Dpa.Store(reader[i], int64(len(mf)), wg, nil)
    67  		if err != nil {
    68  			t.Fatal(err)
    69  		}
    70  		wg.Wait()
    71  	}
    72  
    73  	_, err = http.Get(srv.URL + "/bzzr:/" + common.ToHex(key[0])[2:] + "/a")
    74  	if err != nil {
    75  		t.Fatalf("Failed to connect to proxy: %v", err)
    76  	}
    77  
    78  	for k, v := range testrequests {
    79  		var resp *http.Response
    80  		var respbody []byte
    81  
    82  		url := srv.URL + "/bzzr:/"
    83  		if k[:] != "" {
    84  			url += common.ToHex(key[0])[2:] + "/" + k[1:] + "?content_type=text/plain"
    85  		}
    86  		resp, err = http.Get(url)
    87  		if err != nil {
    88  			t.Fatalf("Request failed: %v", err)
    89  		}
    90  		defer resp.Body.Close()
    91  		respbody, err = ioutil.ReadAll(resp.Body)
    92  
    93  		if string(respbody) != testmanifest[v] {
    94  			isexpectedfailrequest := false
    95  
    96  			for _, r := range expectedfailrequests {
    97  				if k[:] == r {
    98  					isexpectedfailrequest = true
    99  				}
   100  			}
   101  			if !isexpectedfailrequest {
   102  				t.Fatalf("Response body does not match, expected: %v, got %v", testmanifest[v], string(respbody))
   103  			}
   104  		}
   105  	}
   106  
   107  	nonhashtests := []string{
   108  		srv.URL + "/bzz:/name",
   109  		srv.URL + "/bzzi:/nonhash",
   110  		srv.URL + "/bzzr:/nonhash",
   111  	}
   112  
   113  	nonhashresponses := []string{
   114  		"error resolving name: no DNS to resolve name: &#34;name&#34;",
   115  		"error resolving nonhash: immutable address not a content hash: &#34;nonhash&#34;",
   116  		"error resolving nonhash: no DNS to resolve name: &#34;nonhash&#34;",
   117  	}
   118  
   119  	for i, url := range nonhashtests {
   120  		var resp *http.Response
   121  		var respbody []byte
   122  
   123  		resp, err = http.Get(url)
   124  
   125  		if err != nil {
   126  			t.Fatalf("Request failed: %v", err)
   127  		}
   128  		defer resp.Body.Close()
   129  		respbody, err = ioutil.ReadAll(resp.Body)
   130  		if err != nil {
   131  			t.Fatalf("ReadAll failed: %v", err)
   132  		}
   133  		if !strings.Contains(string(respbody), nonhashresponses[i]) {
   134  			t.Fatalf("Non-Hash response body does not match, expected: %v, got: %v", nonhashresponses[i], string(respbody))
   135  		}
   136  	}
   137  
   138  }
   139  
   140  // TestBzzRootRedirect tests that getting the root path of a manifest without
   141  // a trailing slash gets redirected to include the trailing slash so that
   142  // relative URLs work as expected.
   143  func TestBzzRootRedirect(t *testing.T) {
   144  	srv := testutil.NewTestSwarmServer(t)
   145  	defer srv.Close()
   146  
   147  	// create a manifest with some data at the root path
   148  	client := swarm.NewClient(srv.URL)
   149  	data := []byte("data")
   150  	file := &swarm.File{
   151  		ReadCloser: ioutil.NopCloser(bytes.NewReader(data)),
   152  		ManifestEntry: api.ManifestEntry{
   153  			Path:        "",
   154  			ContentType: "text/plain",
   155  			Size:        int64(len(data)),
   156  		},
   157  	}
   158  	hash, err := client.Upload(file, "")
   159  	if err != nil {
   160  		t.Fatal(err)
   161  	}
   162  
   163  	// define a CheckRedirect hook which ensures there is only a single
   164  	// redirect to the correct URL
   165  	redirected := false
   166  	httpClient := http.Client{
   167  		CheckRedirect: func(req *http.Request, via []*http.Request) error {
   168  			if redirected {
   169  				return errors.New("too many redirects")
   170  			}
   171  			redirected = true
   172  			expectedPath := "/bzz:/" + hash + "/"
   173  			if req.URL.Path != expectedPath {
   174  				return fmt.Errorf("expected redirect to %q, got %q", expectedPath, req.URL.Path)
   175  			}
   176  			return nil
   177  		},
   178  	}
   179  
   180  	// perform the GET request and assert the response
   181  	res, err := httpClient.Get(srv.URL + "/bzz:/" + hash)
   182  	if err != nil {
   183  		t.Fatal(err)
   184  	}
   185  	defer res.Body.Close()
   186  	if !redirected {
   187  		t.Fatal("expected GET /bzz:/<hash> to redirect to /bzz:/<hash>/ but it didn't")
   188  	}
   189  	gotData, err := ioutil.ReadAll(res.Body)
   190  	if err != nil {
   191  		t.Fatal(err)
   192  	}
   193  	if !bytes.Equal(gotData, data) {
   194  		t.Fatalf("expected response to equal %q, got %q", data, gotData)
   195  	}
   196  }