Skip to content

Commit

Permalink
Add provider credentials validation
Browse files Browse the repository at this point in the history
Add provider validation tests

Minor refactoring
  • Loading branch information
outcatcher committed Jan 27, 2021
1 parent cf1a237 commit 6707db2
Show file tree
Hide file tree
Showing 4 changed files with 175 additions and 106 deletions.
98 changes: 56 additions & 42 deletions opentelekomcloud/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package opentelekomcloud
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"log"
"net/http"
Expand All @@ -13,7 +14,6 @@ import (
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/go-cleanhttp"
"github.com/hashicorp/terraform-plugin-sdk/helper/pathorcontents"
"github.com/hashicorp/terraform-plugin-sdk/httpclient"
Expand Down Expand Up @@ -72,44 +72,34 @@ func (c *Config) LoadAndValidate() error {
return fmt.Errorf("one of 'auth_url' or 'cloud' must be specified")
}

validEndpoint := false
validEndpoints := []string{
"internal", "internalURL",
"admin", "adminURL",
"public", "publicURL",
"",
}

for _, endpoint := range validEndpoints {
if c.EndpointType == endpoint {
validEndpoint = true
if c.Cloud != "" {
if err := c.load(); err != nil {
return err
}
}

if !validEndpoint {
return fmt.Errorf("invalid endpoint type provided")
if err := c.validateEndpoint(); err != nil {
return err
}

if c.Cloud != "" {
err := c.load()
if err != nil {
return err
}
if err := c.validateProject(); err != nil {
return err
}

err := fmt.Errorf("must config token or aksk or username password to be authorized")

if c.Token != "" {
var err error
switch {
case c.Token != "":
err = buildClientByToken(c)

} else if c.AccessKey != "" && c.SecretKey != "" {
case c.AccessKey != "" && c.SecretKey != "":
err = buildClientByAKSK(c)

} else if c.Password != "" && (c.Username != "" || c.UserID != "") {
case c.Password != "" && (c.Username != "" || c.UserID != ""):
err = buildClientByPassword(c)
default:
err = errors.New(
"no auth means provided. Token, AK/SK or username/password are required for authentication")
}
if err != nil {
return err
return fmt.Errorf("failed to authenticate:\n%s", err)
}

var osDebug bool
Expand Down Expand Up @@ -179,7 +169,7 @@ func (c *Config) load() error {
return nil
}

func generateTLSConfig(c *Config) (*tls.Config, error) {
func (c *Config) generateTLSConfig() (*tls.Config, error) {
config := &tls.Config{}
if c.CACertFile != "" {
caCert, _, err := pathorcontents.Read(c.CACertFile)
Expand Down Expand Up @@ -232,7 +222,7 @@ func (c *Config) newS3Session(osDebug bool) error {
cp, err := creds.Get()
if err != nil {
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoCredentialProviders" {
return fmt.Errorf(`No valid credential sources found for Swift S3 Provider.
return fmt.Errorf(`no valid credential sources found for Swift S3 Provider.
Please see https://terraform.io/docs/providers/aws/index.html for more information on
providing credentials for the S3 Provider`)
}
Expand Down Expand Up @@ -265,12 +255,36 @@ func (c *Config) newS3Session(osDebug bool) error {
// Set up base session for AWS/Swift S3
c.s3sess, err = session.NewSession(awsConfig)
if err != nil {
return errwrap.Wrapf("Error creating Swift S3 session: {{err}}", err)
return fmt.Errorf("error creating Swift S3 session: %s", err)
}
}
return nil
}

var validEndpoints = []string{
"internal", "internalURL",
"admin", "adminURL",
"public", "publicURL",
"",
}

func (c *Config) validateEndpoint() error {
for _, endpoint := range validEndpoints {
if c.EndpointType == endpoint {
return nil
}
}
return fmt.Errorf("invalid endpoint type provided: %s", c.EndpointType)
}

// validateProject checks that `Project`(`Tenant`) value is set
func (c *Config) validateProject() error {
if c.TenantName == "" && c.TenantID == "" && c.DelegatedProject == "" {
return errors.New("no project name/id or delegated project is provided")
}
return nil
}

func buildClientByToken(c *Config) error {
var pao, dao golangsdk.AuthOptions

Expand Down Expand Up @@ -302,9 +316,8 @@ func buildClientByToken(c *Config) error {
for _, ao := range []*golangsdk.AuthOptions{&pao, &dao} {
ao.IdentityEndpoint = c.IdentityEndpoint
ao.TokenID = c.Token

}
return genClients(c, pao, dao)
return c.genClients(pao, dao)
}

func buildClientByAKSK(c *Config) error {
Expand Down Expand Up @@ -342,7 +355,7 @@ func buildClientByAKSK(c *Config) error {
ao.AccessKey = c.AccessKey
ao.SecretKey = c.SecretKey
}
return genClients(c, pao, dao)
return c.genClients(pao, dao)
}

func buildClientByPassword(c *Config) error {
Expand Down Expand Up @@ -383,24 +396,25 @@ func buildClientByPassword(c *Config) error {
ao.Username = c.Username
ao.UserID = c.UserID
}
return genClients(c, pao, dao)
return c.genClients(pao, dao)
}

func genClients(c *Config, pao, dao golangsdk.AuthOptionsProvider) error {
client, err := genClient(c, pao)
func (c *Config) genClients(pao, dao golangsdk.AuthOptionsProvider) error {
client, err := c.genClient(pao)
if err != nil {
return err
}
c.HwClient = client

client, err = genClient(c, dao)
if err == nil {
c.DomainClient = client
client, err = c.genClient(dao)
if err != nil {
return err
}
return err
c.DomainClient = client
return nil
}

func genClient(c *Config, ao golangsdk.AuthOptionsProvider) (*golangsdk.ProviderClient, error) {
func (c *Config) genClient(ao golangsdk.AuthOptionsProvider) (*golangsdk.ProviderClient, error) {
client, err := openstack.NewClient(ao.GetIdentityEndpoint())
if err != nil {
return nil, err
Expand All @@ -409,7 +423,7 @@ func genClient(c *Config, ao golangsdk.AuthOptionsProvider) (*golangsdk.Provider
// Set UserAgent
client.UserAgent.Prepend(httpclient.TerraformUserAgent(c.terraformVersion))

config, err := generateTLSConfig(c)
config, err := c.generateTLSConfig()
if err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion opentelekomcloud/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ func testRequestRetry(t *testing.T, count int) {
})

cfg := &Config{MaxRetries: retryCount}
_, err := genClient(cfg, golangsdk.AuthOptions{
_, err := cfg.genClient(golangsdk.AuthOptions{
IdentityEndpoint: fmt.Sprintf("%s/route", th.Endpoint()),
})
_, ok := err.(golangsdk.ErrDefault500)
Expand Down
129 changes: 66 additions & 63 deletions opentelekomcloud/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func Provider() terraform.ResourceProvider {
},
"tenant_name": {
Type: schema.TypeString,
Required: true,
Optional: true,
DefaultFunc: schema.MultiEnvDefaultFunc([]string{
"OS_TENANT_NAME",
"OS_PROJECT_NAME",
Expand All @@ -79,8 +79,9 @@ func Provider() terraform.ResourceProvider {
Description: descriptions["password"],
},
"token": {
Type: schema.TypeString,
Optional: true,
Type: schema.TypeString,
Optional: true,
Sensitive: true,
DefaultFunc: schema.MultiEnvDefaultFunc([]string{
"OS_TOKEN",
"OS_AUTH_TOKEN",
Expand All @@ -90,6 +91,7 @@ func Provider() terraform.ResourceProvider {
"security_token": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("OS_SECURITY_TOKEN", ""),
Description: descriptions["security_token"],
},
Expand Down Expand Up @@ -180,66 +182,6 @@ func Provider() terraform.ResourceProvider {
Description: descriptions["max_retries"],
},
},

DataSourcesMap: map[string]*schema.Resource{
"opentelekomcloud_antiddos_v1": dataSourceAntiDdosV1(),
"opentelekomcloud_cce_cluster_v3": dataSourceCCEClusterV3(),
"opentelekomcloud_cce_node_ids_v3": dataSourceCceNodeIdsV3(),
"opentelekomcloud_cce_node_v3": dataSourceCceNodesV3(),
"opentelekomcloud_compute_availability_zones_v2": dataSourceComputeAvailabilityZonesV2(),
"opentelekomcloud_compute_bms_flavors_v2": dataSourceBMSFlavorV2(),
"opentelekomcloud_compute_bms_keypairs_v2": dataSourceBMSKeyPairV2(),
"opentelekomcloud_compute_bms_nic_v2": dataSourceBMSNicV2(),
"opentelekomcloud_compute_bms_server_v2": dataSourceBMSServersV2(),
"opentelekomcloud_csbs_backup_v1": dataSourceCSBSBackupV1(),
"opentelekomcloud_csbs_backup_policy_v1": dataSourceCSBSBackupPolicyV1(),
"opentelekomcloud_cts_tracker_v1": dataSourceCTSTrackerV1(),
"opentelekomcloud_dcs_az_v1": dataSourceDcsAZV1(),
"opentelekomcloud_dcs_maintainwindow_v1": dataSourceDcsMaintainWindowV1(),
"opentelekomcloud_dcs_product_v1": dataSourceDcsProductV1(),
"opentelekomcloud_deh_host_v1": dataSourceDEHHostV1(),
"opentelekomcloud_deh_server_v1": dataSourceDEHServersV1(),
"opentelekomcloud_dds_flavors_v3": dataSourceDdsFlavorV3(),
"opentelekomcloud_dds_instance_v3": dataSourceDdsInstanceV3(),
"opentelekomcloud_dms_az_v1": dataSourceDmsAZV1(),
"opentelekomcloud_dms_product_v1": dataSourceDmsProductV1(),
"opentelekomcloud_dms_maintainwindow_v1": dataSourceDmsMaintainWindowV1(),
"opentelekomcloud_dns_zone_v2": dataSourceDNSZoneV2(),
"opentelekomcloud_identity_auth_scope_v3": dataSourceIdentityAuthScopeV3(),
"opentelekomcloud_identity_credential_v3": dataSourceIdentityCredentialV3(),
"opentelekomcloud_identity_group_v3": dataSourceIdentityGroupV3(),
"opentelekomcloud_identity_project_v3": dataSourceIdentityProjectV3(),
"opentelekomcloud_identity_role_v3": dataSourceIdentityRoleV3(),
"opentelekomcloud_identity_user_v3": dataSourceIdentityUserV3(),
"opentelekomcloud_images_image_v2": dataSourceImagesImageV2(),
"opentelekomcloud_kms_key_v1": dataSourceKmsKeyV1(),
"opentelekomcloud_kms_data_key_v1": dataSourceKmsDataKeyV1(),
"opentelekomcloud_networking_network_v2": dataSourceNetworkingNetworkV2(),
"opentelekomcloud_networking_port_v2": dataSourceNetworkingPortV2(),
"opentelekomcloud_networking_secgroup_v2": dataSourceNetworkingSecGroupV2(),
"opentelekomcloud_obs_bucket_object": dataSourceObsBucketObject(),
"opentelekomcloud_rds_flavors_v1": dataSourceRdsFlavorV1(),
"opentelekomcloud_rds_flavors_v3": dataSourceRdsFlavorV3(),
"opentelekomcloud_rds_versions_v3": dataSourceRdsVersionsV3(),
"opentelekomcloud_rts_software_deployment_v1": dataSourceRtsSoftwareDeploymentV1(),
"opentelekomcloud_rts_software_config_v1": dataSourceRtsSoftwareConfigV1(),
"opentelekomcloud_rts_stack_resource_v1": dataSourceRTSStackResourcesV1(),
"opentelekomcloud_rts_stack_v1": dataSourceRTSStackV1(),
"opentelekomcloud_s3_bucket_object": dataSourceS3BucketObject(),
"opentelekomcloud_sfs_file_system_v2": dataSourceSFSFileSystemV2(),
"opentelekomcloud_sdrs_domain_v1": dataSourceSdrsDomainV1(),
"opentelekomcloud_vpc_v1": dataSourceVirtualPrivateCloudVpcV1(),
"opentelekomcloud_vpc_bandwidth": dataSourceBandWidth(),
"opentelekomcloud_vbs_backup_v2": dataSourceVBSBackupV2(),
"opentelekomcloud_vbs_backup_policy_v2": dataSourceVBSBackupPolicyV2(),
"opentelekomcloud_vpc_peering_connection_v2": dataSourceVpcPeeringConnectionV2(),
"opentelekomcloud_vpc_route_v2": dataSourceVPCRouteV2(),
"opentelekomcloud_vpc_route_ids_v2": dataSourceVPCRouteIdsV2(),
"opentelekomcloud_vpc_subnet_v1": dataSourceVpcSubnetV1(),
"opentelekomcloud_vpc_subnet_ids_v1": dataSourceVpcSubnetIdsV1(),
"opentelekomcloud_vpnaas_service_v2": dataSourceVpnServiceV2(),
},

ResourcesMap: map[string]*schema.Resource{
"opentelekomcloud_antiddos_v1": resourceAntiDdosV1(),
"opentelekomcloud_as_configuration_v1": resourceASConfiguration(),
Expand Down Expand Up @@ -363,6 +305,67 @@ func Provider() terraform.ResourceProvider {
"opentelekomcloud_waf_preciseprotection_rule_v1": resourceWafPreciseProtectionRuleV1(),
"opentelekomcloud_waf_webtamperprotection_rule_v1": resourceWafWebTamperProtectionRuleV1(),
},
DataSourcesMap: map[string]*schema.Resource{
"opentelekomcloud_antiddos_v1": dataSourceAntiDdosV1(),
"opentelekomcloud_cce_cluster_v3": dataSourceCCEClusterV3(),
"opentelekomcloud_cce_node_ids_v3": dataSourceCceNodeIdsV3(),
"opentelekomcloud_cce_node_v3": dataSourceCceNodesV3(),
"opentelekomcloud_compute_availability_zones_v2": dataSourceComputeAvailabilityZonesV2(),
"opentelekomcloud_compute_bms_flavors_v2": dataSourceBMSFlavorV2(),
"opentelekomcloud_compute_bms_keypairs_v2": dataSourceBMSKeyPairV2(),
"opentelekomcloud_compute_bms_nic_v2": dataSourceBMSNicV2(),
"opentelekomcloud_compute_bms_server_v2": dataSourceBMSServersV2(),
"opentelekomcloud_csbs_backup_v1": dataSourceCSBSBackupV1(),
"opentelekomcloud_csbs_backup_policy_v1": dataSourceCSBSBackupPolicyV1(),
"opentelekomcloud_cts_tracker_v1": dataSourceCTSTrackerV1(),
"opentelekomcloud_dcs_az_v1": dataSourceDcsAZV1(),
"opentelekomcloud_dcs_maintainwindow_v1": dataSourceDcsMaintainWindowV1(),
"opentelekomcloud_dcs_product_v1": dataSourceDcsProductV1(),
"opentelekomcloud_deh_host_v1": dataSourceDEHHostV1(),
"opentelekomcloud_deh_server_v1": dataSourceDEHServersV1(),
"opentelekomcloud_dds_flavors_v3": dataSourceDdsFlavorV3(),
"opentelekomcloud_dds_instance_v3": dataSourceDdsInstanceV3(),
"opentelekomcloud_dms_az_v1": dataSourceDmsAZV1(),
"opentelekomcloud_dms_product_v1": dataSourceDmsProductV1(),
"opentelekomcloud_dms_maintainwindow_v1": dataSourceDmsMaintainWindowV1(),
"opentelekomcloud_dns_zone_v2": dataSourceDNSZoneV2(),
"opentelekomcloud_identity_auth_scope_v3": dataSourceIdentityAuthScopeV3(),
"opentelekomcloud_identity_credential_v3": dataSourceIdentityCredentialV3(),
"opentelekomcloud_identity_group_v3": dataSourceIdentityGroupV3(),
"opentelekomcloud_identity_project_v3": dataSourceIdentityProjectV3(),
"opentelekomcloud_identity_role_v3": dataSourceIdentityRoleV3(),
"opentelekomcloud_identity_user_v3": dataSourceIdentityUserV3(),
"opentelekomcloud_images_image_v2": dataSourceImagesImageV2(),
"opentelekomcloud_kms_key_v1": dataSourceKmsKeyV1(),
"opentelekomcloud_kms_data_key_v1": dataSourceKmsDataKeyV1(),
"opentelekomcloud_networking_network_v2": dataSourceNetworkingNetworkV2(),
"opentelekomcloud_networking_port_v2": dataSourceNetworkingPortV2(),
"opentelekomcloud_networking_secgroup_v2": dataSourceNetworkingSecGroupV2(),
"opentelekomcloud_obs_bucket_object": dataSourceObsBucketObject(),
"opentelekomcloud_rds_flavors_v1": dataSourceRdsFlavorV1(),
"opentelekomcloud_rds_flavors_v3": dataSourceRdsFlavorV3(),
"opentelekomcloud_rds_versions_v3": dataSourceRdsVersionsV3(),
"opentelekomcloud_rts_software_deployment_v1": dataSourceRtsSoftwareDeploymentV1(),
"opentelekomcloud_rts_software_config_v1": dataSourceRtsSoftwareConfigV1(),
"opentelekomcloud_rts_stack_resource_v1": dataSourceRTSStackResourcesV1(),
"opentelekomcloud_rts_stack_v1": dataSourceRTSStackV1(),
"opentelekomcloud_s3_bucket_object": dataSourceS3BucketObject(),
"opentelekomcloud_sfs_file_system_v2": dataSourceSFSFileSystemV2(),
"opentelekomcloud_sdrs_domain_v1": dataSourceSdrsDomainV1(),
"opentelekomcloud_vpc_v1": dataSourceVirtualPrivateCloudVpcV1(),
"opentelekomcloud_vpc_bandwidth": dataSourceBandWidth(),
"opentelekomcloud_vbs_backup_v2": dataSourceVBSBackupV2(),
"opentelekomcloud_vbs_backup_policy_v2": dataSourceVBSBackupPolicyV2(),
"opentelekomcloud_vpc_peering_connection_v2": dataSourceVpcPeeringConnectionV2(),
"opentelekomcloud_vpc_route_v2": dataSourceVPCRouteV2(),
"opentelekomcloud_vpc_route_ids_v2": dataSourceVPCRouteIdsV2(),
"opentelekomcloud_vpc_subnet_v1": dataSourceVpcSubnetV1(),
"opentelekomcloud_vpc_subnet_ids_v1": dataSourceVpcSubnetIdsV1(),
"opentelekomcloud_vpnaas_service_v2": dataSourceVpnServiceV2(),
},
ConfigureFunc: nil,
MetaReset: nil,
TerraformVersion: "",
}

provider.ConfigureFunc = func(d *schema.ResourceData) (interface{}, error) {
Expand Down
Loading

0 comments on commit 6707db2

Please sign in to comment.