From 0a08214a7472f983c1c9463aa3671d12dc76bc36 Mon Sep 17 00:00:00 2001 From: Martin Atkins Date: Thu, 13 Apr 2017 13:08:21 -0700 Subject: [PATCH] plugin/discovery: SHA256() method to get the hash of each plugin This will be used later to verify that installed plugins match what's available on the releases server. --- plugin/discovery/meta.go | 22 ++++++++++++++++++++++ plugin/discovery/meta_test.go | 22 ++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 plugin/discovery/meta_test.go diff --git a/plugin/discovery/meta.go b/plugin/discovery/meta.go index 16c7e8712..d93296cfc 100644 --- a/plugin/discovery/meta.go +++ b/plugin/discovery/meta.go @@ -1,6 +1,10 @@ package discovery import ( + "crypto/sha256" + "io" + "os" + "github.com/blang/semver" ) @@ -26,3 +30,21 @@ type PluginMeta struct { func (m PluginMeta) VersionObj() (semver.Version, error) { return semver.Make(m.Version) } + +// SHA256 returns a SHA256 hash of the content of the referenced executable +// file, or an error if the file's contents cannot be read. +func (m PluginMeta) SHA256() ([]byte, error) { + f, err := os.Open(m.Path) + if err != nil { + return nil, err + } + defer f.Close() + + h := sha256.New() + _, err = io.Copy(h, f) + if err != nil { + return nil, err + } + + return h.Sum(nil), nil +} diff --git a/plugin/discovery/meta_test.go b/plugin/discovery/meta_test.go new file mode 100644 index 000000000..9249d6f44 --- /dev/null +++ b/plugin/discovery/meta_test.go @@ -0,0 +1,22 @@ +package discovery + +import ( + "fmt" + "testing" +) + +func TestMetaSHA256(t *testing.T) { + m := PluginMeta{ + Path: "test-fixtures/current-style-plugins/mockos_mockarch/terraform-foo-bar-V0.0.1", + } + hash, err := m.SHA256() + if err != nil { + t.Fatalf("failed: %s", err) + } + + got := fmt.Sprintf("%x", hash) + want := "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" // (hash of empty file) + if got != want { + t.Errorf("incorrect hash %s; want %s", got, want) + } +}