Skip to content

Commit

Permalink
fix(update-checksum): copy an asset to a temporal file to calculate t…
Browse files Browse the repository at this point in the history
…he checksum correctly (#2469)

* fix(update-checksum): copy an asset to a temporal file to calculate the checksum correctly

Fixed a bug that the calculated checksum is wrong.

- #2467

* fix: close a file
  • Loading branch information
suzuki-shunsuke authored Nov 15, 2023
1 parent c1a4a5c commit b0328c0
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions pkg/controller/updatechecksum/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/aquaproj/aqua/v2/pkg/download"
"github.com/aquaproj/aqua/v2/pkg/runtime"
"github.com/sirupsen/logrus"
"github.com/spf13/afero"
"github.com/suzuki-shunsuke/logrus-error/logerr"
)

Expand Down Expand Up @@ -291,7 +292,7 @@ func (c *Controller) getChecksum(ctx context.Context, logE *logrus.Entry, checks
return nil
}

func (c *Controller) dlAssetAndGetChecksum(ctx context.Context, logE *logrus.Entry, checksums *checksum.Checksums, pkg *config.Package, rt *runtime.Runtime) (gErr error) {
func (c *Controller) dlAssetAndGetChecksum(ctx context.Context, logE *logrus.Entry, checksums *checksum.Checksums, pkg *config.Package, rt *runtime.Runtime) (gErr error) { //nolint:cyclop
checksumID, err := pkg.ChecksumID(rt)
if err != nil {
return fmt.Errorf("get a checksum id: %w", err)
Expand Down Expand Up @@ -322,9 +323,27 @@ func (c *Controller) dlAssetAndGetChecksum(ctx context.Context, logE *logrus.Ent
return fmt.Errorf("download an asset: %w", err)
}
defer file.Close()

// Download a file to a temporal file.
// https://github.com/aquaproj/aqua/issues/2467
tempFilePath, err := copyToTempFile(c.fs, file)
if err != nil {
return fmt.Errorf("copy an asset to a temporal file: %w", err)
}
defer func() {
if err := c.fs.Remove(tempFilePath); err != nil {
logE.WithError(err).Warn("remove a temporal file")
}
}()
tempFile, err := c.fs.Open(tempFilePath)
if err != nil {
return fmt.Errorf("open a temporal file to calculate the checksum: %w", err)
}
defer tempFile.Close()

algorithm := "sha256"
fields["algorithm"] = algorithm
chk, err := checksum.CalculateReader(file, algorithm)
chk, err := checksum.CalculateReader(tempFile, algorithm)
if err != nil {
return fmt.Errorf("calculate an asset: %w", err)
}
Expand All @@ -335,3 +354,15 @@ func (c *Controller) dlAssetAndGetChecksum(ctx context.Context, logE *logrus.Ent
})
return nil
}

func copyToTempFile(fs afero.Fs, file io.Reader) (string, error) {
tempFile, err := afero.TempFile(fs, "", "")
if err != nil {
return "", fmt.Errorf("create a temporal file: %w", err)
}
if _, err := io.Copy(tempFile, file); err != nil {
return "", fmt.Errorf("download an asset to a temporal file: %w", err)
}
tempFile.Close()
return tempFile.Name(), nil
}

0 comments on commit b0328c0

Please sign in to comment.