diff --git a/credhub/data_sources.go b/credhub/data_sources.go index ae2a2be7..e2d8c565 100644 --- a/credhub/data_sources.go +++ b/credhub/data_sources.go @@ -31,6 +31,7 @@ func (GenericDataSource) DataSourceRead(d *schema.ResourceData, meta interface{} d.Set("credential", credMap) return nil } + func (GenericDataSource) DataSourceSchema() map[string]*schema.Schema { sch := dataSourceSchemaGeneric() sch["credential"] = &schema.Schema{ @@ -53,6 +54,7 @@ func (ValueDataSource) DataSourceRead(d *schema.ResourceData, meta interface{}) d.Set("value", data) return nil } + func (ValueDataSource) DataSourceSchema() map[string]*schema.Schema { sch := dataSourceSchemaGeneric() sch["value"] = &schema.Schema{ @@ -78,6 +80,7 @@ func (JsonDataSource) DataSourceRead(d *schema.ResourceData, meta interface{}) e d.Set("json", string(b)) return nil } + func (JsonDataSource) DataSourceSchema() map[string]*schema.Schema { sch := dataSourceSchemaGeneric() sch["json"] = &schema.Schema{ @@ -99,6 +102,7 @@ func (PasswordDataSource) DataSourceRead(d *schema.ResourceData, meta interface{ d.Set("password", password) return nil } + func (PasswordDataSource) DataSourceSchema() map[string]*schema.Schema { sch := dataSourceSchemaGeneric() sch["password"] = &schema.Schema{ @@ -127,6 +131,7 @@ func (CertificateDataSource) DataSourceRead(d *schema.ResourceData, meta interfa d.Set("private_key", data.PrivateKey) return nil } + func (CertificateDataSource) DataSourceSchema() map[string]*schema.Schema { sch := dataSourceSchemaGeneric() sch["ca"] = &schema.Schema{ @@ -164,6 +169,7 @@ func (RSADataSource) DataSourceRead(d *schema.ResourceData, meta interface{}) er d.Set("private_key", data.PrivateKey) return nil } + func (RSADataSource) DataSourceSchema() map[string]*schema.Schema { sch := dataSourceSchemaGeneric() sch["public_key"] = &schema.Schema{ @@ -193,6 +199,7 @@ func (SSHDataSource) DataSourceRead(d *schema.ResourceData, meta interface{}) er d.Set("private_key", data.PrivateKey) return nil } + func (SSHDataSource) DataSourceSchema() map[string]*schema.Schema { sch := dataSourceSchemaGeneric() sch["public_key"] = &schema.Schema{ @@ -222,6 +229,7 @@ func (UserDataSource) DataSourceRead(d *schema.ResourceData, meta interface{}) e d.Set("password", data.Password) return nil } + func (UserDataSource) DataSourceSchema() map[string]*schema.Schema { sch := dataSourceSchemaGeneric() sch["username"] = &schema.Schema{ diff --git a/credhub/generate_certificate.go b/credhub/generate_certificate.go index 9a2b49c2..3f191b30 100644 --- a/credhub/generate_certificate.go +++ b/credhub/generate_certificate.go @@ -1,7 +1,6 @@ package credhub import ( - "fmt" "github.com/cloudfoundry-incubator/credhub-cli/credhub" "github.com/cloudfoundry-incubator/credhub-cli/credhub/credentials/generate" "github.com/hashicorp/terraform/helper/schema" @@ -18,6 +17,7 @@ var validKeyUsage map[string]bool = map[string]bool{ "encipher_only": true, "decipher_only": true, } + var validExtendKeyUsage map[string]bool = map[string]bool{ "client_auth": true, "server_auth": true, @@ -54,14 +54,6 @@ func (GenerateCertificateResource) Create(d *schema.ResourceData, meta interface return nil } -func (GenerateCertificateResource) validateFromMap(mapValid map[string]bool, keyType string) func(elem interface{}, index string) ([]string, []error) { - return func(elem interface{}, index string) ([]string, []error) { - if _, ok := mapValid[elem.(string)]; !ok { - return make([]string, 0), []error{fmt.Errorf("The provided %s is not supported. Valid values include %s.", keyType, validateMapToString(mapValid))} - } - return make([]string, 0), []error{} - } -} func (r GenerateCertificateResource) Schema() map[string]*schema.Schema { return map[string]*schema.Schema{ "key_length": { @@ -108,7 +100,7 @@ func (r GenerateCertificateResource) Schema() map[string]*schema.Schema { Optional: true, Elem: &schema.Schema{ Type: schema.TypeString, - ValidateFunc: r.validateFromMap(validKeyUsage, "key usage"), + ValidateFunc: validateFromMap(validKeyUsage, "key usage"), }, Set: schema.HashString, }, @@ -117,7 +109,7 @@ func (r GenerateCertificateResource) Schema() map[string]*schema.Schema { Optional: true, Elem: &schema.Schema{ Type: schema.TypeString, - ValidateFunc: r.validateFromMap(validExtendKeyUsage, "extended key usage"), + ValidateFunc: validateFromMap(validExtendKeyUsage, "extended key usage"), }, Set: schema.HashString, }, diff --git a/credhub/loader.go b/credhub/loader.go index bf94c583..d143ed22 100644 --- a/credhub/loader.go +++ b/credhub/loader.go @@ -18,10 +18,12 @@ type Resource interface { Update(*schema.ResourceData, interface{}) error Schema() map[string]*schema.Schema } + type GenerateResource interface { Create(*schema.ResourceData, interface{}) error Schema() map[string]*schema.Schema } + type DataSource interface { DataSourceSchema() map[string]*schema.Schema DataSourceRead(*schema.ResourceData, interface{}) error @@ -59,6 +61,7 @@ func LoadGenerateResource(resource GenerateResource) *schema.Resource { Schema: resSchema, } } + func LoadResource(resource Resource) *schema.Resource { resSchema := resource.Schema() resSchema["name"] = &schema.Schema{ @@ -75,6 +78,7 @@ func LoadResource(resource Resource) *schema.Resource { Schema: resSchema, } } + func LoadDataSource(DataSource DataSource) *schema.Resource { return &schema.Resource{ Read: DataSource.DataSourceRead, @@ -86,16 +90,19 @@ func Name(d *schema.ResourceData) string { return d.Get("name").(string) } + func SetName(d *schema.ResourceData, value string) { d.Set("name", value) } + func transformCredhubError(err error) error { if errResp, ok := err.(*credhub.Error); ok { return fmt.Errorf("%s: %s", errResp.Name, errResp.Description) } return err } + func CreateCreateFunc(create func(d *schema.ResourceData, meta interface{}) error) func(d *schema.ResourceData, meta interface{}) error { return func(d *schema.ResourceData, meta interface{}) error { err := create(d, meta) @@ -112,6 +119,7 @@ func CreateCreateFunc(create func(d *schema.ResourceData, meta interface{}) erro return nil } } + func Delete(d *schema.ResourceData, meta interface{}) error { client := meta.(*credhub.CredHub) cred, err := client.GetById(d.Id()) @@ -120,6 +128,7 @@ func Delete(d *schema.ResourceData, meta interface{}) error { } return client.Delete(cred.Name) } + func GenerateResourceRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*credhub.CredHub) cred, err := client.GetById(d.Id()) @@ -154,6 +163,7 @@ func GenerateResourceRead(d *schema.ResourceData, meta interface{}) error { } return nil } + func generateSignature(value interface{}) string { h := sha512.New() b, err := json.Marshal(value) @@ -164,6 +174,7 @@ func generateSignature(value interface{}) string { sumB := h.Sum(nil) return fmt.Sprintf("%x", sumB) } + func Exists(d *schema.ResourceData, meta interface{}) (bool, error) { client := meta.(*credhub.CredHub) var cred credentials.Credential @@ -191,6 +202,7 @@ func SchemaSetToStringList(set *schema.Set) []string { } return finalList } + func SchemaSetToIntList(set *schema.Set) []int { data := set.List() finalList := make([]int, len(data)) @@ -199,6 +211,7 @@ func SchemaSetToIntList(set *schema.Set) []int { } return finalList } + func validateMapToString(mapValid map[string]bool) string { asList := make([]string, len(mapValid)) i := 0 diff --git a/credhub/provider.go b/credhub/provider.go index 04622337..87a53394 100644 --- a/credhub/provider.go +++ b/credhub/provider.go @@ -1,28 +1,14 @@ package credhub import ( - "encoding/json" "fmt" "github.com/cloudfoundry-incubator/credhub-cli/credhub" "github.com/cloudfoundry-incubator/credhub-cli/credhub/auth" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/terraform" - "io/ioutil" - "os" - "path/filepath" "strings" - "time" ) -const ( - TOKENS_FILENAME = "tf-credhub-tokens.json" -) - -type Tokens struct { - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token"` -} - func Provider() terraform.ResourceProvider { // The actual provider @@ -96,6 +82,7 @@ func Provider() terraform.ResourceProvider { ConfigureFunc: providerConfigure, } } + func providerConfigure(d *schema.ResourceData) (interface{}, error) { apiEndpoint := strings.TrimPrefix(d.Get("credhub_server").(string), "http://") if !strings.HasPrefix(apiEndpoint, "https://") { @@ -108,15 +95,12 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) { if (username == "" || password == "") && (clientId == "" || clientSecret == "") { return nil, fmt.Errorf("One of pair Username/Password or Client_id/client_secret must be set.") } - tokens, err := retrieveTokens() - if err != nil { - return nil, err - } + options := make([]credhub.Option, 0) if username != "" && password != "" { - options = append(options, credhub.Auth(auth.Uaa(clientId, clientSecret, username, password, tokens.AccessToken, tokens.RefreshToken, false))) + options = append(options, credhub.Auth(auth.Uaa(clientId, clientSecret, username, password, "", "", false))) } else { - options = append(options, credhub.Auth(auth.Uaa(clientId, clientSecret, username, password, tokens.AccessToken, tokens.RefreshToken, true))) + options = append(options, credhub.Auth(auth.Uaa(clientId, clientSecret, username, password, "", "", true))) } if d.Get("skip_ssl_validation").(bool) { options = append(options, credhub.SkipTLSValidation(true)) @@ -136,14 +120,9 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) { return nil, err } - tokens.AccessToken = oauthStrategy.AccessToken() - tokens.RefreshToken = oauthStrategy.RefreshToken() - err = storeTokens(tokens) - if err != nil { - return nil, err - } return client, nil } + func uaaLogin(client *credhub.CredHub, oauthStrat *auth.OAuthStrategy) error { _, err := client.GetById("fake") if err == nil || !strings.Contains(err.Error(), "invalid_token") { @@ -152,29 +131,3 @@ func uaaLogin(client *credhub.CredHub, oauthStrat *auth.OAuthStrategy) error { oauthStrat.SetTokens("", "") return oauthStrat.Login() } -func retrieveTokens() (Tokens, error) { - tokenPath := filepath.Join(os.TempDir(), TOKENS_FILENAME) - - if _, err := os.Stat(tokenPath); os.IsNotExist(err) { - return Tokens{}, nil - } - b, err := ioutil.ReadFile(tokenPath) - if err != nil { - return Tokens{}, err - } - var tokens Tokens - err = json.Unmarshal(b, &tokens) - if err != nil { - return Tokens{}, err - } - return tokens, nil -} -func storeTokens(tokens Tokens, fail ...bool) error { - b, _ := json.Marshal(tokens) - err := ioutil.WriteFile(filepath.Join(os.TempDir(), TOKENS_FILENAME), b, 0644) - if err != nil && len(fail) == 0 { - time.Sleep(time.Millisecond * 5) - return storeTokens(tokens, true) - } - return err -} diff --git a/credhub/utils.go b/credhub/utils.go new file mode 100644 index 00000000..042eae0e --- /dev/null +++ b/credhub/utils.go @@ -0,0 +1,12 @@ +package credhub + +import "fmt" + +func validateFromMap(mapValid map[string]bool, keyType string) func(elem interface{}, index string) ([]string, []error) { + return func(elem interface{}, index string) ([]string, []error) { + if _, ok := mapValid[elem.(string)]; !ok { + return make([]string, 0), []error{fmt.Errorf("The provided %s is not supported. Valid values include %s.", keyType, validateMapToString(mapValid))} + } + return make([]string, 0), []error{} + } +}