From d5b0beac017a9731df0a68b490d1f4f9a7b3fffd Mon Sep 17 00:00:00 2001 From: Martin Atkins Date: Wed, 18 Oct 2017 09:50:25 -0700 Subject: [PATCH] svchost/auth: static credentials source This uses an in-memory table of credentials keyed on hostname. This is the simplest possible credentials source that can actually return credentials, and is suitable for representing statically-configured credentials from configuration. --- svchost/auth/static.go | 28 +++++++++++++++++++++++++++ svchost/auth/static_test.go | 38 +++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 svchost/auth/static.go create mode 100644 svchost/auth/static_test.go diff --git a/svchost/auth/static.go b/svchost/auth/static.go new file mode 100644 index 0000000000..5373fddfcc --- /dev/null +++ b/svchost/auth/static.go @@ -0,0 +1,28 @@ +package auth + +import ( + "github.com/hashicorp/terraform/svchost" +) + +// StaticCredentialsSource is a credentials source that retrieves credentials +// from the provided map. It returns nil if a requested hostname is not +// present in the map. +// +// The caller should not modify the given map after passing it to this function. +func StaticCredentialsSource(creds map[svchost.Hostname]map[string]interface{}) CredentialsSource { + return staticCredentialsSource(creds) +} + +type staticCredentialsSource map[svchost.Hostname]map[string]interface{} + +func (s staticCredentialsSource) ForHost(host svchost.Hostname) (HostCredentials, error) { + if s == nil { + return nil, nil + } + + if m, exists := s[host]; exists { + return HostCredentialsFromMap(m), nil + } + + return nil, nil +} diff --git a/svchost/auth/static_test.go b/svchost/auth/static_test.go new file mode 100644 index 0000000000..a24a888ea3 --- /dev/null +++ b/svchost/auth/static_test.go @@ -0,0 +1,38 @@ +package auth + +import ( + "testing" + + "github.com/hashicorp/terraform/svchost" +) + +func TestStaticCredentialsSource(t *testing.T) { + src := StaticCredentialsSource(map[svchost.Hostname]map[string]interface{}{ + svchost.Hostname("example.com"): map[string]interface{}{ + "token": "abc123", + }, + }) + + t.Run("exists", func(t *testing.T) { + creds, err := src.ForHost(svchost.Hostname("example.com")) + if err != nil { + t.Fatal(err) + } + if tokCreds, isToken := creds.(HostCredentialsToken); isToken { + if got, want := string(tokCreds), "abc123"; got != want { + t.Errorf("wrong token %q; want %q", got, want) + } + } else { + t.Errorf("creds is %#v; want HostCredentialsToken", creds) + } + }) + t.Run("does not exist", func(t *testing.T) { + creds, err := src.ForHost(svchost.Hostname("example.net")) + if err != nil { + t.Fatal(err) + } + if creds != nil { + t.Errorf("creds is %#v; want nil", creds) + } + }) +}