Skip to content

Commit 71c6673

Browse files
committed
Verify download checksums
1 parent d92a331 commit 71c6673

2 files changed

Lines changed: 42 additions & 1 deletion

File tree

dev-tools/mage/downloads/utils.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,17 @@ import (
99
"io"
1010
"os"
1111
"path/filepath"
12+
"regexp"
1213
"strings"
1314

15+
devtools "github.com/elastic/elastic-agent/dev-tools/mage"
16+
1417
"github.com/cenkalti/backoff/v4"
1518
"github.com/gofrs/uuid/v5"
1619
)
1720

21+
var checksumFileRegex = regexp.MustCompile(`^([0-9a-f]{128})\s+(\w.*)$`)
22+
1823
// downloadRequest struct contains download details ad path and URL
1924
type downloadRequest struct {
2025
URL string
@@ -88,3 +93,32 @@ func downloadFile(downloadRequest *downloadRequest) error {
8893

8994
return nil
9095
}
96+
97+
// verifyChecksum verifies a checksum file, with the content generated by the sha512sum program.
98+
// The format is the hex encoded checksum, followed by a space, and then the filename.
99+
// It is assumed that the files are in the same directory.
100+
func verifyChecksum(checksumFile string) error {
101+
checksumFileContent, err := os.ReadFile(checksumFile)
102+
if err != nil {
103+
return fmt.Errorf("failed to read checksum file %s: %w", checksumFile, err)
104+
}
105+
strippedChecksumFileContent := strings.TrimSpace(string(checksumFileContent))
106+
matches := checksumFileRegex.FindStringSubmatch(strippedChecksumFileContent)
107+
if len(matches) != 3 {
108+
return fmt.Errorf("checksum file %s has invalid format, expected `{checksum} {filename}`", checksumFile)
109+
}
110+
expectedChecksum := matches[1]
111+
fileName := matches[2]
112+
113+
filePath := filepath.Join(filepath.Dir(checksumFile), fileName)
114+
actualChecksum, err := devtools.GetSHA512Hash(filePath)
115+
if err != nil {
116+
return fmt.Errorf("failed to compute checksum of file %s: %w", fileName, err)
117+
}
118+
119+
if expectedChecksum != actualChecksum {
120+
return fmt.Errorf("checksum of file %s does not match expected checksum of %s", fileName, actualChecksum)
121+
}
122+
123+
return nil
124+
}

dev-tools/mage/downloads/versions.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -489,7 +489,14 @@ func FetchProjectBinaryForSnapshots(ctx context.Context, useCISnapshots bool, pr
489489
return "", err
490490
}
491491
if downloadSHAFile && downloadShaURL != "" {
492-
downloadLocation, err = handleDownload(downloadShaURL)
492+
checksumFileLocation, err := handleDownload(downloadShaURL)
493+
if err != nil {
494+
return "", err
495+
}
496+
err = verifyChecksum(checksumFileLocation)
497+
if err != nil {
498+
return "", err
499+
}
493500
}
494501
return downloadLocation, err
495502
}

0 commit comments

Comments
 (0)