"rsync for cloud storage" - Google Drive, S3, Dropbox, Backblaze B2, One Drive, Swift, Hubic, Wasabi, Google Cloud Storage, Azure Blob, Azure Files, Yandex Files
Go azure-blobazure-blob-storageazure-filesbackblaze-b2cloud-storagedropboxencryptionftpfuse-filesystemgogolanggoogle-cloud-storagegoogle-driveonedriveopenstack-swiftrclones3sftpsyncwebdav
rest: limit the size of HTTP response bodies read into memory
Nick Craig-Wood90e67915c88d
diff --git a/lib/rest/rest.go b/lib/rest/rest.goindex e8c1ec953..4d155d515 100644--- a/lib/rest/rest.go+++ b/lib/rest/rest.go@@ -43,10 +43,24 @@ func NewClient(c *http.Client) *Client {return api}+// ErrBodyTooLarge is returned by ReadBody when the response body is+// bigger than the limit it will read into memory.+var ErrBodyTooLarge = errors.New("response body too large")+// ReadBody reads resp.Body into result, closing the body+//+// It reads at most drainLimit bytes and returns ErrBodyTooLarge if the+// body is bigger than that, so a misbehaving server can't make rclone+// buffer an unbounded response in memory. It is intended for small API+// responses (error bodies, status documents, upload tokens), not for+// file data.func ReadBody(resp *http.Response) (result []byte, err error) {defer fs.CheckClose(resp.Body, &err)- return io.ReadAll(resp.Body)+ result, err = io.ReadAll(io.LimitReader(resp.Body, drainLimit+1))+ if err == nil && len(result) > drainLimit {+ return nil, ErrBodyTooLarge+ }+ return result, err}// defaultErrorHandler doesn't attempt to parse the http body, just@@ -164,6 +178,9 @@ func (o *Opts) Copy() *Opts {return &newOpts}+// drainLimit is the most of a response body that will be consumed+// from the network, whether it is being read by ReadBody or discarded+// by drainAndClose.const drainLimit = 10 * 1024 * 1024// drainAndClose discards up to drainLimit bytes from r and closesdiff --git a/lib/rest/rest_test.go b/lib/rest/rest_test.goindex 39582e649..f95016d81 100644--- a/lib/rest/rest_test.go+++ b/lib/rest/rest_test.go@@ -1,7 +1,9 @@package restimport (+ "bytes""context"+ "io""net/http""net/http/httptest""net/url"@@ -180,3 +182,51 @@ func TestRefuseHTTPSDowngradeRedirectEndToEnd(t *testing.T) {assert.False(t, sawAuth.Load(), "plaintext hop must not receive credentials")})}++// TestReadBodyLimit checks that ReadBody refuses to buffer more than+// drainLimit bytes, so a server streaming an endless response can't+// make rclone allocate memory without bound.+func TestReadBodyLimit(t *testing.T) {+ newResp := func(body io.Reader) *http.Response {+ return &http.Response{Body: io.NopCloser(body)}+ }+ t.Run("AtLimit", func(t *testing.T) {+ want := bytes.Repeat([]byte("x"), drainLimit)+ got, err := ReadBody(newResp(bytes.NewReader(want)))+ require.NoError(t, err)+ assert.Equal(t, want, got)+ })+ t.Run("OverLimit", func(t *testing.T) {+ got, err := ReadBody(newResp(bytes.NewReader(make([]byte, drainLimit+1))))+ assert.ErrorIs(t, err, ErrBodyTooLarge)+ assert.Nil(t, got)+ })++ // A server which answers with an error status and then streams a+ // body far bigger than drainLimit. The default error handler must+ // give up at the limit rather than read it all.+ t.Run("EndlessErrorBody", func(t *testing.T) {+ const chunk = 1 << 20+ const maxChunks = 64 // bounds the test if the client keeps reading+ var written atomic.Int64+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusInternalServerError)+ buf := bytes.Repeat([]byte("x"), chunk)+ for range maxChunks {+ n, err := w.Write(buf)+ written.Add(int64(n))+ if err != nil {+ return+ }+ w.(http.Flusher).Flush()+ }+ }))+ t.Cleanup(srv.Close)++ api := NewClient(srv.Client()).SetRoot(srv.URL)+ _, err := api.Call(context.Background(), &Opts{Method: "GET", Path: "/"})+ require.Error(t, err)+ assert.ErrorIs(t, err, ErrBodyTooLarge)+ assert.Less(t, written.Load(), int64(maxChunks*chunk), "client should stop reading before the server stops sending")+ })+}