Skip to content

Commit 45679a0

Browse files
change implementation
1 parent ced2787 commit 45679a0

File tree

7 files changed

+79
-68
lines changed

7 files changed

+79
-68
lines changed

codefresh/cfclient/client.go

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,12 @@ import (
1111

1212
// Client token, host, htpp.Client
1313
type Client struct {
14-
Token string
15-
TokenHeader string
16-
Host string
17-
HostV2 string
18-
Client *http.Client
14+
Token string
15+
TokenHeader string
16+
Host string
17+
HostV2 string
18+
featureFlags map[string]bool
19+
Client *http.Client
1920
}
2021

2122
// RequestOptions path, method, etc
@@ -35,11 +36,12 @@ func NewClient(hostname string, hostnameV2 string, token string, tokenHeader str
3536
tokenHeader = "Authorization"
3637
}
3738
return &Client{
38-
Host: hostname,
39-
HostV2: hostnameV2,
40-
Token: token,
41-
TokenHeader: tokenHeader,
42-
Client: &http.Client{},
39+
Host: hostname,
40+
HostV2: hostnameV2,
41+
Token: token,
42+
TokenHeader: tokenHeader,
43+
Client: &http.Client{},
44+
featureFlags: map[string]bool{},
4345
}
4446

4547
}
@@ -112,6 +114,25 @@ func (client *Client) RequestApiXAccessToken(opt *RequestOptions) ([]byte, error
112114
return body, nil
113115
}
114116

117+
func (client *Client) isFeatureFlagEnabled(flagName string) (bool, error) {
118+
119+
if len(client.featureFlags) == 0 {
120+
currAcc, err := client.GetCurrentAccount()
121+
122+
if err != nil {
123+
return false, err
124+
}
125+
126+
client.featureFlags = currAcc.FeatureFlags
127+
}
128+
129+
if val, ok := client.featureFlags[flagName]; ok {
130+
return val, nil
131+
}
132+
133+
return false, nil
134+
}
135+
115136
// ToQS add extra parameters to path
116137
func ToQS(qs map[string]string) string {
117138
var arr = []string{}

codefresh/cfclient/context.go

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,16 @@ import (
44
"fmt"
55
"log"
66
"net/url"
7+
"slices"
78
)
89

10+
var encryptedContextTypes = []string{
11+
"secret",
12+
"secret-yaml",
13+
"storage.s3",
14+
"storage.azuref",
15+
}
16+
917
type ContextErrorResponse struct {
1018
Status int `json:"status,omitempty"`
1119
Message string `json:"message,omitempty"`
@@ -17,9 +25,10 @@ type ContextMetadata struct {
1725
}
1826

1927
type Context struct {
20-
Metadata ContextMetadata `json:"metadata,omitempty"`
21-
Spec ContextSpec `json:"spec,omitempty"`
22-
Version string `json:"version,omitempty"`
28+
Metadata ContextMetadata `json:"metadata,omitempty"`
29+
Spec ContextSpec `json:"spec,omitempty"`
30+
Version string `json:"version,omitempty"`
31+
IsEncrypred bool `json:"isEncrypted,omitempty"`
2332
}
2433

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

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

37-
if decrypt {
46+
forbidDecrypt, err := client.isFeatureFlagEnabled("forbidDecrypt")
47+
48+
if err != nil {
49+
forbidDecrypt = false
50+
}
51+
52+
if !forbidDecrypt {
3853
fullPath += "?decrypt=true"
3954
}
4055

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

57-
return &respContext, nil
72+
isEncryptedType := slices.Contains(encryptedContextTypes, respContext.Spec.Type)
73+
respContext.IsEncrypred = isEncryptedType && !forbidDecrypt
5874

75+
return &respContext, nil
5976
}
6077

6178
func (client *Client) CreateContext(context *Context) (*Context, error) {

codefresh/cfclient/current_account.go

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,11 @@ type CurrentAccountUser struct {
1818

1919
// CurrentAccount spec
2020
type CurrentAccount struct {
21-
ID string
22-
Name string
23-
Users []CurrentAccountUser
24-
Admins []CurrentAccountUser
21+
ID string
22+
Name string
23+
Users []CurrentAccountUser
24+
Admins []CurrentAccountUser
25+
FeatureFlags map[string]bool
2526
}
2627

2728
// GetCurrentAccount -
@@ -46,9 +47,10 @@ func (client *Client) GetCurrentAccount() (*CurrentAccount, error) {
4647
return nil, fmt.Errorf("GetCurrentAccount - cannot get activeAccountName")
4748
}
4849
currentAccount := &CurrentAccount{
49-
Name: activeAccountName,
50-
Users: make([]CurrentAccountUser, 0),
51-
Admins: make([]CurrentAccountUser, 0),
50+
Name: activeAccountName,
51+
Users: make([]CurrentAccountUser, 0),
52+
Admins: make([]CurrentAccountUser, 0),
53+
FeatureFlags: make(map[string]bool),
5254
}
5355

5456
accountAdminsIDs := make([]string, 0)
@@ -62,6 +64,11 @@ func (client *Client) GetCurrentAccount() (*CurrentAccount, error) {
6264
for _, adminI := range admins {
6365
accountAdminsIDs = append(accountAdminsIDs, adminI.(string))
6466
}
67+
featureFlags := accX.Get("features").ObjxMap()
68+
69+
for k, v := range featureFlags {
70+
currentAccount.FeatureFlags[k] = v.(bool)
71+
}
6572
break
6673
}
6774
}

codefresh/data_context.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ func dataSourceContextRead(d *schema.ResourceData, meta interface{}) error {
3636
var err error
3737

3838
if name, nameOk := d.GetOk("name"); nameOk {
39-
context, err = client.GetContext(name.(string), true)
39+
context, err = client.GetContext(name.(string))
4040
} else {
4141
return fmt.Errorf("data.codefresh_context - must specify name")
4242
}

codefresh/provider.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55

66
"github.com/codefresh-io/terraform-provider-codefresh/codefresh/cfclient"
77
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
8-
98
"os"
109
)
1110

@@ -87,5 +86,6 @@ func configureProvider(d *schema.ResourceData) (interface{}, error) {
8786
if token == "" {
8887
token = os.Getenv(ENV_CODEFRESH_API_KEY)
8988
}
89+
9090
return cfclient.NewClient(apiURL, apiURLV2, token, ""), nil
9191
}

codefresh/resource_context.go

Lines changed: 4 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -64,12 +64,6 @@ func resourceContext() *schema.Resource {
6464
Required: true,
6565
ForceNew: true,
6666
},
67-
"decrypt_spec": {
68-
Type: schema.TypeBool,
69-
Default: true,
70-
Optional: true,
71-
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",
72-
},
7367
"spec": {
7468
Description: "The context's specs.",
7569
Type: schema.TypeList,
@@ -187,24 +181,20 @@ func resourceContextRead(d *schema.ResourceData, meta interface{}) error {
187181

188182
contextName := d.Id()
189183

190-
currentContextType := getContextTypeFromResource(d)
191-
192-
// Explicitly set decypt flag to true only if context type is encrypted and decrypt_spec is set to true
193-
setExplicitDecrypt := contains(encryptedContextTypes, currentContextType) && d.Get("decrypt_spec").(bool)
194-
195184
if contextName == "" {
196185
d.SetId("")
197186
return nil
198187
}
199188

200-
context, err := client.GetContext(contextName, setExplicitDecrypt)
189+
context, err := client.GetContext(contextName)
201190

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

207196
err = mapContextToResource(*context, d)
197+
208198
if err != nil {
209199
log.Printf("[DEBUG] Error while mapping context to resource. Error = %v", err)
210200
return err
@@ -249,10 +239,8 @@ func mapContextToResource(context cfclient.Context, d *schema.ResourceData) erro
249239
return err
250240
}
251241

252-
currentContextType := getContextTypeFromResource(d)
253-
254-
// Read spec from API if context is not encrypted or decrypt_spec is set to true explicitly
255-
if d.Get("decrypt_spec").(bool) || !contains(encryptedContextTypes, currentContextType) {
242+
// Read spec from API if context is not encrypted or forbitDecrypt is not set
243+
if !context.IsEncrypred {
256244

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

@@ -345,23 +333,3 @@ func mapResourceToContext(d *schema.ResourceData) *cfclient.Context {
345333
},
346334
}
347335
}
348-
349-
func getContextTypeFromResource(d *schema.ResourceData) string {
350-
if _, ok := d.GetOk("spec.0." + schemautil.MustNormalizeFieldName(contextConfig) + ".0.data"); ok {
351-
return contextConfig
352-
} else if _, ok := d.GetOk("spec.0." + schemautil.MustNormalizeFieldName(contextSecret) + ".0.data"); ok {
353-
return contextSecret
354-
} else if _, ok := d.GetOk("spec.0." + schemautil.MustNormalizeFieldName(contextYaml) + ".0.data"); ok {
355-
return contextYaml
356-
} else if _, ok := d.GetOk("spec.0." + schemautil.MustNormalizeFieldName(contextSecretYaml) + ".0.data"); ok {
357-
return contextSecretYaml
358-
} else if _, ok := d.GetOk("spec.0." + schemautil.MustNormalizeFieldName(contextGoogleStorage) + ".0.data"); ok {
359-
return contextGoogleStorage
360-
} else if _, ok := d.GetOk("spec.0." + schemautil.MustNormalizeFieldName(contextS3Storage) + ".0.data"); ok {
361-
return contextS3Storage
362-
} else if _, ok := d.GetOk("spec.0." + schemautil.MustNormalizeFieldName(contextAzureStorage) + ".0.data"); ok {
363-
return contextAzureStorage
364-
}
365-
366-
return ""
367-
}

codefresh/resource_context_test.go

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ func TestAccCodefreshContextSecretYaml(t *testing.T) {
129129
CheckDestroy: testAccCheckCodefreshContextDestroy,
130130
Steps: []resource.TestStep{
131131
{
132-
Config: testAccCodefreshContextSecretYaml(name, "rootKey", "plainKey", "plainValue", "listKey", "listValue1", "listValue2", true),
132+
Config: testAccCodefreshContextSecretYaml(name, "rootKey", "plainKey", "plainValue", "listKey", "listValue1", "listValue2"),
133133
Check: resource.ComposeTestCheckFunc(
134134
testAccCheckCodefreshContextExists(resourceName),
135135
resource.TestCheckResourceAttr(resourceName, "name", name),
@@ -159,7 +159,7 @@ func testAccCheckCodefreshContextExists(resource string) resource.TestCheckFunc
159159
contextID := rs.Primary.ID
160160

161161
apiClient := testAccProvider.Meta().(*cfclient.Client)
162-
_, err := apiClient.GetContext(contextID, false)
162+
_, err := apiClient.GetContext(contextID)
163163

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

180-
_, err := apiClient.GetContext(rs.Primary.ID, false)
180+
_, err := apiClient.GetContext(rs.Primary.ID)
181181

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

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

254254
return fmt.Sprintf(`
255255
resource "codefresh_context" "test" {
256256
257257
name = "%s"
258258
259-
decrypt_spec = %v
260-
261259
spec {
262260
secretyaml {
263261
data = "%s: \n %s: %s\n %s: \n - %s\n - %s"
264262
}
265263
}
266264
}
267-
`, rName, decryptSpec, rootKey, plainKey, plainValue, listKey, listValue1, listValue2)
265+
`, rName, rootKey, plainKey, plainValue, listKey, listValue1, listValue2)
268266
}

0 commit comments

Comments
 (0)