Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: move CalculateFileSHA256 to utils #444

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 1 addition & 13 deletions sztp-agent/pkg/secureagent/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ package secureagent

import (
"bytes"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/asn1"
Expand Down Expand Up @@ -249,21 +248,10 @@ func (a *Agent) downloadAndValidateImage() error {
// TODO: maybe need to move sha calculatinos to a function in util.go
switch a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.BootImage.ImageVerification[i].HashAlgorithm {
case "ietf-sztp-conveyed-info:sha-256":
f, err := os.Open(ARTIFACTS_PATH + a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.InfoTimestampReference + filepath.Base(item))
sum, err := CalculateFileSHA256(ARTIFACTS_PATH + a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.InfoTimestampReference + filepath.Base(item))
if err != nil {
log.Panic(err)
return err
}
defer func() {
if err := f.Close(); err != nil {
log.Println("[ERROR] Error when closing:", err)
}
}()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return err
}
sum := fmt.Sprintf("%x", h.Sum(nil))
original := strings.ReplaceAll(a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.BootImage.ImageVerification[i].HashValue, ":", "")
log.Println("calculated: " + sum)
log.Println("expected : " + original)
Expand Down
28 changes: 28 additions & 0 deletions sztp-agent/pkg/secureagent/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@
package secureagent

import (
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"log"
"os"
"strings"

"github.com/go-ini/ini"
Expand All @@ -34,6 +38,30 @@
return serialNumber
}

// CalculateFileSHA256 computes the SHA-256 checksum of a file specified by its path.
func CalculateFileSHA256(filePath string) (string, error) {
// Open the file
file, err := os.Open(filePath)
if err != nil {
return "", err
}
defer file.Close()

Check failure on line 48 in sztp-agent/pkg/secureagent/utils.go

View workflow job for this annotation

GitHub Actions / golangci

Error return value of `file.Close` is not checked (errcheck)

// Create a new SHA256 hash object
hash := sha256.New()

// Copy the file content to the hash object
if _, err := io.Copy(hash, file); err != nil {
return "", err
}

// Get the final SHA256 hash result
checksum := hash.Sum(nil)

// Convert the result to a hexadecimal string
return fmt.Sprintf("%x", checksum), nil
}

func generateInputJSONContent() string {
osName := ""
osVersion := ""
Expand Down
44 changes: 44 additions & 0 deletions sztp-agent/pkg/secureagent/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package secureagent

import (
"os"
"testing"
)

Expand Down Expand Up @@ -47,3 +48,46 @@
})
}
}

func TestCalculateFileSHA256(t *testing.T) {
// Define test cases
tests := []struct {
name string
filePath string
want string
wantErr bool
}{
{
name: "Valid file",
filePath: "testfile.txt",
want: "d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2", // Replace with actual expected hash
wantErr: false,
},
{
name: "Non-existent file",
filePath: "nonexistentfile.txt",
want: "",
wantErr: true,
},
}

// Create a valid file for testing
err := os.WriteFile("testfile.txt", []byte("test"), 0644)
if err != nil {
t.Fatalf("Failed to create test file: %v", err)
}
defer os.Remove("testfile.txt") // Clean up the file after tests

Check failure on line 79 in sztp-agent/pkg/secureagent/utils_test.go

View workflow job for this annotation

GitHub Actions / golangci

Error return value of `os.Remove` is not checked (errcheck)

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := CalculateFileSHA256(tt.filePath)
if (err != nil) != tt.wantErr {
t.Errorf("CalculateFileSHA256() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("CalculateFileSHA256() = %v, want %v", got, tt.want)
}
})
}
}
Loading