diff --git a/internal/io/archive.go b/internal/io/archive.go index fa6a902a..553b07da 100644 --- a/internal/io/archive.go +++ b/internal/io/archive.go @@ -2,6 +2,7 @@ package io import ( "encoding/base64" + "fmt" "path" ) @@ -48,7 +49,7 @@ func (arc *Archive) ZipFile(sourcePath string, targetPath string, zippedName str } defer fs.CloseFile(zipFile) zipWriter := zip.NewWriter(zipFile) - defer zip.CloseWriter(zipWriter) + defer zip.CloseWriter(zipWriter) //nolint info, err := fs.StatFile(zipFile) if err != nil { @@ -88,7 +89,11 @@ func (arc *Archive) UnzipFile(sourcePath string, targetPath string) error { } defer arc.zip.CloseReader(r) //nolint - f := r.File[1] //TODO: Change to first file and error-check for multiple once sootwrapper builds only one + if len(r.File) != 1 { + return fmt.Errorf("cannot unzip archive which does not contain exactly one file") + } + + f := r.File[0] outFile, err := arc.fs.Create(targetPath) if err != nil { return err diff --git a/internal/io/archive_test.go b/internal/io/archive_test.go index 9adff9d3..6f6454f8 100644 --- a/internal/io/archive_test.go +++ b/internal/io/archive_test.go @@ -206,7 +206,7 @@ func TestUnzipFileReadFileError(t *testing.T) { func TestUnzipFileCreateError(t *testing.T) { reader := zip.Reader{ - File: []*zip.File{nil, nil}, + File: []*zip.File{nil}, } readCloser := zip.ReadCloser{Reader: reader} //nolint fsMock := ioTestData.FileSystemMock{CreateError: fmt.Errorf("%s", t.Name())} @@ -223,7 +223,7 @@ func TestUnzipFileCreateError(t *testing.T) { func TestUnzipFileOpenError(t *testing.T) { reader := zip.Reader{ - File: []*zip.File{nil, nil}, + File: []*zip.File{nil}, } readCloser := zip.ReadCloser{Reader: reader} //nolint fsMock := ioTestData.FileSystemMock{} @@ -237,10 +237,8 @@ func TestUnzipFileOpenError(t *testing.T) { assert.Error(t, err) assert.Equal(t, err.Error(), t.Name()) } - func TestUnzipFileCopyError(t *testing.T) { r, err := zipStruct.OpenReader("testdata/text.zip") - r.File = append(r.File, r.File[0]) // Hack solution (: assert.NoError(t, err) defer zipStruct.CloseReader(r) //nolint @@ -251,8 +249,26 @@ func TestUnzipFileCopyError(t *testing.T) { fs: fsMock, zip: zipMock, } - fmt.Println(t.Name()) err = a.UnzipFile("", "") assert.Error(t, err) assert.Equal(t, err.Error(), t.Name()) } + +func TestUnzipFileNotSingleFile(t *testing.T) { + reader := zip.Reader{ + File: []*zip.File{nil, nil}, + } + readCloser := zip.ReadCloser{Reader: reader} //nolint + defer zipStruct.CloseReader(&readCloser) //nolint + + fsMock := ioTestData.FileSystemMock{} + zipMock := ioTestData.ZipMock{ReaderCloser: &readCloser} + a := Archive{ + workingDirectory: ".", + fs: fsMock, + zip: zipMock, + } + err := a.UnzipFile("", "") + assert.Error(t, err) + assert.Equal(t, err.Error(), "cannot unzip archive which does not contain exactly one file") +}