Skip to content

Commit 0ab98b3

Browse files
authored
Fixed an issue causing Jar decompression to fail when downloaded using chunked encoding (#124)
1 parent 3320fcf commit 0ab98b3

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

remote_fetch.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,14 @@ func closeBody(resp *http.Response) func() {
7575
}
7676

7777
func decompressResponse(bodyBytes []byte, contentLength int64, cacheLocator CacheLocator, downloadURL string) error {
78-
zipReader, err := zip.NewReader(bytes.NewReader(bodyBytes), contentLength)
78+
size := contentLength
79+
// if the content length is not set (i.e. chunked encoding),
80+
// we need to use the length of the bodyBytes otherwise
81+
// the unzip operation will fail
82+
if contentLength < 0 {
83+
size = int64(len(bodyBytes))
84+
}
85+
zipReader, err := zip.NewReader(bytes.NewReader(bodyBytes), size)
7986
if err != nil {
8087
return errorFetchingPostgres(err)
8188
}

remote_fetch_test.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import (
44
"archive/zip"
55
"crypto/sha256"
66
"encoding/hex"
7+
"github.com/stretchr/testify/require"
8+
"io"
79
"net/http"
810
"net/http/httptest"
911
"os"
@@ -370,3 +372,48 @@ func Test_defaultRemoteFetchStrategyWithExistingDownload(t *testing.T) {
370372
out2, err := os.ReadFile(cacheLocation)
371373
assert.Equal(t, out1, out2)
372374
}
375+
376+
func Test_defaultRemoteFetchStrategy_whenContentLengthNotSet(t *testing.T) {
377+
jarFile, cleanUp := createTempZipArchive()
378+
defer cleanUp()
379+
380+
cacheLocation := filepath.Join(filepath.Dir(jarFile), "extract_location", "cache.jar")
381+
382+
bytes, err := os.ReadFile(jarFile)
383+
if err != nil {
384+
require.NoError(t, err)
385+
}
386+
contentHash := sha256.Sum256(bytes)
387+
388+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
389+
if strings.HasSuffix(r.RequestURI, ".sha256") {
390+
w.WriteHeader(200)
391+
if _, err := w.Write([]byte(hex.EncodeToString(contentHash[:]))); err != nil {
392+
panic(err)
393+
}
394+
395+
return
396+
}
397+
398+
f, err := os.Open(jarFile)
399+
if err != nil {
400+
panic(err)
401+
}
402+
403+
// stream the file back so that Go uses
404+
// chunked encoding and never sets Content-Length
405+
_, _ = io.Copy(w, f)
406+
}))
407+
defer server.Close()
408+
409+
remoteFetchStrategy := defaultRemoteFetchStrategy(server.URL+"/maven2",
410+
testVersionStrategy(),
411+
func() (s string, b bool) {
412+
return cacheLocation, false
413+
})
414+
415+
err = remoteFetchStrategy()
416+
417+
assert.NoError(t, err)
418+
assert.FileExists(t, cacheLocation)
419+
}

0 commit comments

Comments
 (0)