Skip to content

Commit

Permalink
Add check to ensure Range is less than content (#266)
Browse files Browse the repository at this point in the history
* Add check to ensure Range is less than content

* This fixes the case where a Range value greater than the length of the
  content is requested, causing the server to crash and fail the
  request.

* Add tests for Range handler
  • Loading branch information
gjabell authored Jun 8, 2020
1 parent 727ddee commit 3ef921c
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
3 changes: 3 additions & 0 deletions fakestorage/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,9 @@ func (s *Server) handleRange(obj Object, r *http.Request) (start, end int, conte
} else {
end++
}
if end > len(obj.Content) {
end = len(obj.Content)
}
return start, end, obj.Content[start:end]
}
}
Expand Down
43 changes: 43 additions & 0 deletions fakestorage/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ func TestDownloadObject(t *testing.T) {
{BucketName: "other-bucket", Name: "static/css/website.css", Content: []byte("body {display: none;}")},
}
runServersTest(t, objs, testDownloadObject)
runServersTest(t, objs, testDownloadObjectRange)
}

func testDownloadObject(t *testing.T, server *Server) {
Expand Down Expand Up @@ -168,6 +169,48 @@ func testDownloadObject(t *testing.T, server *Server) {
}
}

func testDownloadObjectRange(t *testing.T, server *Server) {
tests := []struct {
name string
headers map[string]string
expectedStatus int
expectedBody string
}{
{"No range specified", map[string]string{}, http.StatusOK, "something"},
{"Partial range specified", map[string]string{"Range": "bytes=1-4"}, http.StatusPartialContent, "omet"},
{"Exact range specified", map[string]string{"Range": "bytes=0-8"}, http.StatusOK, "something"},
{"Too-long range specified", map[string]string{"Range": "bytes=0-100"}, http.StatusOK, "something"},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
client := server.HTTPClient()
req, err := http.NewRequest("GET", "https://storage.googleapis.com/some-bucket/files/txt/text-01.txt", nil)
if err != nil {
t.Fatal(err)
}
for header, value := range test.headers {
req.Header.Add(header, value)
}
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != test.expectedStatus {
t.Errorf("wrong status returned\nwant %d\ngot %d", test.expectedStatus, resp.StatusCode)
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if body := string(data); body != test.expectedBody {
t.Errorf("wrong body\nwant %q\ngot %q", test.expectedBody, body)
}
})
}
}

func TestDownloadObjectAlternatePublicHost(t *testing.T) {
tests := []struct {
name string
Expand Down

0 comments on commit 3ef921c

Please sign in to comment.