Skip to content

Commit

Permalink
change implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
ilia-medvedev-codefresh committed Dec 10, 2024
1 parent ced2787 commit 45679a0
Show file tree
Hide file tree
Showing 7 changed files with 79 additions and 68 deletions.
41 changes: 31 additions & 10 deletions codefresh/cfclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ import (

// Client token, host, htpp.Client
type Client struct {
Token string
TokenHeader string
Host string
HostV2 string
Client *http.Client
Token string
TokenHeader string
Host string
HostV2 string
featureFlags map[string]bool
Client *http.Client
}

// RequestOptions path, method, etc
Expand All @@ -35,11 +36,12 @@ func NewClient(hostname string, hostnameV2 string, token string, tokenHeader str
tokenHeader = "Authorization"
}
return &Client{
Host: hostname,
HostV2: hostnameV2,
Token: token,
TokenHeader: tokenHeader,
Client: &http.Client{},
Host: hostname,
HostV2: hostnameV2,
Token: token,
TokenHeader: tokenHeader,
Client: &http.Client{},
featureFlags: map[string]bool{},
}

}
Expand Down Expand Up @@ -112,6 +114,25 @@ func (client *Client) RequestApiXAccessToken(opt *RequestOptions) ([]byte, error
return body, nil
}

func (client *Client) isFeatureFlagEnabled(flagName string) (bool, error) {

if len(client.featureFlags) == 0 {
currAcc, err := client.GetCurrentAccount()

if err != nil {
return false, err
}

client.featureFlags = currAcc.FeatureFlags
}

if val, ok := client.featureFlags[flagName]; ok {
return val, nil
}

return false, nil
}

// ToQS add extra parameters to path
func ToQS(qs map[string]string) string {
var arr = []string{}
Expand Down
29 changes: 23 additions & 6 deletions codefresh/cfclient/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,16 @@ import (
"fmt"
"log"
"net/url"
"slices"
)

var encryptedContextTypes = []string{
"secret",
"secret-yaml",
"storage.s3",
"storage.azuref",
}

type ContextErrorResponse struct {
Status int `json:"status,omitempty"`
Message string `json:"message,omitempty"`
Expand All @@ -17,9 +25,10 @@ type ContextMetadata struct {
}

type Context struct {
Metadata ContextMetadata `json:"metadata,omitempty"`
Spec ContextSpec `json:"spec,omitempty"`
Version string `json:"version,omitempty"`
Metadata ContextMetadata `json:"metadata,omitempty"`
Spec ContextSpec `json:"spec,omitempty"`
Version string `json:"version,omitempty"`
IsEncrypred bool `json:"isEncrypted,omitempty"`
}

type ContextSpec struct {
Expand All @@ -31,10 +40,16 @@ func (context *Context) GetID() string {
return context.Metadata.Name
}

func (client *Client) GetContext(name string, decrypt bool) (*Context, error) {
func (client *Client) GetContext(name string) (*Context, error) {
fullPath := fmt.Sprintf("/contexts/%s", url.PathEscape(name))

if decrypt {
forbidDecrypt, err := client.isFeatureFlagEnabled("forbidDecrypt")

if err != nil {
forbidDecrypt = false
}

if !forbidDecrypt {
fullPath += "?decrypt=true"
}

Expand All @@ -54,8 +69,10 @@ func (client *Client) GetContext(name string, decrypt bool) (*Context, error) {
return nil, err
}

return &respContext, nil
isEncryptedType := slices.Contains(encryptedContextTypes, respContext.Spec.Type)
respContext.IsEncrypred = isEncryptedType && !forbidDecrypt

return &respContext, nil
}

func (client *Client) CreateContext(context *Context) (*Context, error) {
Expand Down
21 changes: 14 additions & 7 deletions codefresh/cfclient/current_account.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ type CurrentAccountUser struct {

// CurrentAccount spec
type CurrentAccount struct {
ID string
Name string
Users []CurrentAccountUser
Admins []CurrentAccountUser
ID string
Name string
Users []CurrentAccountUser
Admins []CurrentAccountUser
FeatureFlags map[string]bool
}

// GetCurrentAccount -
Expand All @@ -46,9 +47,10 @@ func (client *Client) GetCurrentAccount() (*CurrentAccount, error) {
return nil, fmt.Errorf("GetCurrentAccount - cannot get activeAccountName")
}
currentAccount := &CurrentAccount{
Name: activeAccountName,
Users: make([]CurrentAccountUser, 0),
Admins: make([]CurrentAccountUser, 0),
Name: activeAccountName,
Users: make([]CurrentAccountUser, 0),
Admins: make([]CurrentAccountUser, 0),
FeatureFlags: make(map[string]bool),
}

accountAdminsIDs := make([]string, 0)
Expand All @@ -62,6 +64,11 @@ func (client *Client) GetCurrentAccount() (*CurrentAccount, error) {
for _, adminI := range admins {
accountAdminsIDs = append(accountAdminsIDs, adminI.(string))
}
featureFlags := accX.Get("features").ObjxMap()

for k, v := range featureFlags {
currentAccount.FeatureFlags[k] = v.(bool)
}
break
}
}
Expand Down
2 changes: 1 addition & 1 deletion codefresh/data_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func dataSourceContextRead(d *schema.ResourceData, meta interface{}) error {
var err error

if name, nameOk := d.GetOk("name"); nameOk {
context, err = client.GetContext(name.(string), true)
context, err = client.GetContext(name.(string))
} else {
return fmt.Errorf("data.codefresh_context - must specify name")
}
Expand Down
2 changes: 1 addition & 1 deletion codefresh/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (

"github.com/codefresh-io/terraform-provider-codefresh/codefresh/cfclient"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"

"os"
)

Expand Down Expand Up @@ -87,5 +86,6 @@ func configureProvider(d *schema.ResourceData) (interface{}, error) {
if token == "" {
token = os.Getenv(ENV_CODEFRESH_API_KEY)
}

return cfclient.NewClient(apiURL, apiURLV2, token, ""), nil
}
40 changes: 4 additions & 36 deletions codefresh/resource_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,6 @@ func resourceContext() *schema.Resource {
Required: true,
ForceNew: true,
},
"decrypt_spec": {
Type: schema.TypeBool,
Default: true,
Optional: true,
Description: "Whether to allow decryption of context spec for encrypted contexts on read. If set to false context content diff will not be calculated against the API. Must be set to false if `forbidDecrypt` feature flag on Codefresh platfrom is enabled",
},
"spec": {
Description: "The context's specs.",
Type: schema.TypeList,
Expand Down Expand Up @@ -187,24 +181,20 @@ func resourceContextRead(d *schema.ResourceData, meta interface{}) error {

contextName := d.Id()

currentContextType := getContextTypeFromResource(d)

// Explicitly set decypt flag to true only if context type is encrypted and decrypt_spec is set to true
setExplicitDecrypt := contains(encryptedContextTypes, currentContextType) && d.Get("decrypt_spec").(bool)

if contextName == "" {
d.SetId("")
return nil
}

context, err := client.GetContext(contextName, setExplicitDecrypt)
context, err := client.GetContext(contextName)

if err != nil {
log.Printf("[DEBUG] Error while getting context. Error = %v", contextName)
return err
}

err = mapContextToResource(*context, d)

if err != nil {
log.Printf("[DEBUG] Error while mapping context to resource. Error = %v", err)
return err
Expand Down Expand Up @@ -249,10 +239,8 @@ func mapContextToResource(context cfclient.Context, d *schema.ResourceData) erro
return err
}

currentContextType := getContextTypeFromResource(d)

// Read spec from API if context is not encrypted or decrypt_spec is set to true explicitly
if d.Get("decrypt_spec").(bool) || !contains(encryptedContextTypes, currentContextType) {
// Read spec from API if context is not encrypted or forbitDecrypt is not set
if !context.IsEncrypred {

err = d.Set("spec", flattenContextSpec(context.Spec))

Expand Down Expand Up @@ -345,23 +333,3 @@ func mapResourceToContext(d *schema.ResourceData) *cfclient.Context {
},
}
}

func getContextTypeFromResource(d *schema.ResourceData) string {
if _, ok := d.GetOk("spec.0." + schemautil.MustNormalizeFieldName(contextConfig) + ".0.data"); ok {
return contextConfig
} else if _, ok := d.GetOk("spec.0." + schemautil.MustNormalizeFieldName(contextSecret) + ".0.data"); ok {
return contextSecret
} else if _, ok := d.GetOk("spec.0." + schemautil.MustNormalizeFieldName(contextYaml) + ".0.data"); ok {
return contextYaml
} else if _, ok := d.GetOk("spec.0." + schemautil.MustNormalizeFieldName(contextSecretYaml) + ".0.data"); ok {
return contextSecretYaml
} else if _, ok := d.GetOk("spec.0." + schemautil.MustNormalizeFieldName(contextGoogleStorage) + ".0.data"); ok {
return contextGoogleStorage
} else if _, ok := d.GetOk("spec.0." + schemautil.MustNormalizeFieldName(contextS3Storage) + ".0.data"); ok {
return contextS3Storage
} else if _, ok := d.GetOk("spec.0." + schemautil.MustNormalizeFieldName(contextAzureStorage) + ".0.data"); ok {
return contextAzureStorage
}

return ""
}
12 changes: 5 additions & 7 deletions codefresh/resource_context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ func TestAccCodefreshContextSecretYaml(t *testing.T) {
CheckDestroy: testAccCheckCodefreshContextDestroy,
Steps: []resource.TestStep{
{
Config: testAccCodefreshContextSecretYaml(name, "rootKey", "plainKey", "plainValue", "listKey", "listValue1", "listValue2", true),
Config: testAccCodefreshContextSecretYaml(name, "rootKey", "plainKey", "plainValue", "listKey", "listValue1", "listValue2"),
Check: resource.ComposeTestCheckFunc(
testAccCheckCodefreshContextExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "name", name),
Expand Down Expand Up @@ -159,7 +159,7 @@ func testAccCheckCodefreshContextExists(resource string) resource.TestCheckFunc
contextID := rs.Primary.ID

apiClient := testAccProvider.Meta().(*cfclient.Client)
_, err := apiClient.GetContext(contextID, false)
_, err := apiClient.GetContext(contextID)

if err != nil {
return fmt.Errorf("error fetching context with ID %s. %s", contextID, err)
Expand All @@ -177,7 +177,7 @@ func testAccCheckCodefreshContextDestroy(s *terraform.State) error {
continue
}

_, err := apiClient.GetContext(rs.Primary.ID, false)
_, err := apiClient.GetContext(rs.Primary.ID)

if err == nil {
return fmt.Errorf("Alert still exists")
Expand Down Expand Up @@ -249,20 +249,18 @@ resource "codefresh_context" "test" {
`, rName, rootKey, plainKey, plainValue, listKey, listValue1, listValue2)
}

func testAccCodefreshContextSecretYaml(rName, rootKey, plainKey, plainValue, listKey, listValue1, listValue2 string, decryptSpec bool) string {
func testAccCodefreshContextSecretYaml(rName, rootKey, plainKey, plainValue, listKey, listValue1, listValue2 string) string {

return fmt.Sprintf(`
resource "codefresh_context" "test" {
name = "%s"
decrypt_spec = %v
spec {
secretyaml {
data = "%s: \n %s: %s\n %s: \n - %s\n - %s"
}
}
}
`, rName, decryptSpec, rootKey, plainKey, plainValue, listKey, listValue1, listValue2)
`, rName, rootKey, plainKey, plainValue, listKey, listValue1, listValue2)
}

0 comments on commit 45679a0

Please sign in to comment.