Skip to content

Commit 7bcfc6c

Browse files
committed
Support ignnore user credential in instance principal authentication
1 parent 3556388 commit 7bcfc6c

File tree

3 files changed

+67
-40
lines changed

3 files changed

+67
-40
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
### Added
44
- Support for Custom Listener Port added to `database`
5+
- Support ignore API key when using InstancePrincipal authentication
56

67
## 4.40.0 (August 18, 2021)
78

oci/provider.go

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -399,9 +399,10 @@ func getSdkConfigProvider(d *schema.ResourceData, clients *OracleClients) (oci_c
399399
clients.configuration["region"] = region
400400
}
401401

402-
// TODO: DefaultConfigProvider will return us a composingConfigurationProvider that reads from SDK config files,
403-
// and then from the environment variables ("TF_VAR" prefix). References to "TF_VAR" prefix should be removed from
404-
// the SDK, since it's Terraform specific. When that happens, we need to update this to pass in the right prefix.
402+
//In GoSDK, the first step is to check if AuthType exists,
403+
//for composite provider, we only check the first provider in the list for the AuthType.
404+
//Then SDK will based on the AuthType to create the actual provider if it's a valid value.
405+
//If not, then SDK will base on the order in the composite provider list to check for necessary info (tenancyid, userID, fingerprint, region, keyID).
405406
configProviders = append(configProviders, resourceDataConfigProvider)
406407
if profile == "" {
407408
configProviders = append(configProviders, oci_common.DefaultConfigProvider())
@@ -428,9 +429,9 @@ func getConfigProviders(d *schema.ResourceData, auth string) ([]oci_common.Confi
428429
case strings.ToLower(authAPIKeySetting):
429430
// No additional config providers needed
430431
case strings.ToLower(authInstancePrincipalSetting):
431-
apiKeyConfigVariablesToUnset, ok := checkIncompatibleAttrsForApiKeyAuth(d)
432+
_, ok := checkIncompatibleAttrsForApiKeyAuth(d)
432433
if !ok {
433-
return nil, fmt.Errorf(`user credentials %v should be removed from the configuration`, strings.Join(apiKeyConfigVariablesToUnset, ", "))
434+
log.Printf("[DEBUG] Ignoring all user credentials for %v authentication", auth)
434435
}
435436

436437
region, ok := d.GetOk(regionAttrName)
@@ -459,9 +460,9 @@ func getConfigProviders(d *schema.ResourceData, auth string) ([]oci_common.Confi
459460

460461
configProviders = append(configProviders, cfg)
461462
case strings.ToLower(authInstancePrincipalWithCertsSetting):
462-
apiKeyConfigVariablesToUnset, ok := checkIncompatibleAttrsForApiKeyAuth(d)
463+
_, ok := checkIncompatibleAttrsForApiKeyAuth(d)
463464
if !ok {
464-
return nil, fmt.Errorf(`user credentials %v should be removed from the configuration`, strings.Join(apiKeyConfigVariablesToUnset, ", "))
465+
log.Printf("[DEBUG] Ignoring all user credentials for %v authentication", auth)
465466
}
466467

467468
region, ok := d.GetOkExists(regionAttrName)
@@ -511,9 +512,9 @@ func getConfigProviders(d *schema.ResourceData, auth string) ([]oci_common.Confi
511512
configProviders = append(configProviders, cfg)
512513

513514
case strings.ToLower(authSecurityToken):
514-
apiKeyConfigVariablesToUnset, ok := checkIncompatibleAttrsForApiKeyAuth(d)
515+
_, ok := checkIncompatibleAttrsForApiKeyAuth(d)
515516
if !ok {
516-
return nil, fmt.Errorf(`user credentials %v should be removed from the configuration`, strings.Join(apiKeyConfigVariablesToUnset, ", "))
517+
log.Printf("[DEBUG] Ignoring all user credentials for %v authentication", auth)
517518
}
518519
profile, ok := d.GetOk(configFileProfileAttrName)
519520
if !ok {

oci/provider_test.go

Lines changed: 56 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ import (
1313
"strings"
1414
"testing"
1515

16+
oci_identity "github.com/oracle/oci-go-sdk/v46/identity"
17+
1618
oci_budget "github.com/oracle/oci-go-sdk/v46/budget"
1719

1820
"github.com/terraform-providers/terraform-provider-oci/httpreplay"
@@ -435,21 +437,6 @@ func providerConfigTest(t *testing.T, disableRetries bool, skipRequiredField boo
435437
assert.Equal(t, err, nil)
436438
return
437439
}
438-
case authInstancePrincipalSetting:
439-
apiKeyConfigVariablesToUnset, ok := checkIncompatibleAttrsForApiKeyAuth(d)
440-
assert.False(t, ok)
441-
assert.Equal(t, fmt.Sprintf("user credentials %v should be removed from the configuration", strings.Join(apiKeyConfigVariablesToUnset, ", ")), err.Error())
442-
return
443-
case authInstancePrincipalWithCertsSetting:
444-
apiKeyConfigVariablesToUnset, ok := checkIncompatibleAttrsForApiKeyAuth(d)
445-
assert.False(t, ok)
446-
assert.Equal(t, fmt.Sprintf("user credentials %v should be removed from the configuration", strings.Join(apiKeyConfigVariablesToUnset, ", ")), err.Error())
447-
return
448-
case authSecurityToken:
449-
apiKeyConfigVariablesToUnset, ok := checkIncompatibleAttrsForApiKeyAuth(d)
450-
assert.False(t, ok)
451-
assert.Equal(t, fmt.Sprintf("user credentials %v should be removed from the configuration", strings.Join(apiKeyConfigVariablesToUnset, ", ")), err.Error())
452-
return
453440
default:
454441
assert.Error(t, err, fmt.Sprintf("auth must be one of '%s' or '%s' or '%s'", authAPIKeySetting, authInstancePrincipalSetting, authInstancePrincipalWithCertsSetting))
455442
return
@@ -935,6 +922,45 @@ func TestUnitReadOboTokenFromFile(t *testing.T) {
935922
client.ListBudgets(context.Background(), request)
936923
}
937924

925+
func TestUnitOboTokenAndApiKey(t *testing.T) {
926+
t.Skip("Run manual with a valid obo token")
927+
928+
os.Setenv("use_obo_token", "true")
929+
os.Setenv(oboTokenAttrName, "fake-token")
930+
defer os.Unsetenv(oboTokenAttrName)
931+
assert.Equal(t, "true", getEnvSettingWithBlankDefault("use_obo_token"))
932+
r := &schema.Resource{
933+
Schema: schemaMap(),
934+
}
935+
d := r.Data(nil)
936+
d.SetId("tenancy_ocid")
937+
d.Set("auth", "InstancePrincipal")
938+
d.Set("region", "us-phoenix-1")
939+
940+
// Set API key with auth=InstancePrincipal, the API should be unset
941+
d.Set("user_ocid", getEnvSettingWithBlankDefault("user_ocid"))
942+
d.Set("fingerprint", getEnvSettingWithBlankDefault("fingerprint"))
943+
d.Set("private_key_path", getEnvSettingWithBlankDefault("private_key_path"))
944+
d.Set("private_key_password", getEnvSettingWithBlankDefault("private_key_password"))
945+
d.Set("private_key", getEnvSettingWithBlankDefault("private_key"))
946+
947+
client := GetTestClients(d).budgetClient()
948+
assert.NotEmpty(t, client.Host)
949+
950+
request := oci_budget.ListBudgetsRequest{}
951+
compartmentId := getEnvSettingWithBlankDefault("compartment_id")
952+
request.CompartmentId = &compartmentId
953+
fmt.Println("======= First List call with token fake-token ======")
954+
955+
// manual verify request that contains "Opc-Obo-Token: fake-token"
956+
client.ListBudgets(context.Background(), request)
957+
958+
fmt.Println("======= Second List call with token another-token ======")
959+
os.Setenv(oboTokenAttrName, "another-token")
960+
// manual verify request that contains "Opc-Obo-Token: another-token"
961+
client.ListBudgets(context.Background(), request)
962+
}
963+
938964
// issue-routing-tag: terraform/default
939965
func TestUnitVerifyConfigForAPIKeyAuthIsNotSet_basic(t *testing.T) {
940966
httpreplay.SetScenario("TestVerifyConfigForAPIKeyAuthIsNotSet_basic")
@@ -1028,24 +1054,30 @@ func TestUnitHomeDirectoryPrivateKeyPath_basic(t *testing.T) {
10281054
// issue-routing-tag: terraform/default
10291055
func TestUnitSecurityToken_basic(t *testing.T) {
10301056
t.Skip("Run manual with a valid security token")
1031-
for _, apiKeyConfigAttribute := range apiKeyConfigAttributes {
1032-
apiKeyConfigAttributeEnvValue := getEnvSettingWithBlankDefault(apiKeyConfigAttribute)
1033-
if apiKeyConfigAttributeEnvValue != "" {
1034-
t.Skip("apiKeyConfigAttributes are set through environment variables, skip the test")
1035-
}
1036-
}
1057+
10371058
r := &schema.Resource{
10381059
Schema: schemaMap(),
10391060
}
10401061
d := r.Data(nil)
10411062
d.SetId("tenancy_ocid")
10421063
d.Set("auth", authSecurityToken)
1043-
d.Set(configFileProfileAttrName, "PROFILE4") // Run CLI command "oci session authenticate" to get token and profile
1064+
d.Set(configFileProfileAttrName, "DEFAULT")
1065+
1066+
// Set API key, should be removed by auth=SecurityToken
1067+
d.Set("user_ocid", getEnvSettingWithBlankDefault("user_ocid"))
1068+
d.Set("fingerprint", getEnvSettingWithBlankDefault("fingerprint"))
1069+
d.Set("private_key_path", getEnvSettingWithBlankDefault("private_key_path"))
1070+
d.Set("private_key_password", getEnvSettingWithBlankDefault("private_key_password"))
1071+
d.Set("private_key", getEnvSettingWithBlankDefault("private_key"))
1072+
// Run CLI command "oci session authenticate" to get token and profile
10441073
clients := &OracleClients{
10451074
sdkClientMap: make(map[string]interface{}, len(oracleClientRegistrations.registeredClients)),
10461075
configuration: make(map[string]string),
10471076
}
10481077
sdkConfigProvider, err := getSdkConfigProvider(d, clients)
1078+
_, empty := checkIncompatibleAttrsForApiKeyAuth(d)
1079+
// API key should be removed
1080+
assert.True(t, true, empty)
10491081
assert.NoError(t, err)
10501082
finger, _ := sdkConfigProvider.KeyFingerprint()
10511083
assert.NotNil(t, finger)
@@ -1057,18 +1089,11 @@ func TestUnitSecurityToken_basic(t *testing.T) {
10571089
assert.NotNil(t, region)
10581090
privateKey, _ := sdkConfigProvider.PrivateRSAKey()
10591091
assert.NotNil(t, privateKey)
1060-
client, err := oci_budget.NewBudgetClientWithConfigurationProvider(sdkConfigProvider)
1092+
client, err := oci_identity.NewIdentityClientWithConfigurationProvider(sdkConfigProvider)
10611093
assert.NoError(t, err)
10621094
assert.NotEmpty(t, client.Host)
10631095

1064-
request := oci_budget.ListBudgetsRequest{}
1065-
compartmentId, ok := d.GetOk("compartment_id")
1066-
assert.True(t, ok)
1067-
compartmentIdString := compartmentId.(string)
1068-
1069-
request.CompartmentId = &compartmentIdString
1070-
1071-
_, err = client.ListBudgets(context.Background(), request)
1096+
_, err = client.ListRegions(context.Background())
10721097
assert.NoError(t, err)
10731098
}
10741099

0 commit comments

Comments
 (0)