Skip to content

Commit b574b57

Browse files
acudkaralabe
authored andcommitted
swarm: give correct error on 0x hash prefix (#16195)
- added a case error struct that contains information about certain error cases in which we would like to output more information to the client - added a validation method that iterates and adds the information that is stored in the error cases
1 parent 18bb3da commit b574b57

5 files changed

Lines changed: 98 additions & 21 deletions

File tree

‎.gitignore‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ profile.cov
3434
# IdeaIDE
3535
.idea
3636

37+
# VS Code
38+
.vscode
39+
3740
# dashboard
3841
/dashboard/assets/flow-typed
3942
/dashboard/assets/node_modules

‎swarm/api/http/error.go‎

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import (
3535

3636
//templateMap holds a mapping of an HTTP error code to a template
3737
var templateMap map[int]*template.Template
38+
var caseErrors []CaseError
3839

3940
//metrics variables
4041
var (
@@ -51,6 +52,13 @@ type ErrorParams struct {
5152
Details template.HTML
5253
}
5354

55+
//a custom error case struct that would be used to store validators and
56+
//additional error info to display with client responses.
57+
type CaseError struct {
58+
Validator func(*Request) bool
59+
Msg func(*Request) string
60+
}
61+
5462
//we init the error handling right on boot time, so lookup and http response is fast
5563
func init() {
5664
initErrHandling()
@@ -74,6 +82,29 @@ func initErrHandling() {
7482
//assign formatted HTML to the code
7583
templateMap[code] = template.Must(template.New(fmt.Sprintf("%d", code)).Parse(tname))
7684
}
85+
86+
caseErrors = []CaseError{
87+
{
88+
Validator: func(r *Request) bool { return r.uri != nil && r.uri.Addr != "" && strings.HasPrefix(r.uri.Addr, "0x") },
89+
Msg: func(r *Request) string {
90+
uriCopy := r.uri
91+
uriCopy.Addr = strings.TrimPrefix(uriCopy.Addr, "0x")
92+
return fmt.Sprintf(`The requested hash seems to be prefixed with '0x'. You will be redirected to the correct URL within 5 seconds.<br/>
93+
Please click <a href='%[1]s'>here</a> if your browser does not redirect you.<script>setTimeout("location.href='%[1]s';",5000);</script>`, "/"+uriCopy.String())
94+
},
95+
}}
96+
}
97+
98+
//ValidateCaseErrors is a method that process the request object through certain validators
99+
//that assert if certain conditions are met for further information to log as an error
100+
func ValidateCaseErrors(r *Request) string {
101+
for _, err := range caseErrors {
102+
if err.Validator(r) {
103+
return err.Msg(r)
104+
}
105+
}
106+
107+
return ""
77108
}
78109

79110
//ShowMultipeChoices is used when a user requests a resource in a manifest which results
@@ -82,10 +113,10 @@ func initErrHandling() {
82113
//For example, if the user requests bzz:/<hash>/read and that manifest contains entries
83114
//"readme.md" and "readinglist.txt", a HTML page is returned with this two links.
84115
//This only applies if the manifest has no default entry
85-
func ShowMultipleChoices(w http.ResponseWriter, r *http.Request, list api.ManifestList) {
116+
func ShowMultipleChoices(w http.ResponseWriter, r *Request, list api.ManifestList) {
86117
msg := ""
87118
if list.Entries == nil {
88-
ShowError(w, r, "Internal Server Error", http.StatusInternalServerError)
119+
ShowError(w, r, "Could not resolve", http.StatusInternalServerError)
89120
return
90121
}
91122
//make links relative
@@ -102,7 +133,7 @@ func ShowMultipleChoices(w http.ResponseWriter, r *http.Request, list api.Manife
102133
//create clickable link for each entry
103134
msg += "<a href='" + base + e.Path + "'>" + e.Path + "</a><br/>"
104135
}
105-
respond(w, r, &ErrorParams{
136+
respond(w, &r.Request, &ErrorParams{
106137
Code: http.StatusMultipleChoices,
107138
Details: template.HTML(msg),
108139
Timestamp: time.Now().Format(time.RFC1123),
@@ -115,13 +146,15 @@ func ShowMultipleChoices(w http.ResponseWriter, r *http.Request, list api.Manife
115146
//The function just takes a string message which will be displayed in the error page.
116147
//The code is used to evaluate which template will be displayed
117148
//(and return the correct HTTP status code)
118-
func ShowError(w http.ResponseWriter, r *http.Request, msg string, code int) {
149+
func ShowError(w http.ResponseWriter, r *Request, msg string, code int) {
150+
additionalMessage := ValidateCaseErrors(r)
119151
if code == http.StatusInternalServerError {
120152
log.Error(msg)
121153
}
122-
respond(w, r, &ErrorParams{
154+
respond(w, &r.Request, &ErrorParams{
123155
Code: code,
124156
Msg: msg,
157+
Details: template.HTML(additionalMessage),
125158
Timestamp: time.Now().Format(time.RFC1123),
126159
template: getTemplate(code),
127160
})

‎swarm/api/http/error_templates.go‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,11 @@ func GetGenericErrorPage() string {
168168
{{.Msg}}
169169
</td>
170170
</tr>
171+
<tr>
172+
<td class="value">
173+
{{.Details}}
174+
</td>
175+
</tr>
171176
172177
<tr>
173178
<td class="key">
@@ -342,6 +347,12 @@ func GetNotFoundErrorPage() string {
342347
{{.Msg}}
343348
</td>
344349
</tr>
350+
<tr>
351+
<td class="value">
352+
{{.Details}}
353+
</td>
354+
</tr>
355+
345356
346357
<tr>
347358
<td class="key">

‎swarm/api/http/error_test.go‎

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,13 @@ package http_test
1818

1919
import (
2020
"encoding/json"
21-
"golang.org/x/net/html"
2221
"io/ioutil"
2322
"net/http"
2423
"strings"
2524
"testing"
2625

26+
"golang.org/x/net/html"
27+
2728
"github.com/ethereum/go-ethereum/swarm/testutil"
2829
)
2930

@@ -96,8 +97,37 @@ func Test500Page(t *testing.T) {
9697
defer resp.Body.Close()
9798
respbody, err = ioutil.ReadAll(resp.Body)
9899

99-
if resp.StatusCode != 500 || !strings.Contains(string(respbody), "500") {
100-
t.Fatalf("Invalid Status Code received, expected 500, got %d", resp.StatusCode)
100+
if resp.StatusCode != 404 {
101+
t.Fatalf("Invalid Status Code received, expected 404, got %d", resp.StatusCode)
102+
}
103+
104+
_, err = html.Parse(strings.NewReader(string(respbody)))
105+
if err != nil {
106+
t.Fatalf("HTML validation failed for error page returned!")
107+
}
108+
}
109+
func Test500PageWith0xHashPrefix(t *testing.T) {
110+
srv := testutil.NewTestSwarmServer(t)
111+
defer srv.Close()
112+
113+
var resp *http.Response
114+
var respbody []byte
115+
116+
url := srv.URL + "/bzz:/0xthisShouldFailWith500CodeAndAHelpfulMessage"
117+
resp, err := http.Get(url)
118+
119+
if err != nil {
120+
t.Fatalf("Request failed: %v", err)
121+
}
122+
defer resp.Body.Close()
123+
respbody, err = ioutil.ReadAll(resp.Body)
124+
125+
if resp.StatusCode != 404 {
126+
t.Fatalf("Invalid Status Code received, expected 404, got %d", resp.StatusCode)
127+
}
128+
129+
if !strings.Contains(string(respbody), "The requested hash seems to be prefixed with") {
130+
t.Fatalf("Did not receive the expected error message")
101131
}
102132

103133
_, err = html.Parse(strings.NewReader(string(respbody)))
@@ -127,8 +157,8 @@ func TestJsonResponse(t *testing.T) {
127157
defer resp.Body.Close()
128158
respbody, err = ioutil.ReadAll(resp.Body)
129159

130-
if resp.StatusCode != 500 {
131-
t.Fatalf("Invalid Status Code received, expected 500, got %d", resp.StatusCode)
160+
if resp.StatusCode != 404 {
161+
t.Fatalf("Invalid Status Code received, expected 404, got %d", resp.StatusCode)
132162
}
133163

134164
if !isJSON(string(respbody)) {

‎swarm/api/http/server.go‎

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,7 @@ func (s *Server) HandleGet(w http.ResponseWriter, r *Request) {
336336
key, err := s.api.Resolve(r.uri)
337337
if err != nil {
338338
getFail.Inc(1)
339-
s.Error(w, r, fmt.Errorf("error resolving %s: %s", r.uri.Addr, err))
339+
s.NotFound(w, r, fmt.Errorf("error resolving %s: %s", r.uri.Addr, err))
340340
return
341341
}
342342

@@ -421,7 +421,7 @@ func (s *Server) HandleGetFiles(w http.ResponseWriter, r *Request) {
421421
key, err := s.api.Resolve(r.uri)
422422
if err != nil {
423423
getFilesFail.Inc(1)
424-
s.Error(w, r, fmt.Errorf("error resolving %s: %s", r.uri.Addr, err))
424+
s.NotFound(w, r, fmt.Errorf("error resolving %s: %s", r.uri.Addr, err))
425425
return
426426
}
427427

@@ -494,7 +494,7 @@ func (s *Server) HandleGetList(w http.ResponseWriter, r *Request) {
494494
key, err := s.api.Resolve(r.uri)
495495
if err != nil {
496496
getListFail.Inc(1)
497-
s.Error(w, r, fmt.Errorf("error resolving %s: %s", r.uri.Addr, err))
497+
s.NotFound(w, r, fmt.Errorf("error resolving %s: %s", r.uri.Addr, err))
498498
return
499499
}
500500

@@ -598,7 +598,7 @@ func (s *Server) HandleGetFile(w http.ResponseWriter, r *Request) {
598598
key, err := s.api.Resolve(r.uri)
599599
if err != nil {
600600
getFileFail.Inc(1)
601-
s.Error(w, r, fmt.Errorf("error resolving %s: %s", r.uri.Addr, err))
601+
s.NotFound(w, r, fmt.Errorf("error resolving %s: %s", r.uri.Addr, err))
602602
return
603603
}
604604

@@ -628,7 +628,7 @@ func (s *Server) HandleGetFile(w http.ResponseWriter, r *Request) {
628628

629629
s.logDebug(fmt.Sprintf("Multiple choices! --> %v", list))
630630
//show a nice page links to available entries
631-
ShowMultipleChoices(w, &r.Request, list)
631+
ShowMultipleChoices(w, r, list)
632632
return
633633
}
634634

@@ -693,15 +693,15 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
693693
// strictly a traditional PUT request which replaces content
694694
// at a URI, and POST is more ubiquitous)
695695
if uri.Raw() || uri.DeprecatedRaw() {
696-
ShowError(w, r, fmt.Sprintf("No PUT to %s allowed.", uri), http.StatusBadRequest)
696+
ShowError(w, req, fmt.Sprintf("No PUT to %s allowed.", uri), http.StatusBadRequest)
697697
return
698698
} else {
699699
s.HandlePostFiles(w, req)
700700
}
701701

702702
case "DELETE":
703703
if uri.Raw() || uri.DeprecatedRaw() {
704-
ShowError(w, r, fmt.Sprintf("No DELETE to %s allowed.", uri), http.StatusBadRequest)
704+
ShowError(w, req, fmt.Sprintf("No DELETE to %s allowed.", uri), http.StatusBadRequest)
705705
return
706706
}
707707
s.HandleDelete(w, req)
@@ -725,7 +725,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
725725
s.HandleGetFile(w, req)
726726

727727
default:
728-
ShowError(w, r, fmt.Sprintf("Method "+r.Method+" is not supported.", uri), http.StatusMethodNotAllowed)
728+
ShowError(w, req, fmt.Sprintf("Method "+r.Method+" is not supported.", uri), http.StatusMethodNotAllowed)
729729

730730
}
731731
}
@@ -757,13 +757,13 @@ func (s *Server) logError(format string, v ...interface{}) {
757757
}
758758

759759
func (s *Server) BadRequest(w http.ResponseWriter, r *Request, reason string) {
760-
ShowError(w, &r.Request, fmt.Sprintf("Bad request %s %s: %s", r.Method, r.uri, reason), http.StatusBadRequest)
760+
ShowError(w, r, fmt.Sprintf("Bad request %s %s: %s", r.Request.Method, r.uri, reason), http.StatusBadRequest)
761761
}
762762

763763
func (s *Server) Error(w http.ResponseWriter, r *Request, err error) {
764-
ShowError(w, &r.Request, fmt.Sprintf("Error serving %s %s: %s", r.Method, r.uri, err), http.StatusInternalServerError)
764+
ShowError(w, r, fmt.Sprintf("Error serving %s %s: %s", r.Request.Method, r.uri, err), http.StatusInternalServerError)
765765
}
766766

767767
func (s *Server) NotFound(w http.ResponseWriter, r *Request, err error) {
768-
ShowError(w, &r.Request, fmt.Sprintf("NOT FOUND error serving %s %s: %s", r.Method, r.uri, err), http.StatusNotFound)
768+
ShowError(w, r, fmt.Sprintf("NOT FOUND error serving %s %s: %s", r.Request.Method, r.uri, err), http.StatusNotFound)
769769
}

0 commit comments

Comments
 (0)