@@ -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
1924type 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+ }
0 commit comments