Skip to content

Commit

Permalink
remove storing tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
ArthurHlt committed Aug 16, 2018
1 parent fe447ed commit db6b57a
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 63 deletions.
8 changes: 8 additions & 0 deletions credhub/data_sources.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand All @@ -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{
Expand All @@ -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{
Expand All @@ -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{
Expand Down Expand Up @@ -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{
Expand Down Expand Up @@ -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{
Expand Down Expand Up @@ -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{
Expand Down Expand Up @@ -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{
Expand Down
14 changes: 3 additions & 11 deletions credhub/generate_certificate.go
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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,
Expand Down Expand Up @@ -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": {
Expand Down Expand Up @@ -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,
},
Expand All @@ -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,
},
Expand Down
13 changes: 13 additions & 0 deletions credhub/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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{
Expand All @@ -75,6 +78,7 @@ func LoadResource(resource Resource) *schema.Resource {
Schema: resSchema,
}
}

func LoadDataSource(DataSource DataSource) *schema.Resource {
return &schema.Resource{
Read: DataSource.DataSourceRead,
Expand All @@ -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)
Expand All @@ -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())
Expand All @@ -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())
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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))
Expand All @@ -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
Expand Down
57 changes: 5 additions & 52 deletions credhub/provider.go
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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://") {
Expand All @@ -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))
Expand All @@ -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") {
Expand All @@ -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
}
12 changes: 12 additions & 0 deletions credhub/utils.go
Original file line number Diff line number Diff line change
@@ -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{}
}
}

0 comments on commit db6b57a

Please sign in to comment.