Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

provider: Prevent panic when setting endpoints configuration #8226

Merged
merged 4 commits into from
Apr 10, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion aws/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ func (c *Config) Client() (interface{}, error) {
codedeployconn: codedeploy.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["codedeploy"])})),
codepipelineconn: codepipeline.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["codepipeline"])})),
cognitoconn: cognitoidentity.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["cognitoidentity"])})),
cognitoidpconn: cognitoidentityprovider.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["cognitoidentityprovider"])})),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was a bug discovered by the new acceptance testing. 👍

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

cognitoidpconn: cognitoidentityprovider.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["cognitoidp"])})),
configconn: configservice.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["configservice"])})),
costandusagereportconn: costandusagereportservice.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["cur"])})),
datapipelineconn: datapipeline.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["datapipeline"])})),
Expand Down
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -968,6 +968,7 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) {
Profile: d.Get("profile").(string),
Token: d.Get("token").(string),
Region: d.Get("region").(string),
Endpoints: make(map[string]string),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✔️

MaxRetries: d.Get("max_retries").(int),
Insecure: d.Get("insecure").(bool),
SkipCredsValidation: d.Get("skip_credentials_validation").(bool),
Expand Down
211 changes: 211 additions & 0 deletions aws/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import (
"fmt"
"log"
"os"
"reflect"
"regexp"
"strings"
"testing"

"github.com/aws/aws-sdk-go/aws/arn"
Expand Down Expand Up @@ -355,3 +357,212 @@ func testSweepSkipSweepError(err error) bool {
}
return false
}

func TestAccAWSProvider_Endpoints(t *testing.T) {
var providers []*schema.Provider
var endpoints strings.Builder

// Initialize each endpoint configuration with matching name and value
for _, endpointServiceName := range endpointServiceNames {
// Skip deprecated endpoint configurations as they will override expected values
if endpointServiceName == "kinesis_analytics" || endpointServiceName == "r53" {
continue
}

endpoints.WriteString(fmt.Sprintf("%s = \"http://%s\"\n", endpointServiceName, endpointServiceName))
}

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: testAccProviderFactories(&providers),
Steps: []resource.TestStep{
{
Config: testAccAWSProviderConfigEndpoints(endpoints.String()),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSProviderEndpoints(&providers),
),
},
},
})
}

func TestAccAWSProvider_Endpoints_Deprecated(t *testing.T) {
var providers []*schema.Provider
var endpointsDeprecated strings.Builder

// Initialize each deprecated endpoint configuration with matching name and value
for _, endpointServiceName := range endpointServiceNames {
// Only configure deprecated endpoint configurations
if endpointServiceName != "kinesis_analytics" && endpointServiceName != "r53" {
continue
}

endpointsDeprecated.WriteString(fmt.Sprintf("%s = \"http://%s\"\n", endpointServiceName, endpointServiceName))
}

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: testAccProviderFactories(&providers),
Steps: []resource.TestStep{
{
Config: testAccAWSProviderConfigEndpoints(endpointsDeprecated.String()),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSProviderEndpointsDeprecated(&providers),
),
},
},
})
}

func testAccCheckAWSProviderEndpoints(providers *[]*schema.Provider) resource.TestCheckFunc {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function signature threw me for a bit.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed it is a little bizarre! Dealing with pointers here so we can instantiate the slice during runtime. See also: testAccCheckEbsSnapshotCopyExistsWithProviders

return func(s *terraform.State) error {
if providers == nil {
return fmt.Errorf("no providers initialized")
}

// Match AWSClient struct field names to endpoint configuration names
endpointFieldNameF := func(endpoint string) func(string) bool {
return func(name string) bool {
switch endpoint {
case "applicationautoscaling":
endpoint = "appautoscaling"
case "budgets":
endpoint = "budget"
case "cloudformation":
endpoint = "cf"
case "cloudhsm":
endpoint = "cloudhsmv2"
case "cognitoidentity":
endpoint = "cognito"
case "configservice":
endpoint = "config"
case "cur":
endpoint = "costandusagereport"
case "directconnect":
endpoint = "dx"
case "lexmodels":
endpoint = "lexmodel"
case "route53":
endpoint = "r53"
case "sdb":
endpoint = "simpledb"
case "serverlessrepo":
endpoint = "serverlessapplicationrepository"
case "servicecatalog":
endpoint = "sc"
case "servicediscovery":
endpoint = "sd"
case "stepfunctions":
endpoint = "sfn"
}

switch name {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thought about recommending an if statement here, but the multiple || is too much, and I don't feel strongly enough to say use a regex match 💯

case endpoint, fmt.Sprintf("%sconn", endpoint), fmt.Sprintf("%sConn", endpoint):
return true
}

return false
}
}

for _, provider := range *providers {
if provider == nil || provider.Meta() == nil || provider.Meta().(*AWSClient) == nil {
continue
}

providerClient := provider.Meta().(*AWSClient)

for _, endpointServiceName := range endpointServiceNames {
// Skip deprecated endpoint configurations as they will override expected values
if endpointServiceName == "kinesis_analytics" || endpointServiceName == "r53" {
continue
}

providerClientField := reflect.Indirect(reflect.ValueOf(providerClient)).FieldByNameFunc(endpointFieldNameF(endpointServiceName))

if !providerClientField.IsValid() {
return fmt.Errorf("unable to match AWSClient struct field name for endpoint name: %s", endpointServiceName)
}

actualEndpoint := reflect.Indirect(reflect.Indirect(providerClientField).FieldByName("Config").FieldByName("Endpoint")).String()
expectedEndpoint := fmt.Sprintf("http://%s", endpointServiceName)

if actualEndpoint != expectedEndpoint {
return fmt.Errorf("expected endpoint (%s) value (%s), got: %s", endpointServiceName, expectedEndpoint, actualEndpoint)
}
}
}

return nil
}
}

func testAccCheckAWSProviderEndpointsDeprecated(providers *[]*schema.Provider) resource.TestCheckFunc {
return func(s *terraform.State) error {
if providers == nil {
return fmt.Errorf("no providers initialized")
}

// Match AWSClient struct field names to endpoint configuration names
endpointFieldNameF := func(endpoint string) func(string) bool {
return func(name string) bool {
switch endpoint {
case "kinesis_analytics":
endpoint = "kinesisanalytics"
}

return name == fmt.Sprintf("%sconn", endpoint)
}
}

for _, provider := range *providers {
if provider == nil || provider.Meta() == nil || provider.Meta().(*AWSClient) == nil {
continue
}

providerClient := provider.Meta().(*AWSClient)

for _, endpointServiceName := range endpointServiceNames {
// Only check deprecated endpoint configurations
if endpointServiceName != "kinesis_analytics" && endpointServiceName != "r53" {
continue
}

providerClientField := reflect.Indirect(reflect.ValueOf(providerClient)).FieldByNameFunc(endpointFieldNameF(endpointServiceName))

if !providerClientField.IsValid() {
return fmt.Errorf("unable to match AWSClient struct field name for endpoint name: %s", endpointServiceName)
}

actualEndpoint := reflect.Indirect(reflect.Indirect(providerClientField).FieldByName("Config").FieldByName("Endpoint")).String()
expectedEndpoint := fmt.Sprintf("http://%s", endpointServiceName)

if actualEndpoint != expectedEndpoint {
return fmt.Errorf("expected endpoint (%s) value (%s), got: %s", endpointServiceName, expectedEndpoint, actualEndpoint)
}
}
}

return nil
}
}

func testAccAWSProviderConfigEndpoints(endpoints string) string {
return fmt.Sprintf(`
provider "aws" {
skip_credentials_validation = true
skip_get_ec2_platforms = true
skip_metadata_api_check = true
skip_requesting_account_id = true

endpoints {
%[1]s
}
}

# Required to initialize the provider
data "aws_arn" "test" {
arn = "arn:aws:s3:::test"
}
`, endpoints)
}