Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion fetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ func FetchAndParse(ctx context.Context, repoURL, filename string) (*Parser, erro
return nil, fmt.Errorf("HTTP %d fetching %s", resp.StatusCode, rawURL)
}

body, err := io.ReadAll(resp.Body)
const maxBodySize = 1 << 20
body, err := io.ReadAll(io.LimitReader(resp.Body, maxBodySize))
if err != nil {
return nil, err
}
Expand Down
37 changes: 37 additions & 0 deletions fetch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)

Expand Down Expand Up @@ -98,3 +100,38 @@ func TestFetchAndParse(t *testing.T) {
}
})
}

type roundTripFunc func(*http.Request) (*http.Response, error)

func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}

func TestFetchAndParseLimitsBodySize(t *testing.T) {
const limit = 1 << 20

srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("## [1.0.0] - 2024-01-01\n\n"))
_, _ = w.Write([]byte(strings.Repeat("a", limit*2)))
}))
defer srv.Close()

srvURL, _ := url.Parse(srv.URL)

origTransport := http.DefaultClient.Transport
http.DefaultClient.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) {
req.URL.Scheme = srvURL.Scheme
req.URL.Host = srvURL.Host
return http.DefaultTransport.RoundTrip(req)
})
defer func() { http.DefaultClient.Transport = origTransport }()

parser, err := FetchAndParse(context.Background(), "https://github.com/owner/repo", "CHANGELOG.md")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}

if len(parser.content) > limit {
t.Errorf("body not capped: got %d bytes, want <= %d", len(parser.content), limit)
}
}
Loading