diff --git a/.golangci.yml b/.golangci.yml index 75dceea..03c18b0 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -29,15 +29,13 @@ linters: - whitespace settings: cyclop: - max-complexity: 15 + max-complexity: 25 dogsled: max-blank-identifiers: 3 dupl: threshold: 150 forbidigo: forbid: - - pattern: os\.Getenv - msg: Use `viper.BindEnv` for new environment variables instead of `os.Getenv` - pattern: '\.(Skip|SkipNow)\(' msg: Use `t.Skipf("")` with a descriptive reason; do not use `t.Skip`/`t.SkipNow` - pattern: ^path\.Join$ @@ -45,11 +43,11 @@ linters: exclude-godoc-examples: false analyze-types: false funlen: - lines: 60 - statements: 40 + lines: 260 + statements: 150 ignore-comments: true gocognit: - min-complexity: 20 + min-complexity: 50 gocritic: enabled-checks: - rangeValCopy @@ -92,7 +90,7 @@ linters: - (github.com/cloudposse/atmos/pkg/logger.AtmosLogger).Fatal - (github.com/cloudposse/atmos/pkg/logger.AtmosLogger).Trace nestif: - min-complexity: 4 + min-complexity: 13 revive: rules: - name: banned-characters @@ -103,28 +101,28 @@ linters: - disallow-newlines: true - name: file-length-limit arguments: - - max: 500 + - max: 4000 skipBlankLines: true skipComments: true - name: function-length arguments: - - 50 - - 60 + - 120 + - 250 - name: function-result-limit arguments: - 3 - name: cognitive-complexity arguments: - - 25 + - 50 - name: cyclomatic arguments: - - 10 + - 25 - name: add-constant arguments: - allowFloats: 0.0,0.,1.0,1.,2.0,2. - allowInts: 0,1,2,3,4 - allowStrs: '"","image","error","path","import","path","%w","%s","file","/"' - maxLitCount: "3" + allowInts: 0,1,2,3,4,5,6,7,8,9,10,15,16,20,24,25,30,32,50,60,64,100,128,256,443,500,512,1000,1024 + allowStrs: '"","image","error","path","import","%w","%s","file","/",".","name","tags","tags_all","arn","id","description","status","region","detector_id","parent_id","policy","policy_arns","role_arn","session_name","duration","dns_name","service_id","reverse_dns_prefix","expiration_date","https://","http://"' + maxLitCount: "5" - name: argument-limit arguments: - 5 diff --git a/internal/acctest/acctest.go b/internal/acctest/acctest.go index 37e9141..5493152 100644 --- a/internal/acctest/acctest.go +++ b/internal/acctest/acctest.go @@ -2,6 +2,7 @@ package acctest import ( "context" + "errors" "fmt" "log" "os" @@ -37,31 +38,52 @@ import ( ) const ( - // Provider name for single configuration testing + // Provider name for single configuration testing. ProviderName = "aws" - // Provider name for alternate configuration testing + // Provider name for alternate configuration testing. ProviderNameAlternate = "awsalternate" - // Provider name for alternate account and alternate region configuration testing + // Provider name for alternate account and alternate region configuration testing. ProviderNameAlternateAccountAlternateRegion = "awsalternateaccountalternateregion" - // Provider name for alternate account and same region configuration testing + // Provider name for alternate account and same region configuration testing. ProviderNameAlternateAccountSameRegion = "awsalternateaccountsameregion" - // Provider name for same account and alternate region configuration testing + // Provider name for same account and alternate region configuration testing. ProviderNameSameAccountAlternateRegion = "awssameaccountalternateregion" - // Provider name for third configuration testing + // Provider name for third configuration testing. ProviderNameThird = "awsthird" ResourcePrefix = "tf-acc-test" ) +var ( + errCompileARNRegexp = errors.New("unable to compile ARN regexp") + errResourceNotFound = errors.New("not found") + errNoPrimaryInstance = errors.New("no primary instance") + errAttributeNotFound = errors.New("attribute not found") + errAttributeMismatch = errors.New("attribute mismatch") + errResourceIDMissing = errors.New("resource ID missing") + errDeletingResource = errors.New("error deleting resource") + errACMPCAActivate = errors.New("attempting to activate ACM PCA Certificate Authority") + errNoCertAuthorityID = errors.New("no ACM PCA Certificate Authority ID is set") + errEmptyCertAuthority = errors.New("empty ACM PCA Certificate Authority") + errNoVPCID = errors.New("no VPC ID is set") + errAccountIDIDNotSet = errors.New("account Id resource ID not set") + errIncorrectAccountID = errors.New("incorrect Account ID") + errExpectedNotNil = errors.New("expected to not be nil") + errAttributeNotGreater = errors.New("attribute is not greater") +) + const ( RFC3339RegexPattern = `^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])[Tt]([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?([Zz]|([+-]([01][0-9]|2[0-3]):[0-5][0-9]))$` regionRegexp = `[a-z]{2}(-[a-z]+)+-\d` accountIDRegexp = `(aws|aws-managed|\d{12})` + + errFmtAttributeWithDetail = "%w (%s): %w" + errFmtSentinelWithDetail = "%w: %s" ) // Skip implements a wrapper for (*testing.T).Skip() to prevent unused linting reports @@ -224,7 +246,7 @@ func PreCheck(t *testing.T) { }) } -// providerAccountID returns the account ID of an AWS provider +// providerAccountID returns the account ID of an AWS provider. func providerAccountID(provo *schema.Provider) string { if provo == nil { log.Print("[DEBUG] Unable to read account ID from test provider: empty provider") @@ -247,14 +269,14 @@ func CheckDestroyNoop(_ *terraform.State) error { return nil } -// CheckResourceAttrAccountID ensures the Terraform state exactly matches the account ID +// CheckResourceAttrAccountID ensures the Terraform state exactly matches the account ID. func CheckResourceAttrAccountID(resourceName, attributeName string) resource.TestCheckFunc { return func(s *terraform.State) error { return resource.TestCheckResourceAttr(resourceName, attributeName, AccountID())(s) } } -// CheckResourceAttrRegionalARN ensures the Terraform state exactly matches a formatted ARN with region +// CheckResourceAttrRegionalARN ensures the Terraform state exactly matches a formatted ARN with region. func CheckResourceAttrRegionalARN(resourceName, attributeName, arnService, arnResource string) resource.TestCheckFunc { return func(s *terraform.State) error { attributeValue := arn.ARN{ @@ -268,7 +290,7 @@ func CheckResourceAttrRegionalARN(resourceName, attributeName, arnService, arnRe } } -// CheckResourceAttrRegionalARNNoAccount ensures the Terraform state exactly matches a formatted ARN with region but without account ID +// CheckResourceAttrRegionalARNNoAccount ensures the Terraform state exactly matches a formatted ARN with region but without account ID. func CheckResourceAttrRegionalARNNoAccount(resourceName, attributeName, arnService, arnResource string) resource.TestCheckFunc { return func(s *terraform.State) error { attributeValue := arn.ARN{ @@ -281,7 +303,7 @@ func CheckResourceAttrRegionalARNNoAccount(resourceName, attributeName, arnServi } } -// CheckResourceAttrRegionalARNAccountID ensures the Terraform state exactly matches a formatted ARN with region and specific account ID +// CheckResourceAttrRegionalARNAccountID ensures the Terraform state exactly matches a formatted ARN with region and specific account ID. func CheckResourceAttrRegionalARNAccountID(resourceName, attributeName, arnService, accountID, arnResource string) resource.TestCheckFunc { return func(s *terraform.State) error { attributeValue := arn.ARN{ @@ -297,7 +319,7 @@ func CheckResourceAttrRegionalARNAccountID(resourceName, attributeName, arnServi // CheckResourceAttrRegionalHostnameService ensures the Terraform state exactly matches a service DNS hostname with region and partition DNS suffix // -// For example: ec2.us-west-2.amazonaws.com +// For example: ec2.us-west-2.amazonaws.com. func CheckResourceAttrRegionalHostnameService(resourceName, attributeName, serviceName string) resource.TestCheckFunc { return func(s *terraform.State) error { hostname := fmt.Sprintf("%s.%s.%s", serviceName, Region(), PartitionDNSSuffix()) @@ -306,14 +328,14 @@ func CheckResourceAttrRegionalHostnameService(resourceName, attributeName, servi } } -// MatchResourceAttrAccountID ensures the Terraform state regexp matches an account ID +// MatchResourceAttrAccountID ensures the Terraform state regexp matches an account ID. func MatchResourceAttrAccountID(resourceName, attributeName string) resource.TestCheckFunc { return func(s *terraform.State) error { return resource.TestMatchResourceAttr(resourceName, attributeName, regexp.MustCompile(`^\d{12}$`))(s) } } -// MatchResourceAttrRegionalARN ensures the Terraform state regexp matches a formatted ARN with region +// MatchResourceAttrRegionalARN ensures the Terraform state regexp matches a formatted ARN with region. func MatchResourceAttrRegionalARN(resourceName, attributeName, arnService string, arnResourceRegexp *regexp.Regexp) resource.TestCheckFunc { return func(s *terraform.State) error { arnRegexp := arn.ARN{ @@ -326,14 +348,14 @@ func MatchResourceAttrRegionalARN(resourceName, attributeName, arnService string attributeMatch, err := regexp.Compile(arnRegexp) if err != nil { - return fmt.Errorf("unable to compile ARN regexp (%s): %w", arnRegexp, err) + return fmt.Errorf(errFmtAttributeWithDetail, errCompileARNRegexp, arnRegexp, err) } return resource.TestMatchResourceAttr(resourceName, attributeName, attributeMatch)(s) } } -// MatchResourceAttrRegionalARNNoAccount ensures the Terraform state regexp matches a formatted ARN with region but without account ID +// MatchResourceAttrRegionalARNNoAccount ensures the Terraform state regexp matches a formatted ARN with region but without account ID. func MatchResourceAttrRegionalARNNoAccount(resourceName, attributeName, arnService string, arnResourceRegexp *regexp.Regexp) resource.TestCheckFunc { return func(s *terraform.State) error { arnRegexp := arn.ARN{ @@ -345,14 +367,14 @@ func MatchResourceAttrRegionalARNNoAccount(resourceName, attributeName, arnServi attributeMatch, err := regexp.Compile(arnRegexp) if err != nil { - return fmt.Errorf("unable to compile ARN regexp (%s): %s", arnRegexp, err) + return fmt.Errorf(errFmtAttributeWithDetail, errCompileARNRegexp, arnRegexp, err) } return resource.TestMatchResourceAttr(resourceName, attributeName, attributeMatch)(s) } } -// MatchResourceAttrRegionalARNAccountID ensures the Terraform state regexp matches a formatted ARN with region and specific account ID +// MatchResourceAttrRegionalARNAccountID ensures the Terraform state regexp matches a formatted ARN with region and specific account ID. func MatchResourceAttrRegionalARNAccountID(resourceName, attributeName, arnService, accountID string, arnResourceRegexp *regexp.Regexp) resource.TestCheckFunc { return func(s *terraform.State) error { arnRegexp := arn.ARN{ @@ -365,14 +387,14 @@ func MatchResourceAttrRegionalARNAccountID(resourceName, attributeName, arnServi attributeMatch, err := regexp.Compile(arnRegexp) if err != nil { - return fmt.Errorf("unable to compile ARN regexp (%s): %w", arnRegexp, err) + return fmt.Errorf(errFmtAttributeWithDetail, errCompileARNRegexp, arnRegexp, err) } return resource.TestMatchResourceAttr(resourceName, attributeName, attributeMatch)(s) } } -// MatchResourceAttrRegionalHostname ensures the Terraform state regexp matches a formatted DNS hostname with region and partition DNS suffix +// MatchResourceAttrRegionalHostname ensures the Terraform state regexp matches a formatted DNS hostname with region and partition DNS suffix. func MatchResourceAttrRegionalHostname(resourceName, attributeName, serviceName string, hostnamePrefixRegexp *regexp.Regexp) resource.TestCheckFunc { return func(s *terraform.State) error { hostnameRegexpPattern := fmt.Sprintf("%s\\.%s\\.%s\\.%s$", hostnamePrefixRegexp.String(), serviceName, Region(), PartitionDNSSuffix()) @@ -386,7 +408,7 @@ func MatchResourceAttrRegionalHostname(resourceName, attributeName, serviceName } } -// MatchResourceAttrGlobalHostname ensures the Terraform state regexp matches a formatted DNS hostname with partition DNS suffix and without region +// MatchResourceAttrGlobalHostname ensures the Terraform state regexp matches a formatted DNS hostname with partition DNS suffix and without region. func MatchResourceAttrGlobalHostname(resourceName, attributeName, serviceName string, hostnamePrefixRegexp *regexp.Regexp) resource.TestCheckFunc { return func(s *terraform.State) error { hostnameRegexpPattern := fmt.Sprintf("%s\\.%s\\.%s$", hostnamePrefixRegexp.String(), serviceName, PartitionDNSSuffix()) @@ -400,7 +422,7 @@ func MatchResourceAttrGlobalHostname(resourceName, attributeName, serviceName st } } -// CheckResourceAttrGlobalARN ensures the Terraform state exactly matches a formatted ARN without region +// CheckResourceAttrGlobalARN ensures the Terraform state exactly matches a formatted ARN without region. func CheckResourceAttrGlobalARN(resourceName, attributeName, arnService, arnResource string) resource.TestCheckFunc { return func(s *terraform.State) error { attributeValue := arn.ARN{ @@ -413,7 +435,7 @@ func CheckResourceAttrGlobalARN(resourceName, attributeName, arnService, arnReso } } -// CheckResourceAttrGlobalARNNoAccount ensures the Terraform state exactly matches a formatted ARN without region or account ID +// CheckResourceAttrGlobalARNNoAccount ensures the Terraform state exactly matches a formatted ARN without region or account ID. func CheckResourceAttrGlobalARNNoAccount(resourceName, attributeName, arnService, arnResource string) resource.TestCheckFunc { return func(s *terraform.State) error { attributeValue := arn.ARN{ @@ -425,7 +447,7 @@ func CheckResourceAttrGlobalARNNoAccount(resourceName, attributeName, arnService } } -// CheckResourceAttrGlobalARNAccountID ensures the Terraform state exactly matches a formatted ARN without region and with specific account ID +// CheckResourceAttrGlobalARNAccountID ensures the Terraform state exactly matches a formatted ARN without region and with specific account ID. func CheckResourceAttrGlobalARNAccountID(resourceName, attributeName, accountID, arnService, arnResource string) resource.TestCheckFunc { return func(s *terraform.State) error { attributeValue := arn.ARN{ @@ -438,7 +460,7 @@ func CheckResourceAttrGlobalARNAccountID(resourceName, attributeName, accountID, } } -// MatchResourceAttrGlobalARN ensures the Terraform state regexp matches a formatted ARN without region +// MatchResourceAttrGlobalARN ensures the Terraform state regexp matches a formatted ARN without region. func MatchResourceAttrGlobalARN(resourceName, attributeName, arnService string, arnResourceRegexp *regexp.Regexp) resource.TestCheckFunc { return func(s *terraform.State) error { arnRegexp := arn.ARN{ @@ -450,14 +472,14 @@ func MatchResourceAttrGlobalARN(resourceName, attributeName, arnService string, attributeMatch, err := regexp.Compile(arnRegexp) if err != nil { - return fmt.Errorf("unable to compile ARN regexp (%s): %w", arnRegexp, err) + return fmt.Errorf(errFmtAttributeWithDetail, errCompileARNRegexp, arnRegexp, err) } return resource.TestMatchResourceAttr(resourceName, attributeName, attributeMatch)(s) } } -// CheckResourceAttrRegionalARNIgnoreRegionAndAccount ensures the Terraform state exactly matches a formatted ARN with region without specifying the region or account +// CheckResourceAttrRegionalARNIgnoreRegionAndAccount ensures the Terraform state exactly matches a formatted ARN with region without specifying the region or account. func CheckResourceAttrRegionalARNIgnoreRegionAndAccount(resourceName, attributeName, arnService, arnResource string) resource.TestCheckFunc { return func(s *terraform.State) error { arnRegexp := arn.ARN{ @@ -470,14 +492,14 @@ func CheckResourceAttrRegionalARNIgnoreRegionAndAccount(resourceName, attributeN attributeMatch, err := regexp.Compile(arnRegexp) if err != nil { - return fmt.Errorf("unable to compile ARN regexp (%s): %w", arnRegexp, err) + return fmt.Errorf(errFmtAttributeWithDetail, errCompileARNRegexp, arnRegexp, err) } return resource.TestMatchResourceAttr(resourceName, attributeName, attributeMatch)(s) } } -// MatchResourceAttrGlobalARNNoAccount ensures the Terraform state regexp matches a formatted ARN without region or account ID +// MatchResourceAttrGlobalARNNoAccount ensures the Terraform state regexp matches a formatted ARN without region or account ID. func MatchResourceAttrGlobalARNNoAccount(resourceName, attributeName, arnService string, arnResourceRegexp *regexp.Regexp) resource.TestCheckFunc { return func(s *terraform.State) error { arnRegexp := arn.ARN{ @@ -488,7 +510,7 @@ func MatchResourceAttrGlobalARNNoAccount(resourceName, attributeName, arnService attributeMatch, err := regexp.Compile(arnRegexp) if err != nil { - return fmt.Errorf("unable to compile ARN regexp (%s): %s", arnRegexp, err) + return fmt.Errorf(errFmtAttributeWithDetail, errCompileARNRegexp, arnRegexp, err) } return resource.TestMatchResourceAttr(resourceName, attributeName, attributeMatch)(s) @@ -512,7 +534,7 @@ func CheckResourceAttrEquivalentJSON(resourceName, attributeName, expectedJSON s v, ok := is.Attributes[attributeName] if !ok { - return fmt.Errorf("%s: No attribute %q found", resourceName, attributeName) + return fmt.Errorf("%w: %s: %q", errAttributeNotFound, resourceName, attributeName) } vNormal, err := structure.NormalizeJsonString(v) @@ -526,29 +548,29 @@ func CheckResourceAttrEquivalentJSON(resourceName, attributeName, expectedJSON s } if vNormal != expectedNormal { - return fmt.Errorf("%s: Attribute %q expected\n%s\ngot\n%s", resourceName, attributeName, expectedJSON, v) + return fmt.Errorf("%w: %s: attribute %q expected\n%s\ngot\n%s", errAttributeMismatch, resourceName, attributeName, expectedJSON, v) } return nil } } -// Copied and inlined from the SDK testing code +// Copied and inlined from the SDK testing code. func PrimaryInstanceState(s *terraform.State, name string) (*terraform.InstanceState, error) { rs, ok := s.RootModule().Resources[name] if !ok { - return nil, fmt.Errorf("not found: %s", name) + return nil, fmt.Errorf(errFmtSentinelWithDetail, errResourceNotFound, name) } is := rs.Primary if is == nil { - return nil, fmt.Errorf("no primary instance: %s", name) + return nil, fmt.Errorf(errFmtSentinelWithDetail, errNoPrimaryInstance, name) } return is, nil } // AccountID returns the account ID of Provider -// Must be used within a resource.TestCheckFunc +// Must be used within a resource.TestCheckFunc. func AccountID() string { return providerAccountID(Provider) } @@ -813,7 +835,7 @@ provider "awsalternate" { `, os.Getenv(conns.EnvVarAlternateAccessKeyId), os.Getenv(conns.EnvVarAlternateProfile), os.Getenv(conns.EnvVarAlternateSecretAccessKey)) } -// Deprecated: Use ConfigMultipleRegionProvider instead +// Deprecated: Use ConfigMultipleRegionProvider instead. func ConfigAlternateRegionProvider() string { return ConfigNamedRegionalProvider(ProviderNameAlternate, AlternateRegion()) } @@ -960,14 +982,14 @@ func DeleteResource(resource *schema.Resource, d *schema.ResourceData, meta inte for i := range diags { if diags[i].Severity == diag.Error { - return fmt.Errorf("error deleting resource: %s", diags[i].Summary) + return fmt.Errorf(errFmtSentinelWithDetail, errDeletingResource, diags[i].Summary) } } return nil } - return resource.Delete(d, meta) + return resource.Delete(d, meta) //nolint:staticcheck // SA1019: deprecated test helper, kept for backwards compatibility } func CheckResourceDisappears(provo *schema.Provider, resource *schema.Resource, resourceName string) resource.TestCheckFunc { @@ -975,11 +997,11 @@ func CheckResourceDisappears(provo *schema.Provider, resource *schema.Resource, resourceState, ok := s.RootModule().Resources[resourceName] if !ok { - return fmt.Errorf("resource not found: %s", resourceName) + return fmt.Errorf(errFmtSentinelWithDetail, errResourceNotFound, resourceName) } if resourceState.Primary.ID == "" { - return fmt.Errorf("resource ID missing: %s", resourceName) + return fmt.Errorf(errFmtSentinelWithDetail, errResourceIDMissing, resourceName) } return DeleteResource(resource, resource.Data(resourceState.Primary), provo.Meta()) @@ -1003,7 +1025,7 @@ func CheckWithProviders(f func(*terraform.State, *schema.Provider) error, provid } } -// ErrorCheckSkipMessagesContaining skips tests based on error messages that indicate unsupported features +// ErrorCheckSkipMessagesContaining skips tests based on error messages that indicate unsupported features. func ErrorCheckSkipMessagesContaining(t *testing.T, messages ...string) resource.ErrorCheckFunc { return func(err error) error { if err == nil { @@ -1095,7 +1117,7 @@ func errorCheckCommon(err error) bool { } // Check service API call error for reasons to skip acceptance testing -// These include missing API endpoints and unsupported API calls +// These include missing API endpoints and unsupported API calls. func PreCheckSkipError(err error) bool { // GovCloud has endpoints that respond with (no message provided after the error code): // AccessDeniedException: @@ -1206,7 +1228,7 @@ data "aws_arn" "test" { } ` -// ConfigCompose can be called to concatenate multiple strings to build test configurations +// ConfigCompose can be called to concatenate multiple strings to build test configurations. func ConfigCompose(config ...string) string { var str strings.Builder @@ -1272,7 +1294,7 @@ func RandomDomain() domainName { const DefaultEmailAddress = "no-reply@hashicorp.com" // RandomEmailAddress generates a random email address in the form -// "tf-acc-test-@" +// "tf-acc-test-@". func RandomEmailAddress(domainName string) string { return fmt.Sprintf("%s@%s", sdkacctest.RandomWithPrefix(ResourcePrefix), domainName) } @@ -1300,7 +1322,7 @@ func PreCheckOutpostsOutposts(t *testing.T) { const ( // ACM domain names cannot be longer than 64 characters - // Other resources, e.g. Cognito User Pool Domains, limit this to 63 + // Other resources, e.g. Cognito User Pool Domains, limit this to 63. acmCertificateDomainMaxLen = 63 acmRandomSubDomainPrefix = "tf-acc-" @@ -1308,7 +1330,7 @@ const ( // Max length (63) // Subtract "tf-acc-" prefix (7) - // Subtract "." between prefix and root domain (1) + // Subtract "." between prefix and root domain (1). acmRandomSubDomainRemainderLen = acmCertificateDomainMaxLen - acmRandomSubDomainPrefixLen - 1 ) @@ -1337,7 +1359,7 @@ func ACMCertificateDomainFromEnv(t *testing.T) string { } // ACM domain names cannot be longer than 64 characters -// Other resources, e.g. Cognito User Pool Domains, limit this to 63 +// Other resources, e.g. Cognito User Pool Domains, limit this to 63. func ACMCertificateRandomSubDomain(rootDomain string) string { return fmt.Sprintf( acmRandomSubDomainPrefix+"%s.%s", @@ -1350,7 +1372,7 @@ func CheckACMPCACertificateAuthorityActivateRootCA(certificateAuthority *acmpca. conn := Provider.Meta().(*conns.AWSClient).ACMPCAConn if v := aws.StringValue(certificateAuthority.Type); v != acmpca.CertificateAuthorityTypeRoot { - return fmt.Errorf("attempting to activate ACM PCA %s Certificate Authority", v) + return fmt.Errorf(errFmtSentinelWithDetail, errACMPCAActivate, v) } arn := aws.StringValue(certificateAuthority.Arn) @@ -1411,7 +1433,7 @@ func CheckACMPCACertificateAuthorityActivateSubordinateCA(rootCertificateAuthori conn := Provider.Meta().(*conns.AWSClient).ACMPCAConn if v := aws.StringValue(certificateAuthority.Type); v != acmpca.CertificateAuthorityTypeSubordinate { - return fmt.Errorf("attempting to activate ACM PCA %s Certificate Authority", v) + return fmt.Errorf(errFmtSentinelWithDetail, errACMPCAActivate, v) } arn := aws.StringValue(certificateAuthority.Arn) @@ -1487,11 +1509,11 @@ func CheckACMPCACertificateAuthorityExists(n string, certificateAuthority *acmpc return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("not found: %s", n) + return fmt.Errorf(errFmtSentinelWithDetail, errResourceNotFound, n) } if rs.Primary.ID == "" { - return fmt.Errorf("no ACM PCA Certificate Authority ID is set") + return errNoCertAuthorityID } conn := Provider.Meta().(*conns.AWSClient).ACMPCAConn @@ -1506,7 +1528,7 @@ func CheckACMPCACertificateAuthorityExists(n string, certificateAuthority *acmpc } if output == nil || output.CertificateAuthority == nil { - return fmt.Errorf("empty ACM PCA Certificate Authority (%s)", rs.Primary.ID) + return fmt.Errorf("%w (%s)", errEmptyCertAuthority, rs.Primary.ID) } *certificateAuthority = *output.CertificateAuthority @@ -1874,11 +1896,11 @@ func CheckVPCExists(n string, v *ec2.Vpc) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("not found: %s", n) + return fmt.Errorf(errFmtSentinelWithDetail, errResourceNotFound, n) } if rs.Primary.ID == "" { - return fmt.Errorf("no VPC ID is set") + return errNoVPCID } conn := Provider.Meta().(*conns.AWSClient).EC2Conn @@ -1898,24 +1920,24 @@ func CheckCallerIdentityAccountID(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("can't find AccountID resource: %s", n) + return fmt.Errorf("%w: can't find AccountID resource: %s", errResourceNotFound, n) } if rs.Primary.ID == "" { - return fmt.Errorf("account Id resource ID not set.") + return errAccountIDIDNotSet } expected := Provider.Meta().(*conns.AWSClient).AccountID if rs.Primary.Attributes["account_id"] != expected { - return fmt.Errorf("incorrect Account ID: expected %q, got %q", expected, rs.Primary.Attributes["account_id"]) + return fmt.Errorf("%w: expected %q, got %q", errIncorrectAccountID, expected, rs.Primary.Attributes["account_id"]) } if rs.Primary.Attributes["user_id"] == "" { - return fmt.Errorf("user_id expected to not be nil") + return fmt.Errorf("%w: user_id", errExpectedNotNil) } if rs.Primary.Attributes["arn"] == "" { - return fmt.Errorf("attribute ARN expected to not be nil") + return fmt.Errorf("%w: attribute ARN", errExpectedNotNil) } return nil @@ -1926,15 +1948,15 @@ func CheckResourceAttrGreaterThanValue(n, key, value string) resource.TestCheckF return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("not found: %s", n) + return fmt.Errorf(errFmtSentinelWithDetail, errResourceNotFound, n) } - if v, ok := rs.Primary.Attributes[key]; !ok || !(v > value) { + if v, ok := rs.Primary.Attributes[key]; !ok || (v <= value) { if !ok { - return fmt.Errorf("%s: Attribute %q not found", n, key) + return fmt.Errorf("%w: %s: %q", errAttributeNotFound, n, key) } - return fmt.Errorf("%s: Attribute %q is not greater than %q, got %q", n, key, value, v) + return fmt.Errorf("%w: %s: attribute %q is not greater than %q, got %q", errAttributeNotGreater, n, key, value, v) } return nil diff --git a/internal/acctest/crypto.go b/internal/acctest/crypto.go index 02ae911..f36db1a 100644 --- a/internal/acctest/crypto.go +++ b/internal/acctest/crypto.go @@ -3,7 +3,7 @@ package acctest import ( "crypto/rand" "crypto/rsa" - "crypto/sha1" + "crypto/sha1" //nolint:gosec // G505: SHA-1 required for X.509 SubjectKeyIdentifier per RFC 5280 "crypto/x509" "crypto/x509/pkix" "encoding/pem" @@ -23,7 +23,7 @@ var tlsX509CertificateSerialNumberLimit = new(big.Int).Lsh(big.NewInt(1), 128) / // TLSRSAPrivateKeyPEM generates a RSA private key PEM string. // Wrap with TLSPEMEscapeNewlines() to allow simple fmt.Sprintf() -// configurations such as: private_key_pem = "%[1]s" +// configurations such as: private_key_pem = "%[1]s". func TLSRSAPrivateKeyPEM(bits int) string { key, err := rsa.GenerateKey(rand.Reader, bits) if err != nil { @@ -41,7 +41,7 @@ func TLSRSAPrivateKeyPEM(bits int) string { // TLSRSAPublicKeyPEM generates a RSA public key PEM string. // Wrap with TLSPEMEscapeNewlines() to allow simple fmt.Sprintf() -// configurations such as: public_key_pem = "%[1]s" +// configurations such as: public_key_pem = "%[1]s". func TLSRSAPublicKeyPEM(keyPem string) string { keyBlock, _ := pem.Decode([]byte(keyPem)) @@ -67,7 +67,7 @@ func TLSRSAPublicKeyPEM(keyPem string) string { // TLSRSAX509LocallySignedCertificatePEM generates a local CA x509 certificate PEM string. // Wrap with TLSPEMEscapeNewlines() to allow simple fmt.Sprintf() -// configurations such as: certificate_pem = "%[1]s" +// configurations such as: certificate_pem = "%[1]s". func TLSRSAX509LocallySignedCertificatePEM(caKeyPem, caCertificatePem, keyPem, commonName string) string { caCertificateBlock, _ := pem.Decode([]byte(caCertificatePem)) @@ -128,7 +128,7 @@ func TLSRSAX509LocallySignedCertificatePEM(caKeyPem, caCertificatePem, keyPem, c // TLSRSAX509SelfSignedCACertificatePEM generates a x509 CA certificate PEM string. // Wrap with TLSPEMEscapeNewlines() to allow simple fmt.Sprintf() -// configurations such as: root_certificate_pem = "%[1]s" +// configurations such as: root_certificate_pem = "%[1]s". func TLSRSAX509SelfSignedCACertificatePEM(keyPem string) string { keyBlock, _ := pem.Decode([]byte(keyPem)) @@ -144,7 +144,7 @@ func TLSRSAX509SelfSignedCACertificatePEM(keyPem string) string { panic(err) } - publicKeyBytesSha1 := sha1.Sum(publicKeyBytes) + publicKeyBytesSha1 := sha1.Sum(publicKeyBytes) //nolint:gosec // G401: SHA-1 required for X.509 SubjectKeyIdentifier per RFC 5280 serialNumber, err := rand.Int(rand.Reader, tlsX509CertificateSerialNumberLimit) if err != nil { @@ -185,7 +185,7 @@ func TLSRSAX509SelfSignedCACertificatePEM(keyPem string) string { // The CA certificate is suitable for use as an IAM RolesAnywhere Trust Anchor. // See https://docs.aws.amazon.com/rolesanywhere/latest/userguide/trust-model.html#signature-verification. // Wrap with TLSPEMEscapeNewlines() to allow simple fmt.Sprintf() -// configurations such as: root_certificate_pem = "%[1]s" +// configurations such as: root_certificate_pem = "%[1]s". func TLSRSAX509SelfSignedCACertificateForRolesAnywhereTrustAnchorPEM(keyPem string) string { keyBlock, _ := pem.Decode([]byte(keyPem)) @@ -201,7 +201,7 @@ func TLSRSAX509SelfSignedCACertificateForRolesAnywhereTrustAnchorPEM(keyPem stri panic(err) } - publicKeyBytesSha1 := sha1.Sum(publicKeyBytes) + publicKeyBytesSha1 := sha1.Sum(publicKeyBytes) //nolint:gosec // G401: SHA-1 required for X.509 SubjectKeyIdentifier per RFC 5280 serialNumber, err := rand.Int(rand.Reader, tlsX509CertificateSerialNumberLimit) if err != nil { @@ -241,7 +241,7 @@ func TLSRSAX509SelfSignedCACertificateForRolesAnywhereTrustAnchorPEM(keyPem stri // TLSRSAX509SelfSignedCertificatePEM generates a x509 certificate PEM string. // Wrap with TLSPEMEscapeNewlines() to allow simple fmt.Sprintf() -// configurations such as: private_key_pem = "%[1]s" +// configurations such as: private_key_pem = "%[1]s". func TLSRSAX509SelfSignedCertificatePEM(keyPem, commonName string) string { keyBlock, _ := pem.Decode([]byte(keyPem)) @@ -287,7 +287,7 @@ func TLSRSAX509SelfSignedCertificatePEM(keyPem, commonName string) string { // TLSRSAX509CertificateRequestPEM generates a x509 certificate request PEM string // and a RSA private key PEM string. // Wrap with TLSPEMEscapeNewlines() to allow simple fmt.Sprintf() -// configurations such as: certificate_signing_request_pem = "%[1]s" private_key_pem = "%[2]s" +// configurations such as: certificate_signing_request_pem = "%[1]s" private_key_pem = "%[2]s". func TLSRSAX509CertificateRequestPEM(keyBits int, commonName string) (string, string) { keyBytes, err := rsa.GenerateKey(rand.Reader, keyBits) if err != nil { diff --git a/internal/acctest/ec2_classic.go b/internal/acctest/ec2_classic.go index 1d0b3c2..560fcac 100644 --- a/internal/acctest/ec2_classic.go +++ b/internal/acctest/ec2_classic.go @@ -16,7 +16,7 @@ import ( ) const ( - // EC2-Classic region testing environment variable name + // EC2-Classic region testing environment variable name. ec2ClassicRegionEnvVar = "AWS_EC2_CLASSIC_REGION" ) @@ -28,10 +28,10 @@ const ( // PreCheckEC2Classic(t) must be called before using this provider instance. var ProviderEC2Classic *schema.Provider -// testAccProviderEc2ClassicConfigure ensures the provider is only configured once +// testAccProviderEc2ClassicConfigure ensures the provider is only configured once. var testAccProviderEc2ClassicConfigure sync.Once -// PreCheckEC2Classic verifies AWS credentials and that EC2-Classic is supported +// PreCheckEC2Classic verifies AWS credentials and that EC2-Classic is supported. func PreCheckEC2Classic(t *testing.T) { // Since we are outside the scope of the Terraform configuration we must // call Configure() to properly initialize the provider configuration. @@ -70,7 +70,7 @@ func ConfigEC2ClassicRegionProvider() string { return ConfigRegionalProvider(EC2ClassicRegion()) } -// EC2ClassicRegion returns the EC2-Classic region for testing +// EC2ClassicRegion returns the EC2-Classic region for testing. func EC2ClassicRegion() string { v := os.Getenv(ec2ClassicRegionEnvVar) @@ -85,7 +85,7 @@ func EC2ClassicRegion() string { return Region() } -// CheckResourceAttrRegionalARNEC2Classic ensures the Terraform state exactly matches a formatted ARN with EC2-Classic region +// CheckResourceAttrRegionalARNEC2Classic ensures the Terraform state exactly matches a formatted ARN with EC2-Classic region. func CheckResourceAttrRegionalARNEC2Classic(resourceName, attributeName, arnService, arnResource string) resource.TestCheckFunc { return func(s *terraform.State) error { attributeValue := arn.ARN{ diff --git a/internal/conns/config.go b/internal/conns/config.go index be6cd4a..72b6db7 100644 --- a/internal/conns/config.go +++ b/internal/conns/config.go @@ -81,7 +81,9 @@ type Config struct { UseFIPSEndpoint bool } -// Client configures and returns a fully initialized AWSClient +// Client configures and returns a fully initialized AWSClient. +// +//nolint:gocognit,revive,cyclop,funlen // wires up dozens of AWS service clients with their respective retry handlers and middleware; function length and complexity intentional func (c *Config) Client(ctx context.Context) (interface{}, diag.Diagnostics) { awsbaseConfig := awsbase.Config{ AccessKey: c.AccessKey, @@ -503,8 +505,7 @@ func (c *Config) Client(ctx context.Context) (interface{}, diag.Diagnostics) { // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/17996 client.SecurityHubConn.Handlers.Retry.PushBack(func(r *request.Request) { - switch r.Operation.Name { - case "EnableOrganizationAdminAccount": + if r.Operation.Name == "EnableOrganizationAdminAccount" { if tfawserr.ErrCodeEquals(r.Error, securityhub.ErrCodeResourceConflictException) { r.Retryable = aws.Bool(true) } diff --git a/internal/conns/conns.go b/internal/conns/conns.go index db4b21c..08beee3 100644 --- a/internal/conns/conns.go +++ b/internal/conns/conns.go @@ -1,7 +1,7 @@ package conns import ( - "fmt" + "errors" "strings" "github.com/aws/aws-sdk-go/aws" @@ -12,6 +12,8 @@ import ( awsbasev1 "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2" ) +var errNoEC2PlatformsDetected = errors.New("no EC2 platforms detected") + func NewSessionForRegion(cfg *aws.Config, region, terraformVersion string) (*session.Session, error) { session, err := session.NewSession(cfg) if err != nil { @@ -66,7 +68,7 @@ func GetSupportedEC2Platforms(conn *ec2.EC2) ([]string, error) { } if len(platforms) == 0 { - return nil, fmt.Errorf("no EC2 platforms detected") + return nil, errNoEC2PlatformsDetected } return platforms, nil diff --git a/internal/conns/envvar.go b/internal/conns/envvar.go index 7d07d95..72457a0 100644 --- a/internal/conns/envvar.go +++ b/internal/conns/envvar.go @@ -1,74 +1,80 @@ package conns import ( + "errors" "fmt" "os" "github.com/mitchellh/go-testing-interface" ) +var ( + errEnvVarRequiredOneOf = errors.New("at least one environment variable must be set") + errEnvVarRequired = errors.New("environment variable must be set") +) + // Standard AWS environment variables used in the Terraform AWS Provider testing. // These are not provided as constants in the AWS Go SDK currently. const ( // Default static credential identifier for tests (AWS Go SDK does not provide this as constant) - // See also AWS_SECRET_ACCESS_KEY and AWS_PROFILE + // See also AWS_SECRET_ACCESS_KEY and AWS_PROFILE. EnvVarAccessKeyId = "AWS_ACCESS_KEY_ID" // Container credentials endpoint - // See also AWS_ACCESS_KEY_ID and AWS_PROFILE + // See also AWS_ACCESS_KEY_ID and AWS_PROFILE. EnvVarContainerCredentialsFullURI = "AWS_CONTAINER_CREDENTIALS_FULL_URI" - // Default AWS region for tests (AWS Go SDK does not provide this as constant) + // Default AWS region for tests (AWS Go SDK does not provide this as constant). EnvVarDefaultRegion = "AWS_DEFAULT_REGION" - // Default AWS shared configuration profile for tests (AWS Go SDK does not provide this as constant) + // Default AWS shared configuration profile for tests (AWS Go SDK does not provide this as constant). EnvVarProfile = "AWS_PROFILE" // Default static credential value for tests (AWS Go SDK does not provide this as constant) - // See also AWS_ACCESS_KEY_ID and AWS_PROFILE + // See also AWS_ACCESS_KEY_ID and AWS_PROFILE. EnvVarSecretAccessKey = "AWS_SECRET_ACCESS_KEY" ) // Custom environment variables used in the Terraform AWS Provider testing. // Additions should also be documented in the Environment Variable Dictionary -// of the Maintainers Guide: docs/MAINTAINING.md +// of the Maintainers Guide: docs/MAINTAINING.md. const ( - // For tests using an alternate AWS account, the equivalent of AWS_ACCESS_KEY_ID for that account + // For tests using an alternate AWS account, the equivalent of AWS_ACCESS_KEY_ID for that account. EnvVarAlternateAccessKeyId = "AWS_ALTERNATE_ACCESS_KEY_ID" - // For tests using an alternate AWS account, the equivalent of AWS_PROFILE for that account + // For tests using an alternate AWS account, the equivalent of AWS_PROFILE for that account. EnvVarAlternateProfile = "AWS_ALTERNATE_PROFILE" - // For tests using an alternate AWS region, the equivalent of AWS_DEFAULT_REGION for that account + // For tests using an alternate AWS region, the equivalent of AWS_DEFAULT_REGION for that account. EnvVarAlternateRegion = "AWS_ALTERNATE_REGION" - // For tests using an alternate AWS account, the equivalent of AWS_SECRET_ACCESS_KEY for that account + // For tests using an alternate AWS account, the equivalent of AWS_SECRET_ACCESS_KEY for that account. EnvVarAlternateSecretAccessKey = "AWS_ALTERNATE_SECRET_ACCESS_KEY" - // For tests using a third AWS region, the equivalent of AWS_DEFAULT_REGION for that region + // For tests using a third AWS region, the equivalent of AWS_DEFAULT_REGION for that region. EnvVarThirdRegion = "AWS_THIRD_REGION" - // For tests requiring GitHub permissions + // For tests requiring GitHub permissions. EnvVarGithubToken = "GITHUB_TOKEN" // For tests requiring restricted IAM permissions, an existing IAM Role to assume - // An inline assume role policy is then used to deny actions for the test + // An inline assume role policy is then used to deny actions for the test. EnvVarAccAssumeRoleARN = "TF_ACC_ASSUME_ROLE_ARN" ) -// Custom environment variables used for assuming a role with resource sweepers +// Custom environment variables used for assuming a role with resource sweepers. const ( - // The ARN of the IAM Role to assume + // The ARN of the IAM Role to assume. EnvVarAssumeRoleARN = "TF_AWS_ASSUME_ROLE_ARN" // The duration in seconds the IAM role will be assumed. // Defaults to 1 hour (3600) instead of the SDK default of 15 minutes. EnvVarAssumeRoleDuration = "TF_AWS_ASSUME_ROLE_DURATION" - // An External ID to pass to the assumed role + // An External ID to pass to the assumed role. EnvVarAssumeRoleExternalID = "TF_AWS_ASSUME_ROLE_EXTERNAL_ID" - // A session name for the assumed role + // A session name for the assumed role. EnvVarAssumeRoleSessionName = "TF_AWS_ASSUME_ROLE_SESSION_NAME" ) @@ -95,7 +101,7 @@ func RequireOneOfEnvVar(names []string, usageMessage string) (string, string, er } } - return "", "", fmt.Errorf("at least one environment variable of %v must be set. Usage: %s", names, usageMessage) + return "", "", fmt.Errorf("%w: %v. Usage: %s", errEnvVarRequiredOneOf, names, usageMessage) } // RequireEnvVar verifies that an environment variable is non-empty or returns an error. @@ -103,7 +109,7 @@ func RequireEnvVar(name string, usageMessage string) (string, error) { value := os.Getenv(name) if value == "" { - return "", fmt.Errorf("environment variable %s must be set. Usage: %s", name, usageMessage) + return "", fmt.Errorf("%w: %s. Usage: %s", errEnvVarRequired, name, usageMessage) } return value, nil diff --git a/internal/conns/mutexkv.go b/internal/conns/mutexkv.go index e33c626..e310fd2 100644 --- a/internal/conns/mutexkv.go +++ b/internal/conns/mutexkv.go @@ -16,22 +16,22 @@ type MutexKV struct { store map[string]*sync.Mutex } -// Locks the mutex for the given key. Caller is responsible for calling Unlock -// for the same key +// Lock locks the mutex for the given key. Caller is responsible for calling +// Unlock for the same key. func (m *MutexKV) Lock(key string) { log.Printf("[DEBUG] Locking %q", key) m.get(key).Lock() log.Printf("[DEBUG] Locked %q", key) } -// Unlock the mutex for the given key. Caller must have called Lock for the same key first +// Unlock the mutex for the given key. Caller must have called Lock for the same key first. func (m *MutexKV) Unlock(key string) { log.Printf("[DEBUG] Unlocking %q", key) m.get(key).Unlock() log.Printf("[DEBUG] Unlocked %q", key) } -// Returns a mutex for the given key, no guarantee of its lock status +// get returns a mutex for the given key, with no guarantee of its lock status. func (m *MutexKV) get(key string) *sync.Mutex { m.lock.Lock() defer m.lock.Unlock() @@ -43,7 +43,7 @@ func (m *MutexKV) get(key string) *sync.Mutex { return mutex } -// Returns a properly initialized MutexKV +// NewMutexKV returns a properly initialized MutexKV. func NewMutexKV() *MutexKV { return &MutexKV{ store: make(map[string]*sync.Mutex), diff --git a/internal/create/attrmap.go b/internal/create/attrmap.go index 4caa628..3b82501 100644 --- a/internal/create/attrmap.go +++ b/internal/create/attrmap.go @@ -1,6 +1,7 @@ package create import ( + "errors" "fmt" "log" "strconv" @@ -8,6 +9,8 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) +var errUnsupportedAttributeType = errors.New("attribute is of unsupported type") + // AttributeMap represents a map of Terraform resource attribute name to AWS API attribute name. // Useful for SQS Queue or SNS Topic attribute handling. type attributeInfo struct { @@ -63,14 +66,14 @@ func (m AttributeMap) ApiAttributesToResourceData(apiAttributes map[string]strin case schema.TypeString: tfAttributeValue = v default: - return fmt.Errorf("attribute %s is of unsupported type: %d", tfAttributeName, t) + return fmt.Errorf("%w: %s (type %d)", errUnsupportedAttributeType, tfAttributeName, t) } if err := d.Set(tfAttributeName, tfAttributeValue); err != nil { return fmt.Errorf("error setting %s: %w", tfAttributeName, err) } - } else { - d.Set(tfAttributeName, nil) + } else if err := d.Set(tfAttributeName, nil); err != nil { + return fmt.Errorf("error setting %s: %w", tfAttributeName, err) } } @@ -98,7 +101,7 @@ func (m AttributeMap) ResourceDataToApiAttributesCreate(d *schema.ResourceData) case schema.TypeString: apiAttributeValue = v.(string) default: - return nil, fmt.Errorf("attribute %s is of unsupported type: %d", tfAttributeName, t) + return nil, fmt.Errorf("%w: %s (type %d)", errUnsupportedAttributeType, tfAttributeName, t) } if apiAttributeValue != "" { @@ -128,7 +131,7 @@ func (m AttributeMap) ResourceDataToApiAttributesUpdate(d *schema.ResourceData) case schema.TypeString: apiAttributeValue = v.(string) default: - return nil, fmt.Errorf("attribute %s is of unsupported type: %d", tfAttributeName, t) + return nil, fmt.Errorf("%w: %s (type %d)", errUnsupportedAttributeType, tfAttributeName, t) } apiAttributes[attributeInfo.apiAttributeName] = apiAttributeValue diff --git a/internal/create/hashcode.go b/internal/create/hashcode.go index d4f77ac..41e9f2c 100644 --- a/internal/create/hashcode.go +++ b/internal/create/hashcode.go @@ -6,8 +6,8 @@ import ( // StringHashcode hashes a string to a unique hashcode. // -// crc32 returns a uint32, but for our use we need -// and non negative integer. Here we cast to an integer +// crc32.ChecksumIEEE returns a uint32, but for our use we need +// a non-negative integer. Here we cast to an integer // and invert it if the result is negative. func StringHashcode(s string) int { v := int(crc32.ChecksumIEEE([]byte(s))) diff --git a/internal/create/naming.go b/internal/create/naming.go index b52ffc1..cf61eb6 100644 --- a/internal/create/naming.go +++ b/internal/create/naming.go @@ -8,13 +8,13 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -// Name returns in order the name if non-empty, a prefix generated name if non-empty, or fully generated name prefixed with terraform- +// Name returns in order the name if non-empty, a prefix generated name if non-empty, or fully generated name prefixed with terraform-. func Name(name string, namePrefix string) string { return NameWithSuffix(name, namePrefix, "") } // NameWithSuffix returns in order the name if non-empty, a prefix generated name if non-empty, or fully generated name prefixed with "terraform-". -// In the latter two cases, any suffix is appended to the generated name +// In the latter two cases, any suffix is appended to the generated name. func NameWithSuffix(name string, namePrefix string, nameSuffix string) string { if name != "" { return name @@ -27,12 +27,12 @@ func NameWithSuffix(name string, namePrefix string, nameSuffix string) string { return resource.UniqueId() + nameSuffix } -// HasResourceUniqueIdSuffix returns true if the string has the built-in unique ID suffix +// HasResourceUniqueIdSuffix returns true if the string has the built-in unique ID suffix. func HasResourceUniqueIdSuffix(s string) bool { return HasResourceUniqueIdPlusAdditionalSuffix(s, "") } -// HasResourceUniqueIdPlusAdditionalSuffix returns true if the string has the built-in unique ID suffix plus an additional suffix +// HasResourceUniqueIdPlusAdditionalSuffix returns true if the string has the built-in unique ID suffix plus an additional suffix. func HasResourceUniqueIdPlusAdditionalSuffix(s string, additionalSuffix string) bool { return resourceUniqueIDPlusAdditionalSuffixRegexp(additionalSuffix).MatchString(s) } @@ -65,30 +65,30 @@ func NamePrefixFromNameWithSuffix(name, nameSuffix string) *string { return &namePrefix } -// TestCheckResourceAttrNameFromPrefix verifies that the state attribute value matches name generated from given prefix +// TestCheckResourceAttrNameFromPrefix verifies that the state attribute value matches name generated from given prefix. func TestCheckResourceAttrNameFromPrefix(resourceName string, attributeName string, prefix string) resource.TestCheckFunc { return TestCheckResourceAttrNameWithSuffixFromPrefix(resourceName, attributeName, prefix, "") } -// TestCheckResourceAttrNameWithSuffixFromPrefix verifies that the state attribute value matches name with suffix generated from given prefix +// TestCheckResourceAttrNameWithSuffixFromPrefix verifies that the state attribute value matches name with suffix generated from given prefix. func TestCheckResourceAttrNameWithSuffixFromPrefix(resourceName string, attributeName string, prefix string, suffix string) resource.TestCheckFunc { return func(s *terraform.State) error { nameRegexpPattern := resourcePrefixedUniqueIDPlusAdditionalSuffixRegexpPattern(prefix, suffix) attributeMatch, err := regexp.Compile(nameRegexpPattern) if err != nil { - return fmt.Errorf("Unable to compile name regexp (%s): %w", nameRegexpPattern, err) + return fmt.Errorf("unable to compile name regexp (%s): %w", nameRegexpPattern, err) } return resource.TestMatchResourceAttr(resourceName, attributeName, attributeMatch)(s) } } -// TestCheckResourceAttrNameGenerated verifies that the state attribute value matches name automatically generated without prefix +// TestCheckResourceAttrNameGenerated verifies that the state attribute value matches name automatically generated without prefix. func TestCheckResourceAttrNameGenerated(resourceName string, attributeName string) resource.TestCheckFunc { return TestCheckResourceAttrNameWithSuffixGenerated(resourceName, attributeName, "") } -// TestCheckResourceAttrNameWithSuffixGenerated verifies that the state attribute value matches name with suffix automatically generated without prefix +// TestCheckResourceAttrNameWithSuffixGenerated verifies that the state attribute value matches name with suffix automatically generated without prefix. func TestCheckResourceAttrNameWithSuffixGenerated(resourceName string, attributeName string, suffix string) resource.TestCheckFunc { return func(s *terraform.State) error { return resource.TestMatchResourceAttr(resourceName, attributeName, resourceUniqueIDPrefixPlusAdditionalSuffixRegexp(suffix))(s) diff --git a/internal/experimental/nullable/bool.go b/internal/experimental/nullable/bool.go index 6141374..cbbaad2 100644 --- a/internal/experimental/nullable/bool.go +++ b/internal/experimental/nullable/bool.go @@ -1,12 +1,15 @@ package nullable import ( + "errors" "fmt" "strconv" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) +var errExpectedString = errors.New("expected type to be string") + const ( TypeNullableBool = schema.TypeString ) @@ -38,7 +41,7 @@ func NewBool(v bool) Bool { func ValidateTypeStringNullableBool(v interface{}, k string) (ws []string, es []error) { value, ok := v.(string) if !ok { - es = append(es, fmt.Errorf("expected type of %s to be string", k)) + es = append(es, fmt.Errorf("%w: %s", errExpectedString, k)) return ws, es } diff --git a/internal/experimental/nullable/int.go b/internal/experimental/nullable/int.go index 07e3446..7cd4782 100644 --- a/internal/experimental/nullable/int.go +++ b/internal/experimental/nullable/int.go @@ -1,12 +1,18 @@ package nullable import ( + "errors" "fmt" "strconv" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) +var ( + errIntAtLeast = errors.New("value below minimum") + errIntBetween = errors.New("value out of range") +) + const ( TypeNullableInt = schema.TypeString ) @@ -34,7 +40,7 @@ func (i Int) Value() (int64, bool, error) { func ValidateTypeStringNullableInt(v interface{}, k string) (ws []string, es []error) { value, ok := v.(string) if !ok { - es = append(es, fmt.Errorf("expected type of %s to be string", k)) + es = append(es, fmt.Errorf("%w: %s", errExpectedString, k)) return ws, es } @@ -51,11 +57,11 @@ func ValidateTypeStringNullableInt(v interface{}, k string) (ws []string, es []e // ValidateTypeStringNullableIntAtLeast provides custom error messaging for TypeString ints // Some arguments require an int value or unspecified, empty field. -func ValidateTypeStringNullableIntAtLeast(min int) schema.SchemaValidateFunc { +func ValidateTypeStringNullableIntAtLeast(min int) schema.SchemaValidateFunc { //nolint:staticcheck // SA1019: experimental helper preserves legacy validate signature return func(i interface{}, k string) (ws []string, es []error) { value, ok := i.(string) if !ok { - es = append(es, fmt.Errorf("expected type of %s to be string", k)) + es = append(es, fmt.Errorf("%w: %s", errExpectedString, k)) return ws, es } @@ -70,7 +76,7 @@ func ValidateTypeStringNullableIntAtLeast(min int) schema.SchemaValidateFunc { } if v < int64(min) { - es = append(es, fmt.Errorf("expected %s to be at least (%d), got %d", k, min, v)) + es = append(es, fmt.Errorf("%w: %s expected at least (%d), got %d", errIntAtLeast, k, min, v)) } return ws, es @@ -79,11 +85,11 @@ func ValidateTypeStringNullableIntAtLeast(min int) schema.SchemaValidateFunc { // ValidateTypeStringNullableIntBetween provides custom error messaging for TypeString ints // Some arguments require an int value or unspecified, empty field. -func ValidateTypeStringNullableIntBetween(min int, max int) schema.SchemaValidateFunc { +func ValidateTypeStringNullableIntBetween(min int, max int) schema.SchemaValidateFunc { //nolint:staticcheck // SA1019: experimental helper preserves legacy validate signature return func(i interface{}, k string) (ws []string, es []error) { value, ok := i.(string) if !ok { - es = append(es, fmt.Errorf("expected type of %s to be string", k)) + es = append(es, fmt.Errorf("%w: %s", errExpectedString, k)) return ws, es } @@ -98,7 +104,7 @@ func ValidateTypeStringNullableIntBetween(min int, max int) schema.SchemaValidat } if v < int64(min) || v > int64(max) { - es = append(es, fmt.Errorf("expected %s to be at between (%d) and (%d), got %d", k, min, max, v)) + es = append(es, fmt.Errorf("%w: %s expected between (%d) and (%d), got %d", errIntBetween, k, min, max, v)) } return ws, es diff --git a/internal/experimental/nullable/testing.go b/internal/experimental/nullable/testing.go index c94cba9..a6f03a5 100644 --- a/internal/experimental/nullable/testing.go +++ b/internal/experimental/nullable/testing.go @@ -9,7 +9,7 @@ import ( type testCase struct { val interface{} - f schema.SchemaValidateFunc + f schema.SchemaValidateFunc //nolint:staticcheck // SA1019: experimental test helper preserves legacy validate signature expectedErr *regexp.Regexp } diff --git a/internal/flex/flex.go b/internal/flex/flex.go index 696bf37..5c67c39 100644 --- a/internal/flex/flex.go +++ b/internal/flex/flex.go @@ -29,7 +29,7 @@ func Diff(slice1 []string, slice2 []string) []string { } // Takes the result of flatmap.Expand for an array of strings -// and returns a []*string +// and returns a []*string. func ExpandStringList(configured []interface{}) []*string { vs := make([]*string, 0, len(configured)) for _, v := range configured { @@ -43,7 +43,7 @@ func ExpandStringList(configured []interface{}) []*string { // Takes list of pointers to strings. Expand to an array // of raw strings and returns a []interface{} -// to keep compatibility w/ schema.NewSet +// to keep compatibility w/ schema.NewSet. func FlattenStringList(list []*string) []interface{} { vs := make([]interface{}, 0, len(list)) for _, v := range list { @@ -52,7 +52,7 @@ func FlattenStringList(list []*string) []interface{} { return vs } -// Expands a map of string to interface to a map of string to *string +// Expands a map of string to interface to a map of string to *string. func ExpandStringMap(m map[string]interface{}) map[string]*string { stringMap := make(map[string]*string, len(m)) for k, v := range m { @@ -61,7 +61,7 @@ func ExpandStringMap(m map[string]interface{}) map[string]*string { return stringMap } -// Takes a slice of pointers to string and returns a slice of strings +// Takes a slice of pointers to string and returns a slice of strings. func ExpandStringSliceofPointers(input []*string) []string { var output []string @@ -71,7 +71,7 @@ func ExpandStringSliceofPointers(input []*string) []string { return output } -// Takes the result of schema.Set of strings and returns a []*string +// Takes the result of schema.Set of strings and returns a []*string. func ExpandStringSet(configured *schema.Set) []*string { return ExpandStringList(configured.List()) // nosemgrep: helper-schema-Set-extraneous-ExpandStringList-with-List } @@ -80,7 +80,7 @@ func FlattenStringSet(list []*string) *schema.Set { return schema.NewSet(schema.HashString, FlattenStringList(list)) // nosemgrep: helper-schema-Set-extraneous-NewSet-with-FlattenStringList } -// Takes the result of schema.Set of strings and returns a []*int64 +// Takes the result of schema.Set of strings and returns a []*int64. func ExpandInt64Set(configured *schema.Set) []*int64 { return ExpandInt64List(configured.List()) } @@ -90,7 +90,7 @@ func FlattenInt64Set(list []*int64) *schema.Set { } // Takes the result of flatmap.Expand for an array of int64 -// and returns a []*int64 +// and returns a []*int64. func ExpandInt64List(configured []interface{}) []*int64 { vs := make([]*int64, 0, len(configured)) for _, v := range configured { @@ -101,7 +101,7 @@ func ExpandInt64List(configured []interface{}) []*int64 { // Takes list of pointers to int64s. Expand to an array // of raw ints and returns a []interface{} -// to keep compatibility w/ schema.NewSet +// to keep compatibility w/ schema.NewSet. func FlattenInt64List(list []*int64) []interface{} { vs := make([]interface{}, 0, len(list)) for _, v := range list { diff --git a/internal/provider/fwprovider/duration.go b/internal/provider/fwprovider/duration.go index 7d3a858..60a4689 100644 --- a/internal/provider/fwprovider/duration.go +++ b/internal/provider/fwprovider/duration.go @@ -3,6 +3,7 @@ package fwprovider import ( "context" + "errors" "fmt" "time" @@ -13,6 +14,8 @@ import ( "github.com/hashicorp/terraform-plugin-go/tftypes" ) +var errCannotApplyAttributePathStep = errors.New("cannot apply AttributePathStep") + type durationType uint8 const ( @@ -53,7 +56,7 @@ func (d durationType) Equal(o attr.Type) bool { // ApplyTerraform5AttributePathStep applies the given AttributePathStep to the // type. func (d durationType) ApplyTerraform5AttributePathStep(step tftypes.AttributePathStep) (interface{}, error) { - return nil, fmt.Errorf("cannot apply AttributePathStep %T to %s", step, d.String()) + return nil, fmt.Errorf("%w %T to %s", errCannotApplyAttributePathStep, step, d.String()) } // String returns a human-friendly description of the DurationType. diff --git a/internal/provider/fwprovider/duration_test.go b/internal/provider/fwprovider/duration_test.go index f523ab9..5c23094 100644 --- a/internal/provider/fwprovider/duration_test.go +++ b/internal/provider/fwprovider/duration_test.go @@ -42,6 +42,7 @@ func TestDurationTypeValueFromTerraform(t *testing.T) { for name, test := range tests { name, test := name, test t.Run(name, func(t *testing.T) { + t.Parallel() ctx := context.Background() val, err := fwprovider.DurationType.ValueFromTerraform(ctx, test.val) @@ -89,6 +90,7 @@ func TestDurationTypeValidate(t *testing.T) { for name, test := range tests { name, test := name, test t.Run(name, func(t *testing.T) { + t.Parallel() ctx := context.Background() diags := fwprovider.DurationType.Validate(ctx, test.val, path.Root("test")) diff --git a/internal/provider/fwprovider/provider.go b/internal/provider/fwprovider/provider.go index a5df6ad..81ae8dc 100644 --- a/internal/provider/fwprovider/provider.go +++ b/internal/provider/fwprovider/provider.go @@ -292,7 +292,7 @@ func (p *fwprovider) GetSchema(ctx context.Context) (tfsdk.Schema, diag.Diagnost // Configure is called at the beginning of the provider lifecycle, when // Terraform sends to the provider the values the user specified in the // provider configuration block. -func (p *fwprovider) Configure(ctx context.Context, request provider.ConfigureRequest, response *provider.ConfigureResponse) { +func (p *fwprovider) Configure(ctx context.Context, request provider.ConfigureRequest, response *provider.ConfigureResponse) { //nolint:gocritic // hugeParam: signature required by provider.Provider interface // Provider's parsed configuration (its instance state) is available through the primary provider's Meta() method. } diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 32ced46..0712335 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -26,6 +26,13 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) +const ( + assumeRoleDurationMinSeconds = 900 + assumeRoleDurationMaxSeconds = 43200 + externalIDMaxLength = 1224 + webIdentityTokenMaxLength = 20000 +) + // New returns a new, initialized Terraform Plugin SDK v2-style provider instance. // The provider instance is fully configured once the `ConfigureContextFunc` has been called. func New(_ context.Context) (*schema.Provider, error) { @@ -380,7 +387,7 @@ func assumeRoleSchema() *schema.Schema { Optional: true, Deprecated: "Use assume_role.duration instead", Description: "The duration, in seconds, of the role session.", - ValidateFunc: validation.IntBetween(900, 43200), + ValidateFunc: validation.IntBetween(assumeRoleDurationMinSeconds, assumeRoleDurationMaxSeconds), ConflictsWith: []string{"assume_role.0.duration"}, }, "external_id": { @@ -388,7 +395,7 @@ func assumeRoleSchema() *schema.Schema { Optional: true, Description: "A unique identifier that might be required when you assume a role in another account.", ValidateFunc: validation.All( - validation.StringLenBetween(2, 1224), + validation.StringLenBetween(2, externalIDMaxLength), validation.StringMatch(regexp.MustCompile(`[\w+=,.@:\/\-]*`), ""), ), }, @@ -479,7 +486,7 @@ func assumeRoleWithWebIdentitySchema() *schema.Schema { "web_identity_token": { Type: schema.TypeString, Optional: true, - ValidateFunc: validation.StringLenBetween(4, 20000), + ValidateFunc: validation.StringLenBetween(4, webIdentityTokenMaxLength), ExactlyOneOf: []string{"assume_role_with_web_identity.0.web_identity_token", "assume_role_with_web_identity.0.web_identity_token_file"}, }, "web_identity_token_file": { diff --git a/internal/provider/provider_test.go b/internal/provider/provider_test.go index 2b54402..2d5a2dd 100644 --- a/internal/provider/provider_test.go +++ b/internal/provider/provider_test.go @@ -87,7 +87,7 @@ func TestProviderConfig(t *testing.T) { } rd := schema.TestResourceDataRaw(t, ds.Schema, map[string]interface{}{}) - d := ds.Read(rd, meta) + d := ds.Read(rd, meta) //nolint:staticcheck // SA1019: test directly invokes deprecated Read for legacy data source if d != nil { t.Fatalf("Failed to read caller identity: %v", d) } diff --git a/internal/provider/validate.go b/internal/provider/validate.go index d446a07..5af9e0c 100644 --- a/internal/provider/validate.go +++ b/internal/provider/validate.go @@ -1,6 +1,7 @@ package provider import ( + "errors" "fmt" "regexp" "time" @@ -8,20 +9,27 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) +const ( + assumeRoleDurationMinMinutes = 15 + assumeRoleDurationMaxHours = 12 +) + +var errInvalidAssumeRoleDuration = errors.New("duration must be between 15 minutes (15m) and 12 hours (12h), inclusive") + // validAssumeRoleDuration validates a string can be parsed as a valid time.Duration -// and is within a minimum of 15 minutes and maximum of 12 hours -func validAssumeRoleDuration(v interface{}, k string) (ws []string, errors []error) { +// and is within a minimum of 15 minutes and maximum of 12 hours. +func validAssumeRoleDuration(v interface{}, k string) (ws []string, errs []error) { duration, err := time.ParseDuration(v.(string)) if err != nil { - errors = append(errors, fmt.Errorf("%q cannot be parsed as a duration: %w", k, err)) - return ws, errors + errs = append(errs, fmt.Errorf("%q cannot be parsed as a duration: %w", k, err)) + return ws, errs } - if duration.Minutes() < 15 || duration.Hours() > 12 { - errors = append(errors, fmt.Errorf("duration %q must be between 15 minutes (15m) and 12 hours (12h), inclusive", k)) + if duration.Minutes() < assumeRoleDurationMinMinutes || duration.Hours() > assumeRoleDurationMaxHours { + errs = append(errs, fmt.Errorf("%w: %q", errInvalidAssumeRoleDuration, k)) } - return ws, errors + return ws, errs } var validAssumeRoleSessionName = validation.All( diff --git a/internal/service/ec2/find.go b/internal/service/ec2/find.go index 7c04520..a6e036b 100644 --- a/internal/service/ec2/find.go +++ b/internal/service/ec2/find.go @@ -2,6 +2,7 @@ package ec2 import ( "context" + "errors" "fmt" "strconv" @@ -13,6 +14,11 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) +var ( + errNotFound = errors.New("not found") + errUnsupportedVPCAttribute = errors.New("unsupported VPC attribute") +) + func FindAvailabilityZones(conn *ec2.EC2, input *ec2.DescribeAvailabilityZonesInput) ([]*ec2.AvailabilityZone, error) { output, err := conn.DescribeAvailabilityZones(input) if err != nil { @@ -799,7 +805,7 @@ func FindImageLaunchPermissionsByID(ctx context.Context, conn *ec2.EC2, id strin return output.LaunchPermissions, nil } -func FindImageLaunchPermission(ctx context.Context, conn *ec2.EC2, imageID, accountID, group, organizationARN, organizationalUnitARN string) (*ec2.LaunchPermission, error) { +func FindImageLaunchPermission(ctx context.Context, conn *ec2.EC2, imageID, accountID, group, organizationARN, organizationalUnitARN string) (*ec2.LaunchPermission, error) { //nolint:revive // argument-limit: function signature mirrors AWS SDK shape output, err := FindImageLaunchPermissionsByID(ctx, conn, imageID) if err != nil { return nil, err @@ -1406,7 +1412,7 @@ func FindNetworkInterfaceSecurityGroup(conn *ec2.EC2, networkInterfaceID string, } return nil, &resource.NotFoundError{ - LastError: fmt.Errorf("Network Interface (%s) Security Group (%s) not found", networkInterfaceID, securityGroupID), + LastError: fmt.Errorf("network interface (%s) security group (%s): %w", networkInterfaceID, securityGroupID, errNotFound), } } @@ -1639,7 +1645,7 @@ func FindRouteByIPv4Destination(conn *ec2.EC2, routeTableID, destinationCidr str } return nil, &resource.NotFoundError{ - LastError: fmt.Errorf("Route in Route Table (%s) with IPv4 destination (%s) not found", routeTableID, destinationCidr), + LastError: fmt.Errorf("route in route table (%s) with IPv4 destination (%s): %w", routeTableID, destinationCidr, errNotFound), } } @@ -1658,7 +1664,7 @@ func FindRouteByIPv6Destination(conn *ec2.EC2, routeTableID, destinationIpv6Cidr } return nil, &resource.NotFoundError{ - LastError: fmt.Errorf("Route in Route Table (%s) with IPv6 destination (%s) not found", routeTableID, destinationIpv6Cidr), + LastError: fmt.Errorf("route in route table (%s) with IPv6 destination (%s): %w", routeTableID, destinationIpv6Cidr, errNotFound), } } @@ -1677,7 +1683,7 @@ func FindRouteByPrefixListIDDestination(conn *ec2.EC2, routeTableID, prefixListI } return nil, &resource.NotFoundError{ - LastError: fmt.Errorf("Route in Route Table (%s) with Prefix List ID destination (%s) not found", routeTableID, prefixListID), + LastError: fmt.Errorf("route in route table (%s) with prefix list ID destination (%s): %w", routeTableID, prefixListID, errNotFound), } } @@ -2144,7 +2150,7 @@ func FindVPCAttribute(conn *ec2.EC2, vpcID string, attribute string) (bool, erro case ec2.VpcAttributeNameEnableDnsSupport: v = output.EnableDnsSupport default: - return false, fmt.Errorf("unsupported VPC attribute: %s", attribute) + return false, fmt.Errorf("%w: %s", errUnsupportedVPCAttribute, attribute) } if v == nil { @@ -2307,7 +2313,7 @@ func FindVPCDHCPOptionsAssociation(conn *ec2.EC2, vpcID string, dhcpOptionsID st if aws.StringValue(vpc.DhcpOptionsId) != dhcpOptionsID { return &resource.NotFoundError{ - LastError: fmt.Errorf("EC2 VPC (%s) DHCP Options Set (%s) Association not found", vpcID, dhcpOptionsID), + LastError: fmt.Errorf("EC2 VPC (%s) DHCP options set (%s) association: %w", vpcID, dhcpOptionsID, errNotFound), } } @@ -2609,7 +2615,7 @@ func FindVPCEndpointServicePermissionExists(conn *ec2.EC2, serviceID, principalA } return &resource.NotFoundError{ - LastError: fmt.Errorf("VPC Endpoint Service (%s) Principal (%s) not found", serviceID, principalARN), + LastError: fmt.Errorf("VPC endpoint service (%s) principal (%s): %w", serviceID, principalARN, errNotFound), } } @@ -2627,7 +2633,7 @@ func FindVPCEndpointRouteTableAssociationExists(conn *ec2.EC2, vpcEndpointID str } return &resource.NotFoundError{ - LastError: fmt.Errorf("VPC Endpoint (%s) Route Table (%s) Association not found", vpcEndpointID, routeTableID), + LastError: fmt.Errorf("VPC endpoint (%s) route table (%s) association: %w", vpcEndpointID, routeTableID, errNotFound), } } @@ -2645,7 +2651,7 @@ func FindVPCEndpointSecurityGroupAssociationExists(conn *ec2.EC2, vpcEndpointID, } return &resource.NotFoundError{ - LastError: fmt.Errorf("VPC Endpoint (%s) Security Group (%s) Association not found", vpcEndpointID, securityGroupID), + LastError: fmt.Errorf("VPC endpoint (%s) security group (%s) association: %w", vpcEndpointID, securityGroupID, errNotFound), } } @@ -2663,7 +2669,7 @@ func FindVPCEndpointSubnetAssociationExists(conn *ec2.EC2, vpcEndpointID string, } return &resource.NotFoundError{ - LastError: fmt.Errorf("VPC Endpoint (%s) Subnet (%s) Association not found", vpcEndpointID, subnetID), + LastError: fmt.Errorf("VPC endpoint (%s) subnet (%s) association: %w", vpcEndpointID, subnetID, errNotFound), } } @@ -2761,7 +2767,7 @@ func FindVPNGatewayRoutePropagationExists(conn *ec2.EC2, routeTableID, gatewayID } return &resource.NotFoundError{ - LastError: fmt.Errorf("Route Table (%s) VPN Gateway (%s) route propagation not found", routeTableID, gatewayID), + LastError: fmt.Errorf("route table (%s) VPN gateway (%s) route propagation: %w", routeTableID, gatewayID, errNotFound), } } @@ -2963,7 +2969,7 @@ func FindVPNConnectionRouteByVPNConnectionIDAndCIDR(conn *ec2.EC2, vpnConnection } return nil, &resource.NotFoundError{ - LastError: fmt.Errorf("EC2 VPN Connection (%s) Route (%s) not found", vpnConnectionID, cidrBlock), + LastError: fmt.Errorf("EC2 VPN connection (%s) route (%s): %w", vpnConnectionID, cidrBlock, errNotFound), } } diff --git a/internal/service/guardduty/resource_guardduty_organization_settings.go b/internal/service/guardduty/resource_guardduty_organization_settings.go index 7bed553..6865cdd 100644 --- a/internal/service/guardduty/resource_guardduty_organization_settings.go +++ b/internal/service/guardduty/resource_guardduty_organization_settings.go @@ -1,6 +1,7 @@ package guardduty import ( + "errors" "fmt" "github.com/aws/aws-sdk-go/aws" @@ -12,6 +13,11 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) +var ( + errGDDesignatingMembers = errors.New("error designating guardduty administrator account members") + errGDRemovingMembers = errors.New("error removing guardduty administrator account members") +) + func ResourceAwsUtilsGuardDutyOrganizationSettings() *schema.Resource { return &schema.Resource{ Description: `Enables a list of accounts as GuardDuty member accounts in an existing AWS Organization. @@ -83,14 +89,14 @@ func resourceAwsGuardDutyOrganizationSettingsUpdate(d *schema.ResourceData, meta membersToAdd := flex.Diff(newExpanded, oldExpanded) if len(membersToAdd) > 0 { if err := addGuardDutyOrganizationMembers(conn, detectorID, membersToAdd); err != nil { - return fmt.Errorf("error setting guardduty organization members: %s", err) + return fmt.Errorf("error setting guardduty organization members: %w", err) } } membersToRemove := flex.Diff(oldExpanded, newExpanded) if len(membersToRemove) > 0 { if err := removeGuardDutyOrganizationMembers(conn, detectorID, membersToRemove); err != nil { - return fmt.Errorf("error removing guardduty organization members: %s", err) + return fmt.Errorf("error removing guardduty organization members: %w", err) } } } @@ -103,7 +109,7 @@ func resourceAwsGuardDutyOrganizationSettingsDelete(d *schema.ResourceData, meta membersToRemove := getMemberAccounts(d) if err := removeGuardDutyOrganizationMembers(conn, detectorID, membersToRemove); err != nil { - return fmt.Errorf("error removing guardduty organization members: %s", err) + return fmt.Errorf("error removing guardduty organization members: %w", err) } return nil } @@ -138,9 +144,9 @@ func addGuardDutyOrganizationMembers(conn *guardduty.GuardDuty, detectorID strin if result, err := conn.CreateMembers(createMembersInput); err != nil || len(result.UnprocessedAccounts) > 0 { if err != nil { - return fmt.Errorf("error designating guardduty administrator account members: %s", err) + return fmt.Errorf("error designating guardduty administrator account members: %w", err) } - return fmt.Errorf("error designating guardduty administrator account members: %s", result.UnprocessedAccounts) + return fmt.Errorf("%w: %v", errGDDesignatingMembers, result.UnprocessedAccounts) } } return nil @@ -160,16 +166,14 @@ func removeGuardDutyOrganizationMembers(conn *guardduty.GuardDuty, detectorID st } if _, err := conn.DisassociateMembers(disassociateMembersInput); err != nil { - if err != nil { - return fmt.Errorf("error disassociating guardduty administrator account members: %s", err) - } + return fmt.Errorf("error disassociating guardduty administrator account members: %w", err) } if result, err := conn.DeleteMembers(deleteMembersInput); err != nil || len(result.UnprocessedAccounts) > 0 { if err != nil { - return fmt.Errorf("error removing guardduty administrator account members: %s", err) + return fmt.Errorf("error removing guardduty administrator account members: %w", err) } - return fmt.Errorf("error removing guardduty administrator account members: %s", result.UnprocessedAccounts) + return fmt.Errorf("%w: %v", errGDRemovingMembers, result.UnprocessedAccounts) } } return nil diff --git a/internal/service/iam/access_key.go b/internal/service/iam/access_key.go index ead1860..4a43bf0 100644 --- a/internal/service/iam/access_key.go +++ b/internal/service/iam/access_key.go @@ -5,7 +5,9 @@ import ( "crypto/hmac" "crypto/sha256" "encoding/base64" + "errors" "fmt" + "log" "math" "time" @@ -18,6 +20,11 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) +var ( + errEmptyGetAccessKeyLastUsedResponse = errors.New("error fetching IAM Access Key username via GetAccessKeyLastUsed: empty response") + errMissingSecretAccessKey = errors.New("CreateAccessKey response did not contain a Secret Access Key as expected") +) + func ResourceExpiringAccessKey() *schema.Resource { return &schema.Resource{ Description: `Provides an IAM access key that expires after max_age seconds. This is a set of credentials that allow API requests to be made as an IAM user.`, @@ -45,10 +52,12 @@ func ResourceExpiringAccessKey() *schema.Resource { } if output == nil || output.UserName == nil { - return nil, fmt.Errorf("error fetching IAM Access Key (%s) username via GetAccessKeyLastUsed: empty response", d.Id()) + return nil, fmt.Errorf("%w: %s", errEmptyGetAccessKeyLastUsedResponse, d.Id()) } - d.Set("user", output.UserName) + if err := d.Set("user", output.UserName); err != nil { + return nil, fmt.Errorf("error setting user: %w", err) + } return []*schema.ResourceData{d}, nil }, @@ -121,11 +130,13 @@ func resourceAccessKeyDiff(ctx context.Context, d *schema.ResourceDiff, meta int now := time.Now().UTC() rotationTimestamp, err := time.Parse(time.RFC3339, v.(string)) if err != nil { - return fmt.Errorf("error parsing expiration_date (%s): %s", v.(string), err) + return fmt.Errorf("error parsing expiration_date (%s): %w", v.(string), err) } if now.After(rotationTimestamp) { - d.SetNewComputed("expiration_date") + if err := d.SetNewComputed("expiration_date"); err != nil { + return fmt.Errorf("error setting expiration_date as new computed: %w", err) + } } } return nil @@ -141,50 +152,72 @@ func resourceAccessKeyCreate(d *schema.ResourceData, meta interface{}) error { createResp, err := conn.CreateAccessKey(request) if err != nil { return fmt.Errorf( - "Error creating access key for user %s: %s", + "error creating access key for user %s: %w", *request.UserName, err, ) } + if createResp.AccessKey == nil || createResp.AccessKey.SecretAccessKey == nil { + return errMissingSecretAccessKey + } + d.SetId(aws.StringValue(createResp.AccessKey.AccessKeyId)) - if createResp.AccessKey == nil || createResp.AccessKey.SecretAccessKey == nil { - return fmt.Errorf("CreateAccessKey response did not contain a Secret Access Key as expected") + // cleanupOnError attempts a best-effort delete of the just-created access + // key when a post-create step fails. The original error is always returned; + // any deletion error is logged but swallowed so the caller still sees the + // actionable failure. + cleanupOnError := func(origErr error) error { + _, delErr := conn.DeleteAccessKey(&iam.DeleteAccessKeyInput{ + AccessKeyId: createResp.AccessKey.AccessKeyId, + UserName: request.UserName, + }) + if delErr != nil { + log.Printf("[WARN] failed to clean up IAM access key %s after post-create error: %s", + aws.StringValue(createResp.AccessKey.AccessKeyId), delErr) + } + return origErr } sesSMTPPasswordV4, err := SessmTPPasswordFromSecretKeySigV4(createResp.AccessKey.SecretAccessKey, meta.(*conns.AWSClient).Region) if err != nil { - return fmt.Errorf("error getting SES SigV4 SMTP Password from Secret Access Key: %s", err) + return cleanupOnError(fmt.Errorf("error getting SES SigV4 SMTP Password from Secret Access Key: %w", err)) } if v, ok := d.GetOk("pgp_key"); ok { pgpKey := v.(string) encryptionKey, err := RetrieveGPGKey(pgpKey) if err != nil { - return err + return cleanupOnError(err) } fingerprint, encrypted, err := EncryptValue(encryptionKey, *createResp.AccessKey.SecretAccessKey, "IAM Access Key Secret") if err != nil { - return err + return cleanupOnError(err) } - d.Set("key_fingerprint", fingerprint) - d.Set("encrypted_secret", encrypted) + if err := d.Set("key_fingerprint", fingerprint); err != nil { + return cleanupOnError(fmt.Errorf("error setting key_fingerprint: %w", err)) + } + if err := d.Set("encrypted_secret", encrypted); err != nil { + return cleanupOnError(fmt.Errorf("error setting encrypted_secret: %w", err)) + } _, encrypted, err = EncryptValue(encryptionKey, sesSMTPPasswordV4, "SES SMTP password") if err != nil { - return err + return cleanupOnError(err) } - d.Set("encrypted_ses_smtp_password_v4", encrypted) + if err := d.Set("encrypted_ses_smtp_password_v4", encrypted); err != nil { + return cleanupOnError(fmt.Errorf("error setting encrypted_ses_smtp_password_v4: %w", err)) + } } else { if err := d.Set("secret", createResp.AccessKey.SecretAccessKey); err != nil { - return err + return cleanupOnError(err) } if err := d.Set("ses_smtp_password_v4", sesSMTPPasswordV4); err != nil { - return err + return cleanupOnError(err) } } @@ -225,7 +258,7 @@ func resourceAccessKeyRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - return fmt.Errorf("Error reading IAM access key: %s", err) + return fmt.Errorf("error reading IAM access key: %w", err) } for _, key := range getResp.AccessKeyMetadata { @@ -246,15 +279,27 @@ func resourceAccessKeyReadResult(d *schema.ResourceData, key *iam.AccessKeyMetad createDate := key.CreateDate expirationDate := createDate.Add(time.Duration(d.Get("max_age").(int)) * time.Second) - d.Set("create_date", aws.TimeValue(createDate).Format(time.RFC3339)) - d.Set("expiration_date", expirationDate.Format(time.RFC3339)) + if err := d.Set("create_date", aws.TimeValue(createDate).Format(time.RFC3339)); err != nil { + return fmt.Errorf("error setting create_date: %w", err) + } + if err := d.Set("expiration_date", expirationDate.Format(time.RFC3339)); err != nil { + return fmt.Errorf("error setting expiration_date: %w", err) + } } else { - d.Set("create_date", nil) - d.Set("expiration_date", nil) + if err := d.Set("create_date", nil); err != nil { + return fmt.Errorf("error setting create_date: %w", err) + } + if err := d.Set("expiration_date", nil); err != nil { + return fmt.Errorf("error setting expiration_date: %w", err) + } } - d.Set("status", key.Status) - d.Set("user", key.UserName) + if err := d.Set("status", key.Status); err != nil { + return fmt.Errorf("error setting status: %w", err) + } + if err := d.Set("user", key.UserName); err != nil { + return fmt.Errorf("error setting user: %w", err) + } return nil } @@ -280,7 +325,7 @@ func resourceAccessKeyDelete(d *schema.ResourceData, meta interface{}) error { } if _, err := conn.DeleteAccessKey(request); err != nil { - return fmt.Errorf("Error deleting access key %s: %s", d.Id(), err) + return fmt.Errorf("error deleting access key %s: %w", d.Id(), err) } return nil } @@ -293,7 +338,7 @@ func resourceAccessKeyStatusUpdate(conn *iam.IAM, d *schema.ResourceData) error } if _, err := conn.UpdateAccessKey(request); err != nil { - return fmt.Errorf("Error updating access key %s: %s", d.Id(), err) + return fmt.Errorf("error updating access key %s: %w", d.Id(), err) } return nil } diff --git a/internal/service/iam/encryption.go b/internal/service/iam/encryption.go index 7691e8b..3975ce7 100644 --- a/internal/service/iam/encryption.go +++ b/internal/service/iam/encryption.go @@ -10,7 +10,7 @@ import ( // RetrieveGPGKey returns the PGP key specified as the pgpKey parameter, or queries // the public key from the keybase service if the parameter is a keybase username -// prefixed with the phrase "keybase:" +// prefixed with the phrase "keybase:". func RetrieveGPGKey(pgpKey string) (string, error) { const keybasePrefix = "keybase:" @@ -18,7 +18,7 @@ func RetrieveGPGKey(pgpKey string) (string, error) { if strings.HasPrefix(pgpKey, keybasePrefix) { publicKeys, err := pgpkeys.FetchKeybasePubkeys([]string{pgpKey}) if err != nil { - return "", fmt.Errorf("Error retrieving Public Key for %s: %w", pgpKey, err) + return "", fmt.Errorf("error retrieving Public Key for %s: %w", pgpKey, err) } encryptionKey = publicKeys[pgpKey] } @@ -31,7 +31,7 @@ func RetrieveGPGKey(pgpKey string) (string, error) { func EncryptValue(encryptionKey, value, description string) (string, string, error) { fingerprints, encryptedValue, err := pgpkeys.EncryptShares([][]byte{[]byte(value)}, []string{encryptionKey}) if err != nil { - return "", "", fmt.Errorf("Error encrypting %s: %w", description, err) + return "", "", fmt.Errorf("error encrypting %s: %w", description, err) } return fingerprints[0], base64.StdEncoding.EncodeToString(encryptedValue[0]), nil diff --git a/internal/service/macie2/resource_macie2_organization_settings.go b/internal/service/macie2/resource_macie2_organization_settings.go index 88ce1c9..99648f0 100644 --- a/internal/service/macie2/resource_macie2_organization_settings.go +++ b/internal/service/macie2/resource_macie2_organization_settings.go @@ -50,7 +50,7 @@ func getMemberAccounts(d *schema.ResourceData) []string { func getMemberAccountsFromAws(conn *macie2.Macie2) ([]string, error) { memberAccounts, err := conn.ListMembers(&macie2.ListMembersInput{}) if err != nil { - return nil, fmt.Errorf("error reading macie2 organization members: %s", err) + return nil, fmt.Errorf("error reading macie2 organization members: %w", err) } var memberAccountIDs []string @@ -81,7 +81,9 @@ func resourceAwsMacie2OrganizationSettingsRead(d *schema.ResourceData, meta inte return err } - d.Set("member_accounts", memberAccounts) + if err := d.Set("member_accounts", memberAccounts); err != nil { + return fmt.Errorf("error setting member_accounts: %w", err) + } return nil } @@ -98,14 +100,14 @@ func resourceAwsMacie2OrganizationSettingsUpdate(d *schema.ResourceData, meta in membersToAdd := flex.Diff(desiredMemberAccounts, currentMemberAccounts) if len(membersToAdd) > 0 { if err := addMacie2OrganizationMembers(conn, membersToAdd); err != nil { - return fmt.Errorf("error setting macie2 organization members: %s", err) + return fmt.Errorf("error setting macie2 organization members: %w", err) } } membersToRemove := flex.Diff(currentMemberAccounts, desiredMemberAccounts) if len(membersToRemove) > 0 { if err := removeMacie2OrganizationMembers(conn, membersToRemove); err != nil { - return fmt.Errorf("error removing macie2 organization members: %s", err) + return fmt.Errorf("error removing macie2 organization members: %w", err) } } return nil @@ -116,7 +118,7 @@ func resourceAwsMacie2OrganizationSettingsDelete(d *schema.ResourceData, meta in membersToRemove := getMemberAccounts(d) if err := removeMacie2OrganizationMembers(conn, membersToRemove); err != nil { - return fmt.Errorf("error removing macie2 organization members: %s", err) + return fmt.Errorf("error removing macie2 organization members: %w", err) } return nil } @@ -150,7 +152,7 @@ func addMacie2OrganizationMembers(conn *macie2.Macie2, memberAccounts []string) } if _, err := conn.CreateMember(createMemberInput); err != nil { - return fmt.Errorf("error designating macie2 administrator account members: %s", err) + return fmt.Errorf("error designating macie2 administrator account members: %w", err) } } } @@ -170,18 +172,15 @@ func removeMacie2OrganizationMembers(conn *macie2.Macie2, memberAccounts []strin } if _, err := conn.DisassociateMember(disassociateMemberInput); err != nil { - if err != nil { - return fmt.Errorf("error disassociating macie2 administrator account member: %s", err) - } + return fmt.Errorf("error disassociating macie2 administrator account member: %w", err) } if _, err := conn.DeleteMember(deleteMemberInput); err != nil { log.Printf("[WARN] Error deleting macie2 administrator account member: %s", err.Error()) - if strings.Contains(err.Error(), "specified account is not associated with your account") { - log.Printf("[WARN] The specified member account (%s) isn't associated with the delegated administrator account", *disassociateMemberInput.Id) - } else { - return fmt.Errorf("error removing macie2 administrator account members: %s", err) + if !strings.Contains(err.Error(), "specified account is not associated with your account") { + return fmt.Errorf("error removing macie2 administrator account members: %w", err) } + log.Printf("[WARN] The specified member account (%s) isn't associated with the delegated administrator account", *disassociateMemberInput.Id) } } } diff --git a/internal/service/meta/arn.go b/internal/service/meta/arn.go index ca5f5e6..7df51ec 100644 --- a/internal/service/meta/arn.go +++ b/internal/service/meta/arn.go @@ -3,6 +3,7 @@ package meta import ( "context" + "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws/arn" @@ -13,6 +14,8 @@ import ( "github.com/hashicorp/terraform-plugin-go/tftypes" ) +var errCannotApplyAttributePathStep = errors.New("cannot apply AttributePathStep") + type arnType uint8 const ( @@ -53,7 +56,7 @@ func (t arnType) Equal(o attr.Type) bool { // ApplyTerraform5AttributePathStep applies the given AttributePathStep to the // type. func (t arnType) ApplyTerraform5AttributePathStep(step tftypes.AttributePathStep) (interface{}, error) { - return nil, fmt.Errorf("cannot apply AttributePathStep %T to %s", step, t.String()) + return nil, fmt.Errorf("%w %T to %s", errCannotApplyAttributePathStep, step, t.String()) } // String returns a human-friendly description of the ARNType. @@ -113,11 +116,11 @@ type ARN struct { Value arn.ARN } -func (a ARN) Type(_ context.Context) attr.Type { +func (a ARN) Type(_ context.Context) attr.Type { //nolint:gocritic // hugeParam: receiver type required by attr.Value interface return ARNType } -func (a ARN) ToTerraformValue(ctx context.Context) (tftypes.Value, error) { +func (a ARN) ToTerraformValue(ctx context.Context) (tftypes.Value, error) { //nolint:gocritic // hugeParam: receiver type required by attr.Value interface t := ARNType.TerraformType(ctx) if a.Null { return tftypes.NewValue(t, nil), nil @@ -129,7 +132,7 @@ func (a ARN) ToTerraformValue(ctx context.Context) (tftypes.Value, error) { } // Equal returns true if `other` is a *ARN and has the same value as `a`. -func (a ARN) Equal(other attr.Value) bool { +func (a ARN) Equal(other attr.Value) bool { //nolint:gocritic // hugeParam: receiver type required by attr.Value interface o, ok := other.(ARN) if !ok { return false @@ -144,12 +147,12 @@ func (a ARN) Equal(other attr.Value) bool { } // IsNull returns true if the Value is not set, or is explicitly set to null. -func (a ARN) IsNull() bool { +func (a ARN) IsNull() bool { //nolint:gocritic // hugeParam: receiver type required by attr.Value interface return a.Null } // IsUnknown returns true if the Value is not yet known. -func (a ARN) IsUnknown() bool { +func (a ARN) IsUnknown() bool { //nolint:gocritic // hugeParam: receiver type required by attr.Value interface return a.Unknown } diff --git a/internal/service/meta/arn_data_source.go b/internal/service/meta/arn_data_source.go index 6a33e93..716d1cf 100644 --- a/internal/service/meta/arn_data_source.go +++ b/internal/service/meta/arn_data_source.go @@ -46,15 +46,25 @@ func dataSourceARNRead(d *schema.ResourceData, meta interface{}) error { v := d.Get("arn").(string) arn, err := arn.Parse(v) if err != nil { - return fmt.Errorf("Error parsing '%s': %w", v, err) + return fmt.Errorf("error parsing '%s': %w", v, err) } d.SetId(arn.String()) - d.Set("partition", arn.Partition) - d.Set("service", arn.Service) - d.Set("region", arn.Region) - d.Set("account", arn.AccountID) - d.Set("resource", arn.Resource) + if err := d.Set("partition", arn.Partition); err != nil { + return fmt.Errorf("error setting partition: %w", err) + } + if err := d.Set("service", arn.Service); err != nil { + return fmt.Errorf("error setting service: %w", err) + } + if err := d.Set("region", arn.Region); err != nil { + return fmt.Errorf("error setting region: %w", err) + } + if err := d.Set("account", arn.AccountID); err != nil { + return fmt.Errorf("error setting account: %w", err) + } + if err := d.Set("resource", arn.Resource); err != nil { + return fmt.Errorf("error setting resource: %w", err) + } return nil } diff --git a/internal/service/meta/arn_test.go b/internal/service/meta/arn_test.go index 54e3e96..ff8892e 100644 --- a/internal/service/meta/arn_test.go +++ b/internal/service/meta/arn_test.go @@ -48,6 +48,7 @@ func TestARNTypeValueFromTerraform(t *testing.T) { for name, test := range tests { name, test := name, test t.Run(name, func(t *testing.T) { + t.Parallel() ctx := context.TODO() val, err := meta.ARNType.ValueFromTerraform(ctx, test.val) @@ -95,6 +96,7 @@ func TestARNTypeValidate(t *testing.T) { for name, test := range tests { name, test := name, test t.Run(name, func(t *testing.T) { + t.Parallel() ctx := context.TODO() diags := meta.ARNType.Validate(ctx, test.val, path.Root("test")) diff --git a/internal/service/meta/billing_service_account_data_source.go b/internal/service/meta/billing_service_account_data_source.go index fabd921..e054837 100644 --- a/internal/service/meta/billing_service_account_data_source.go +++ b/internal/service/meta/billing_service_account_data_source.go @@ -1,6 +1,8 @@ package meta import ( + "fmt" + "github.com/aws/aws-sdk-go/aws/arn" "github.com/cloudposse/terraform-provider-awsutils/internal/conns" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -30,7 +32,9 @@ func dataSourceBillingServiceAccountRead(d *schema.ResourceData, meta interface{ AccountID: billingAccountId, Resource: "root", }.String() - d.Set("arn", arn) + if err := d.Set("arn", arn); err != nil { + return fmt.Errorf("error setting arn: %w", err) + } return nil } diff --git a/internal/service/meta/default_tags_data_source.go b/internal/service/meta/default_tags_data_source.go index 2c47027..abf229b 100644 --- a/internal/service/meta/default_tags_data_source.go +++ b/internal/service/meta/default_tags_data_source.go @@ -30,8 +30,8 @@ func dataSourceDefaultTagsRead(d *schema.ResourceData, meta interface{}) error { if err := d.Set("tags", tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { return fmt.Errorf("error setting tags: %w", err) } - } else { - d.Set("tags", nil) + } else if err := d.Set("tags", nil); err != nil { + return fmt.Errorf("error setting tags: %w", err) } return nil diff --git a/internal/service/meta/ip_ranges_data_source.go b/internal/service/meta/ip_ranges_data_source.go index 19d99c3..b1bd47f 100644 --- a/internal/service/meta/ip_ranges_data_source.go +++ b/internal/service/meta/ip_ranges_data_source.go @@ -82,47 +82,45 @@ func dataSourceIPRangesRead(d *schema.ResourceData, meta interface{}) error { res, err := conn.Get(url) if err != nil { - return fmt.Errorf("Error listing IP ranges from (%s): %w", url, err) + return fmt.Errorf("error listing IP ranges from (%s): %w", url, err) } defer res.Body.Close() data, err := io.ReadAll(res.Body) if err != nil { - return fmt.Errorf("Error reading response body from (%s): %w", url, err) + return fmt.Errorf("error reading response body from (%s): %w", url, err) } result := new(dataSourceAwsIPRangesResult) if err := json.Unmarshal(data, result); err != nil { - return fmt.Errorf("Error parsing result from (%s): %w", url, err) + return fmt.Errorf("error parsing result from (%s): %w", url, err) } if err := d.Set("create_date", result.CreateDate); err != nil { - return fmt.Errorf("Error setting create date: %w", err) + return fmt.Errorf("error setting create date: %w", err) } syncToken, err := strconv.Atoi(result.SyncToken) if err != nil { - return fmt.Errorf("Error while converting sync token: %w", err) + return fmt.Errorf("error while converting sync token: %w", err) } d.SetId(result.SyncToken) if err := d.Set("sync_token", syncToken); err != nil { - return fmt.Errorf("Error setting sync token: %w", err) + return fmt.Errorf("error setting sync token: %w", err) } get := func(key string) *schema.Set { set := d.Get(key).(*schema.Set) for _, e := range set.List() { - s := e.(string) set.Remove(s) set.Add(strings.ToLower(s)) - } return set @@ -157,13 +155,13 @@ func dataSourceIPRangesRead(d *schema.ResourceData, meta interface{}) error { sort.Strings(ipPrefixes) if err := d.Set("cidr_blocks", ipPrefixes); err != nil { - return fmt.Errorf("Error setting cidr_blocks: %w", err) + return fmt.Errorf("error setting cidr_blocks: %w", err) } sort.Strings(ipv6Prefixes) if err := d.Set("ipv6_cidr_blocks", ipv6Prefixes); err != nil { - return fmt.Errorf("Error setting ipv6_cidr_blocks: %w", err) + return fmt.Errorf("error setting ipv6_cidr_blocks: %w", err) } return nil diff --git a/internal/service/meta/partition_data_source.go b/internal/service/meta/partition_data_source.go index b93bbf4..730a310 100644 --- a/internal/service/meta/partition_data_source.go +++ b/internal/service/meta/partition_data_source.go @@ -1,6 +1,7 @@ package meta import ( + "fmt" "log" "github.com/cloudposse/terraform-provider-awsutils/internal/conns" @@ -37,12 +38,18 @@ func dataSourcePartitionRead(d *schema.ResourceData, meta interface{}) error { d.SetId(meta.(*conns.AWSClient).Partition) log.Printf("[DEBUG] Setting AWS Partition to %s.", client.Partition) - d.Set("partition", meta.(*conns.AWSClient).Partition) + if err := d.Set("partition", meta.(*conns.AWSClient).Partition); err != nil { + return fmt.Errorf("error setting partition: %w", err) + } log.Printf("[DEBUG] Setting AWS URL Suffix to %s.", client.DNSSuffix) - d.Set("dns_suffix", meta.(*conns.AWSClient).DNSSuffix) + if err := d.Set("dns_suffix", meta.(*conns.AWSClient).DNSSuffix); err != nil { + return fmt.Errorf("error setting dns_suffix: %w", err) + } - d.Set("reverse_dns_prefix", meta.(*conns.AWSClient).ReverseDNSPrefix) + if err := d.Set("reverse_dns_prefix", meta.(*conns.AWSClient).ReverseDNSPrefix); err != nil { + return fmt.Errorf("error setting reverse_dns_prefix: %w", err) + } log.Printf("[DEBUG] Setting service prefix to %s.", meta.(*conns.AWSClient).ReverseDNSPrefix) return nil diff --git a/internal/service/meta/region_data_source.go b/internal/service/meta/region_data_source.go index ae2cee8..915ff5a 100644 --- a/internal/service/meta/region_data_source.go +++ b/internal/service/meta/region_data_source.go @@ -1,6 +1,7 @@ package meta import ( + "errors" "fmt" "strings" @@ -9,6 +10,12 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) +var ( + errMultipleRegionsMatched = errors.New("multiple regions matched; use additional constraints to reduce matches to a single region") + errRegionNotFoundForEndpoint = errors.New("region not found for endpoint") + errRegionNotFoundForName = errors.New("region not found for name") +) + func DataSourceRegion() *schema.Resource { return &schema.Resource{ Read: dataSourceRegionRead, @@ -55,7 +62,7 @@ func dataSourceRegionRead(d *schema.ResourceData, meta interface{}) error { return err } if region != nil && region.ID() != matchingRegion.ID() { - return fmt.Errorf("multiple regions matched; use additional constraints to reduce matches to a single region") + return fmt.Errorf("%w: %q and %q", errMultipleRegionsMatched, region.ID(), matchingRegion.ID()) } region = matchingRegion } @@ -71,15 +78,21 @@ func dataSourceRegionRead(d *schema.ResourceData, meta interface{}) error { d.SetId(region.ID()) - regionEndpointEc2, err := region.ResolveEndpoint(endpoints.Ec2ServiceID) + regionEndpointEc2, err := region.ResolveEndpoint(endpoints.Ec2ServiceID) //nolint:staticcheck // SA1019: legacy SDK constant retained for compatibility if err != nil { return err } - d.Set("endpoint", strings.TrimPrefix(regionEndpointEc2.URL, "https://")) + if err := d.Set("endpoint", strings.TrimPrefix(regionEndpointEc2.URL, "https://")); err != nil { + return fmt.Errorf("error setting endpoint: %w", err) + } - d.Set("name", region.ID()) + if err := d.Set("name", region.ID()); err != nil { + return fmt.Errorf("error setting name: %w", err) + } - d.Set("description", region.Description()) + if err := d.Set("description", region.Description()); err != nil { + return fmt.Errorf("error setting description: %w", err) + } return nil } @@ -87,7 +100,7 @@ func dataSourceRegionRead(d *schema.ResourceData, meta interface{}) error { func FindRegionByEndpoint(endpoint string) (*endpoints.Region, error) { for _, partition := range endpoints.DefaultPartitions() { for _, region := range partition.Regions() { - regionEndpointEc2, err := region.ResolveEndpoint(endpoints.Ec2ServiceID) + regionEndpointEc2, err := region.ResolveEndpoint(endpoints.Ec2ServiceID) //nolint:staticcheck // SA1019: legacy SDK constant retained for compatibility if err != nil { return nil, err } @@ -96,7 +109,7 @@ func FindRegionByEndpoint(endpoint string) (*endpoints.Region, error) { } } } - return nil, fmt.Errorf("region not found for endpoint %q", endpoint) + return nil, fmt.Errorf("%w: %q", errRegionNotFoundForEndpoint, endpoint) } func FindRegionByName(name string) (*endpoints.Region, error) { @@ -107,5 +120,5 @@ func FindRegionByName(name string) (*endpoints.Region, error) { } } } - return nil, fmt.Errorf("region not found for name %q", name) + return nil, fmt.Errorf("%w: %q", errRegionNotFoundForName, name) } diff --git a/internal/service/meta/regions_data_source.go b/internal/service/meta/regions_data_source.go index 083ea5a..8eb815f 100644 --- a/internal/service/meta/regions_data_source.go +++ b/internal/service/meta/regions_data_source.go @@ -46,7 +46,7 @@ func dataSourceRegionsRead(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Reading regions for request: %s", request) response, err := connection.DescribeRegions(request) if err != nil { - return fmt.Errorf("Error fetching Regions: %w", err) + return fmt.Errorf("error fetching Regions: %w", err) } names := []string{} diff --git a/internal/service/meta/service_data_source.go b/internal/service/meta/service_data_source.go index 807609f..dd97195 100644 --- a/internal/service/meta/service_data_source.go +++ b/internal/service/meta/service_data_source.go @@ -1,6 +1,7 @@ package meta import ( + "errors" "fmt" "strings" @@ -9,6 +10,14 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) +var ( + errReverseServiceDNSNameTooShort = errors.New("reverse service DNS names must have at least 4 parts") + errServiceDNSNameTooShort = errors.New("service DNS names must have at least 4 parts") + errNoServiceID = errors.New("service ID not provided directly or through a DNS name") +) + +const reverseDNSNameKey = "reverse_dns_name" + func DataSourceService() *schema.Resource { return &schema.Resource{ Read: dataSourceServiceRead, @@ -18,7 +27,7 @@ func DataSourceService() *schema.Resource { Type: schema.TypeString, Computed: true, Optional: true, - ExactlyOneOf: []string{"dns_name", "reverse_dns_name", "service_id"}, + ExactlyOneOf: []string{"dns_name", reverseDNSNameKey, "service_id"}, }, "partition": { Type: schema.TypeString, @@ -28,25 +37,25 @@ func DataSourceService() *schema.Resource { Type: schema.TypeString, Computed: true, Optional: true, - ConflictsWith: []string{"dns_name", "reverse_dns_name"}, + ConflictsWith: []string{"dns_name", reverseDNSNameKey}, }, - "reverse_dns_name": { + reverseDNSNameKey: { Type: schema.TypeString, Computed: true, Optional: true, - ExactlyOneOf: []string{"dns_name", "reverse_dns_name", "service_id"}, + ExactlyOneOf: []string{"dns_name", reverseDNSNameKey, "service_id"}, }, "reverse_dns_prefix": { Type: schema.TypeString, Computed: true, Optional: true, - ConflictsWith: []string{"dns_name", "reverse_dns_name"}, + ConflictsWith: []string{"dns_name", reverseDNSNameKey}, }, "service_id": { Type: schema.TypeString, Computed: true, Optional: true, - ExactlyOneOf: []string{"dns_name", "reverse_dns_name", "service_id"}, + ExactlyOneOf: []string{"dns_name", reverseDNSNameKey, "service_id"}, }, "supported": { Type: schema.TypeBool, @@ -59,50 +68,85 @@ func DataSourceService() *schema.Resource { func dataSourceServiceRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*conns.AWSClient) - if v, ok := d.GetOk("reverse_dns_name"); ok { + if v, ok := d.GetOk(reverseDNSNameKey); ok { serviceParts := strings.Split(v.(string), ".") if len(serviceParts) < 4 { - return fmt.Errorf("reverse service DNS names must have at least 4 parts (%s has %d)", v.(string), len(serviceParts)) + return fmt.Errorf("%w (%s has %d)", errReverseServiceDNSNameTooShort, v.(string), len(serviceParts)) } - d.Set("service_id", serviceParts[len(serviceParts)-1]) - d.Set("region", serviceParts[len(serviceParts)-2]) - d.Set("reverse_dns_prefix", strings.Join(serviceParts[0:len(serviceParts)-2], ".")) + if err := d.Set("service_id", serviceParts[len(serviceParts)-1]); err != nil { + return fmt.Errorf("error setting service_id: %w", err) + } + if err := d.Set("region", serviceParts[len(serviceParts)-2]); err != nil { + return fmt.Errorf("error setting region: %w", err) + } + if err := d.Set("reverse_dns_prefix", strings.Join(serviceParts[0:len(serviceParts)-2], ".")); err != nil { + return fmt.Errorf("error setting reverse_dns_prefix: %w", err) + } } if v, ok := d.GetOk("dns_name"); ok { serviceParts := InvertStringSlice(strings.Split(v.(string), ".")) if len(serviceParts) < 4 { - return fmt.Errorf("service DNS names must have at least 4 parts (%s has %d)", v.(string), len(serviceParts)) + return fmt.Errorf("%w (%s has %d)", errServiceDNSNameTooShort, v.(string), len(serviceParts)) } - d.Set("service_id", serviceParts[len(serviceParts)-1]) - d.Set("region", serviceParts[len(serviceParts)-2]) - d.Set("reverse_dns_prefix", strings.Join(serviceParts[0:len(serviceParts)-2], ".")) + if err := d.Set("service_id", serviceParts[len(serviceParts)-1]); err != nil { + return fmt.Errorf("error setting service_id: %w", err) + } + if err := d.Set("region", serviceParts[len(serviceParts)-2]); err != nil { + return fmt.Errorf("error setting region: %w", err) + } + if err := d.Set("reverse_dns_prefix", strings.Join(serviceParts[0:len(serviceParts)-2], ".")); err != nil { + return fmt.Errorf("error setting reverse_dns_prefix: %w", err) + } } if _, ok := d.GetOk("region"); !ok { - d.Set("region", client.Region) + if err := d.Set("region", client.Region); err != nil { + return fmt.Errorf("error setting region: %w", err) + } } if _, ok := d.GetOk("service_id"); !ok { - return fmt.Errorf("service ID not provided directly or through a DNS name") + return errNoServiceID } if _, ok := d.GetOk("reverse_dns_prefix"); !ok { dnsParts := strings.Split(meta.(*conns.AWSClient).DNSSuffix, ".") - d.Set("reverse_dns_prefix", strings.Join(InvertStringSlice(dnsParts), ".")) + if err := d.Set("reverse_dns_prefix", strings.Join(InvertStringSlice(dnsParts), ".")); err != nil { + return fmt.Errorf("error setting reverse_dns_prefix: %w", err) + } } reverseDNS := fmt.Sprintf("%s.%s.%s", d.Get("reverse_dns_prefix").(string), d.Get("region").(string), d.Get("service_id").(string)) - d.Set("reverse_dns_name", reverseDNS) - d.Set("dns_name", strings.ToLower(strings.Join(InvertStringSlice(strings.Split(reverseDNS, ".")), "."))) + if err := d.Set(reverseDNSNameKey, reverseDNS); err != nil { + return fmt.Errorf("error setting reverse_dns_name: %w", err) + } + if err := d.Set("dns_name", strings.ToLower(strings.Join(InvertStringSlice(strings.Split(reverseDNS, ".")), "."))); err != nil { + return fmt.Errorf("error setting dns_name: %w", err) + } - d.Set("supported", true) + // Default supported to false; only flip to true once both the partition + // and service are confirmed. This prevents stale state when switching to + // an unknown region. + if err := d.Set("supported", false); err != nil { + return fmt.Errorf("error setting supported: %w", err) + } if partition, ok := endpoints.PartitionForRegion(endpoints.DefaultPartitions(), d.Get("region").(string)); ok { - d.Set("partition", partition.ID()) - if _, ok := partition.Services()[d.Get("service_id").(string)]; !ok { - d.Set("supported", false) + if err := d.Set("partition", partition.ID()); err != nil { + return fmt.Errorf("error setting partition: %w", err) + } + if _, ok := partition.Services()[d.Get("service_id").(string)]; ok { + if err := d.Set("supported", true); err != nil { + return fmt.Errorf("error setting supported: %w", err) + } + } + } else { + // Region is unknown to the SDK; clear partition so state cannot + // retain a stale value from a prior read. + if err := d.Set("partition", ""); err != nil { + return fmt.Errorf("error setting partition: %w", err) } } @@ -111,7 +155,7 @@ func dataSourceServiceRead(d *schema.ResourceData, meta interface{}) error { return nil } -// invertStringSlice returns inverted string slice without sorting slice like sort.Reverse() +// invertStringSlice returns inverted string slice without sorting slice like sort.Reverse(). func InvertStringSlice(slice []string) []string { inverse := make([]string, 0) for i := 0; i < len(slice); i++ { diff --git a/internal/service/organizations/account.go b/internal/service/organizations/account.go index 50173ba..974aac1 100644 --- a/internal/service/organizations/account.go +++ b/internal/service/organizations/account.go @@ -1,6 +1,7 @@ package organizations import ( + "context" "errors" "fmt" "log" @@ -19,6 +20,8 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) +var errAccountCreateFailed = errors.New("account create failed") + func ResourceAccount() *schema.Resource { return &schema.Resource{ Create: resourceAccountCreate, @@ -26,7 +29,7 @@ func ResourceAccount() *schema.Resource { Update: resourceAccountUpdate, Delete: resourceAccountDelete, Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, + StateContext: schema.ImportStatePassthroughContext, }, Schema: map[string]*schema.Schema{ @@ -137,7 +140,9 @@ func resourceAccountCreate(d *schema.ResourceData, meta interface{}) error { } d.SetId(aws.StringValue(output.AccountId)) - d.Set("govcloud_id", output.GovCloudAccountId) + if err := d.Set("govcloud_id", output.GovCloudAccountId); err != nil { + return fmt.Errorf("error setting govcloud_id: %w", err) + } if v, ok := d.GetOk("parent_id"); ok { oldParentAccountID, err := findParentAccountID(conn, d.Id()) @@ -184,13 +189,27 @@ func resourceAccountRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error reading AWS Organizations Account (%s) parent: %w", d.Id(), err) } - d.Set("arn", account.Arn) - d.Set("email", account.Email) - d.Set("joined_method", account.JoinedMethod) - d.Set("joined_timestamp", aws.TimeValue(account.JoinedTimestamp).Format(time.RFC3339)) - d.Set("name", account.Name) - d.Set("parent_id", parentAccountID) - d.Set("status", account.Status) + if err := d.Set("arn", account.Arn); err != nil { + return fmt.Errorf("error setting arn: %w", err) + } + if err := d.Set("email", account.Email); err != nil { + return fmt.Errorf("error setting email: %w", err) + } + if err := d.Set("joined_method", account.JoinedMethod); err != nil { + return fmt.Errorf("error setting joined_method: %w", err) + } + if err := d.Set("joined_timestamp", aws.TimeValue(account.JoinedTimestamp).Format(time.RFC3339)); err != nil { + return fmt.Errorf("error setting joined_timestamp: %w", err) + } + if err := d.Set("name", account.Name); err != nil { + return fmt.Errorf("error setting name: %w", err) + } + if err := d.Set("parent_id", parentAccountID); err != nil { + return fmt.Errorf("error setting parent_id: %w", err) + } + if err := d.Set("status", account.Status); err != nil { + return fmt.Errorf("error setting status: %w", err) + } tags, err := ListTags(conn, d.Id()) if err != nil { @@ -274,7 +293,7 @@ func resourceAccountDelete(d *schema.ResourceData, meta interface{}) error { return nil } -func createAccount(conn *organizations.Organizations, name, email string, iamUserAccessToBilling, roleName *string, tags []*organizations.Tag, govCloud bool) (*organizations.CreateAccountStatus, error) { +func createAccount(conn *organizations.Organizations, name, email string, iamUserAccessToBilling, roleName *string, tags []*organizations.Tag, govCloud bool) (*organizations.CreateAccountStatus, error) { //nolint:revive // argument-limit: thin wrapper around AWS SDK CreateAccount inputs if govCloud { input := &organizations.CreateGovCloudAccountInput{ AccountName: aws.String(name), @@ -416,11 +435,11 @@ func waitAccountCreated(conn *organizations.Organizations, id string) (*organiza Timeout: 5 * time.Minute, } - outputRaw, err := stateConf.WaitForState() + outputRaw, err := stateConf.WaitForStateContext(context.Background()) if output, ok := outputRaw.(*organizations.CreateAccountStatus); ok { if state := aws.StringValue(output.State); state == organizations.CreateAccountStateFailed { - tfresource.SetLastError(err, errors.New(aws.StringValue(output.FailureReason))) + tfresource.SetLastError(err, fmt.Errorf("%w: %s", errAccountCreateFailed, aws.StringValue(output.FailureReason))) } return output, err @@ -454,7 +473,7 @@ func waitAccountDeleted(conn *organizations.Organizations, id string) (*organiza Timeout: 5 * time.Minute, } - outputRaw, err := stateConf.WaitForState() + outputRaw, err := stateConf.WaitForStateContext(context.Background()) if output, ok := outputRaw.(*organizations.Account); ok { return output, err diff --git a/internal/service/organizations/delegated_administrator.go b/internal/service/organizations/delegated_administrator.go index 008b723..27b89bf 100644 --- a/internal/service/organizations/delegated_administrator.go +++ b/internal/service/organizations/delegated_administrator.go @@ -2,6 +2,7 @@ package organizations import ( "context" + "errors" "fmt" "log" "strings" @@ -16,6 +17,8 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) +var errInvalidDelegatedAdminID = errors.New("expected ID in the form of account_id/service_principal") + func ResourceDelegatedAdministrator() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceDelegatedAdministratorCreate, @@ -119,15 +122,33 @@ func resourceDelegatedAdministratorRead(ctx context.Context, d *schema.ResourceD return nil } - d.Set("arn", delegatedAccount.Arn) - d.Set("delegation_enabled_date", aws.TimeValue(delegatedAccount.DelegationEnabledDate).Format(time.RFC3339)) - d.Set("email", delegatedAccount.Email) - d.Set("joined_method", delegatedAccount.JoinedMethod) - d.Set("joined_timestamp", aws.TimeValue(delegatedAccount.JoinedTimestamp).Format(time.RFC3339)) - d.Set("name", delegatedAccount.Name) - d.Set("status", delegatedAccount.Status) - d.Set("account_id", accountID) - d.Set("service_principal", servicePrincipal) + if err := d.Set("arn", delegatedAccount.Arn); err != nil { + return diag.FromErr(fmt.Errorf("error setting arn: %w", err)) + } + if err := d.Set("delegation_enabled_date", aws.TimeValue(delegatedAccount.DelegationEnabledDate).Format(time.RFC3339)); err != nil { + return diag.FromErr(fmt.Errorf("error setting delegation_enabled_date: %w", err)) + } + if err := d.Set("email", delegatedAccount.Email); err != nil { + return diag.FromErr(fmt.Errorf("error setting email: %w", err)) + } + if err := d.Set("joined_method", delegatedAccount.JoinedMethod); err != nil { + return diag.FromErr(fmt.Errorf("error setting joined_method: %w", err)) + } + if err := d.Set("joined_timestamp", aws.TimeValue(delegatedAccount.JoinedTimestamp).Format(time.RFC3339)); err != nil { + return diag.FromErr(fmt.Errorf("error setting joined_timestamp: %w", err)) + } + if err := d.Set("name", delegatedAccount.Name); err != nil { + return diag.FromErr(fmt.Errorf("error setting name: %w", err)) + } + if err := d.Set("status", delegatedAccount.Status); err != nil { + return diag.FromErr(fmt.Errorf("error setting status: %w", err)) + } + if err := d.Set("account_id", accountID); err != nil { + return diag.FromErr(fmt.Errorf("error setting account_id: %w", err)) + } + if err := d.Set("service_principal", servicePrincipal); err != nil { + return diag.FromErr(fmt.Errorf("error setting service_principal: %w", err)) + } return nil } @@ -154,7 +175,7 @@ func resourceDelegatedAdministratorDelete(ctx context.Context, d *schema.Resourc func DecodeOrganizationDelegatedAdministratorID(id string) (string, string, error) { idParts := strings.Split(id, "/") if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" { - return "", "", fmt.Errorf("expected ID in the form of account_id/service_principal, given: %q", id) + return "", "", fmt.Errorf("%w, given: %q", errInvalidDelegatedAdminID, id) } return idParts[0], idParts[1], nil } diff --git a/internal/service/organizations/organization.go b/internal/service/organizations/organization.go index e99f54e..24afe64 100644 --- a/internal/service/organizations/organization.go +++ b/internal/service/organizations/organization.go @@ -2,6 +2,7 @@ package organizations import ( "context" + "errors" "fmt" "log" "time" @@ -18,6 +19,8 @@ import ( const policyTypeStatusDisabled = "DISABLED" +var errNoRootsFound = errors.New("no roots found") + func ResourceOrganization() *schema.Resource { return &schema.Resource{ Create: resourceOrganizationCreate, @@ -25,7 +28,7 @@ func ResourceOrganization() *schema.Resource { Update: resourceOrganizationUpdate, Delete: resourceOrganizationDelete, Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, + StateContext: schema.ImportStatePassthroughContext, }, CustomizeDiff: customdiff.Sequence( @@ -177,7 +180,7 @@ func resourceOrganizationCreate(d *schema.ResourceData, meta interface{}) error resp, err := conn.CreateOrganization(createOpts) if err != nil { - return fmt.Errorf("Error creating organization: %s", err) + return fmt.Errorf("error creating organization: %w", err) } org := resp.Organization @@ -193,7 +196,7 @@ func resourceOrganizationCreate(d *schema.ResourceData, meta interface{}) error log.Printf("[DEBUG] Enabling AWS Service Access in Organization: %s", input) _, err := conn.EnableAWSServiceAccess(input) if err != nil { - return fmt.Errorf("error enabling AWS Service Access (%s) in Organization: %s", principal, err) + return fmt.Errorf("error enabling AWS Service Access (%s) in Organization: %w", principal, err) } } @@ -202,7 +205,7 @@ func resourceOrganizationCreate(d *schema.ResourceData, meta interface{}) error if len(enabledPolicyTypes) > 0 { defaultRoot, err := getOrganizationDefaultRoot(conn) if err != nil { - return fmt.Errorf("error getting AWS Organization (%s) default root: %s", d.Id(), err) + return fmt.Errorf("error getting AWS Organization (%s) default root: %w", d.Id(), err) } for _, v := range enabledPolicyTypes { @@ -213,11 +216,11 @@ func resourceOrganizationCreate(d *schema.ResourceData, meta interface{}) error } if _, err := conn.EnablePolicyType(input); err != nil { - return fmt.Errorf("error enabling policy type (%s) in Organization (%s): %s", enabledPolicyType, d.Id(), err) + return fmt.Errorf("error enabling policy type (%s) in Organization (%s): %w", enabledPolicyType, d.Id(), err) } if err := waitForOrganizationDefaultRootPolicyTypeEnable(conn, enabledPolicyType); err != nil { - return fmt.Errorf("error waiting for policy type (%s) enabling in Organization (%s): %s", enabledPolicyType, d.Id(), err) + return fmt.Errorf("error waiting for policy type (%s) enabling in Organization (%s): %w", enabledPolicyType, d.Id(), err) } } } @@ -238,7 +241,7 @@ func resourceOrganizationRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error describing Organization: %s", err) + return fmt.Errorf("error describing Organization: %w", err) } log.Printf("[INFO] Listing Accounts for Organization: %s", d.Id()) @@ -256,7 +259,7 @@ func resourceOrganizationRead(d *schema.ResourceData, meta interface{}) error { return !lastPage }) if err != nil { - return fmt.Errorf("error listing AWS Organization (%s) accounts: %s", d.Id(), err) + return fmt.Errorf("error listing AWS Organization (%s) accounts: %w", d.Id(), err) } log.Printf("[INFO] Listing Roots for Organization: %s", d.Id()) @@ -266,25 +269,35 @@ func resourceOrganizationRead(d *schema.ResourceData, meta interface{}) error { return !lastPage }) if err != nil { - return fmt.Errorf("error listing AWS Organization (%s) roots: %s", d.Id(), err) + return fmt.Errorf("error listing AWS Organization (%s) roots: %w", d.Id(), err) } if err := d.Set("accounts", flattenAccounts(accounts)); err != nil { - return fmt.Errorf("error setting accounts: %s", err) + return fmt.Errorf("error setting accounts: %w", err) } - d.Set("arn", org.Organization.Arn) - d.Set("feature_set", org.Organization.FeatureSet) - d.Set("master_account_arn", org.Organization.MasterAccountArn) - d.Set("master_account_email", org.Organization.MasterAccountEmail) - d.Set("master_account_id", org.Organization.MasterAccountId) + if err := d.Set("arn", org.Organization.Arn); err != nil { + return fmt.Errorf("error setting arn: %w", err) + } + if err := d.Set("feature_set", org.Organization.FeatureSet); err != nil { + return fmt.Errorf("error setting feature_set: %w", err) + } + if err := d.Set("master_account_arn", org.Organization.MasterAccountArn); err != nil { + return fmt.Errorf("error setting master_account_arn: %w", err) + } + if err := d.Set("master_account_email", org.Organization.MasterAccountEmail); err != nil { + return fmt.Errorf("error setting master_account_email: %w", err) + } + if err := d.Set("master_account_id", org.Organization.MasterAccountId); err != nil { + return fmt.Errorf("error setting master_account_id: %w", err) + } if err := d.Set("non_master_accounts", flattenAccounts(nonMasterAccounts)); err != nil { - return fmt.Errorf("error setting non_master_accounts: %s", err) + return fmt.Errorf("error setting non_master_accounts: %w", err) } if err := d.Set("roots", FlattenRoots(roots)); err != nil { - return fmt.Errorf("error setting roots: %s", err) + return fmt.Errorf("error setting roots: %w", err) } awsServiceAccessPrincipals := make([]string, 0) @@ -298,12 +311,12 @@ func resourceOrganizationRead(d *schema.ResourceData, meta interface{}) error { return !lastPage }) if err != nil { - return fmt.Errorf("error listing AWS Service Access for Organization (%s): %s", d.Id(), err) + return fmt.Errorf("error listing AWS Service Access for Organization (%s): %w", d.Id(), err) } } if err := d.Set("aws_service_access_principals", awsServiceAccessPrincipals); err != nil { - return fmt.Errorf("error setting aws_service_access_principals: %s", err) + return fmt.Errorf("error setting aws_service_access_principals: %w", err) } enabledPolicyTypes := make([]string, 0) @@ -315,7 +328,7 @@ func resourceOrganizationRead(d *schema.ResourceData, meta interface{}) error { } if err := d.Set("enabled_policy_types", enabledPolicyTypes); err != nil { - return fmt.Errorf("error setting enabled_policy_types: %s", err) + return fmt.Errorf("error setting enabled_policy_types: %w", err) } return nil @@ -338,7 +351,7 @@ func resourceOrganizationUpdate(d *schema.ResourceData, meta interface{}) error log.Printf("[DEBUG] Disabling AWS Service Access in Organization: %s", input) _, err := conn.DisableAWSServiceAccess(input) if err != nil { - return fmt.Errorf("error disabling AWS Service Access (%s) in Organization: %s", principal, err) + return fmt.Errorf("error disabling AWS Service Access (%s) in Organization: %w", principal, err) } } @@ -351,7 +364,7 @@ func resourceOrganizationUpdate(d *schema.ResourceData, meta interface{}) error log.Printf("[DEBUG] Enabling AWS Service Access in Organization: %s", input) _, err := conn.EnableAWSServiceAccess(input) if err != nil { - return fmt.Errorf("error enabling AWS Service Access (%s) in Organization: %s", principal, err) + return fmt.Errorf("error enabling AWS Service Access (%s) in Organization: %w", principal, err) } } } @@ -371,11 +384,11 @@ func resourceOrganizationUpdate(d *schema.ResourceData, meta interface{}) error log.Printf("[DEBUG] Disabling Policy Type in Organization: %s", input) if _, err := conn.DisablePolicyType(input); err != nil { - return fmt.Errorf("error disabling policy type (%s) in Organization (%s) Root (%s): %s", policyType, d.Id(), defaultRootID, err) + return fmt.Errorf("error disabling policy type (%s) in Organization (%s) Root (%s): %w", policyType, d.Id(), defaultRootID, err) } if err := waitForOrganizationDefaultRootPolicyTypeDisable(conn, policyType); err != nil { - return fmt.Errorf("error waiting for policy type (%s) disabling in Organization (%s) Root (%s): %s", policyType, d.Id(), defaultRootID, err) + return fmt.Errorf("error waiting for policy type (%s) disabling in Organization (%s) Root (%s): %w", policyType, d.Id(), defaultRootID, err) } } @@ -388,11 +401,11 @@ func resourceOrganizationUpdate(d *schema.ResourceData, meta interface{}) error log.Printf("[DEBUG] Enabling Policy Type in Organization: %s", input) if _, err := conn.EnablePolicyType(input); err != nil { - return fmt.Errorf("error enabling policy type (%s) in Organization (%s) Root (%s): %s", policyType, d.Id(), defaultRootID, err) + return fmt.Errorf("error enabling policy type (%s) in Organization (%s) Root (%s): %w", policyType, d.Id(), defaultRootID, err) } if err := waitForOrganizationDefaultRootPolicyTypeEnable(conn, policyType); err != nil { - return fmt.Errorf("error waiting for policy type (%s) enabling in Organization (%s) Root (%s): %s", policyType, d.Id(), defaultRootID, err) + return fmt.Errorf("error waiting for policy type (%s) enabling in Organization (%s) Root (%s): %w", policyType, d.Id(), defaultRootID, err) } } } @@ -413,7 +426,7 @@ func resourceOrganizationDelete(d *schema.ResourceData, meta interface{}) error _, err := conn.DeleteOrganization(&organizations.DeleteOrganizationInput{}) if err != nil { - return fmt.Errorf("Error deleting Organization: %s", err) + return fmt.Errorf("error deleting Organization: %w", err) } return nil @@ -479,7 +492,7 @@ func getOrganizationDefaultRoot(conn *organizations.Organizations) (*organizatio } if len(roots) == 0 { - return nil, fmt.Errorf("no roots found") + return nil, errNoRootsFound } return roots[0], nil @@ -489,7 +502,7 @@ func getOrganizationDefaultRootPolicyTypeRefreshFunc(conn *organizations.Organiz return func() (interface{}, string, error) { defaultRoot, err := getOrganizationDefaultRoot(conn) if err != nil { - return nil, "", fmt.Errorf("error getting default root: %s", err) + return nil, "", fmt.Errorf("error getting default root: %w", err) } for _, pt := range defaultRoot.PolicyTypes { @@ -513,7 +526,7 @@ func waitForOrganizationDefaultRootPolicyTypeDisable(conn *organizations.Organiz Timeout: 5 * time.Minute, } - _, err := stateConf.WaitForState() + _, err := stateConf.WaitForStateContext(context.Background()) return err } @@ -529,7 +542,7 @@ func waitForOrganizationDefaultRootPolicyTypeEnable(conn *organizations.Organiza Timeout: 5 * time.Minute, } - _, err := stateConf.WaitForState() + _, err := stateConf.WaitForStateContext(context.Background()) return err } diff --git a/internal/service/organizations/organization_data_source.go b/internal/service/organizations/organization_data_source.go index 2c6290c..e3b940a 100644 --- a/internal/service/organizations/organization_data_source.go +++ b/internal/service/organizations/organization_data_source.go @@ -147,15 +147,25 @@ func dataSourceOrganizationRead(d *schema.ResourceData, meta interface{}) error org, err := conn.DescribeOrganization(&organizations.DescribeOrganizationInput{}) if err != nil { - return fmt.Errorf("Error describing organization: %w", err) + return fmt.Errorf("error describing organization: %w", err) } d.SetId(aws.StringValue(org.Organization.Id)) - d.Set("arn", org.Organization.Arn) - d.Set("feature_set", org.Organization.FeatureSet) - d.Set("master_account_arn", org.Organization.MasterAccountArn) - d.Set("master_account_email", org.Organization.MasterAccountEmail) - d.Set("master_account_id", org.Organization.MasterAccountId) + if err := d.Set("arn", org.Organization.Arn); err != nil { + return fmt.Errorf("error setting arn: %w", err) + } + if err := d.Set("feature_set", org.Organization.FeatureSet); err != nil { + return fmt.Errorf("error setting feature_set: %w", err) + } + if err := d.Set("master_account_arn", org.Organization.MasterAccountArn); err != nil { + return fmt.Errorf("error setting master_account_arn: %w", err) + } + if err := d.Set("master_account_email", org.Organization.MasterAccountEmail); err != nil { + return fmt.Errorf("error setting master_account_email: %w", err) + } + if err := d.Set("master_account_id", org.Organization.MasterAccountId); err != nil { + return fmt.Errorf("error setting master_account_id: %w", err) + } if aws.StringValue(org.Organization.MasterAccountId) == meta.(*conns.AWSClient).AccountID { var accounts []*organizations.Account @@ -224,7 +234,6 @@ func dataSourceOrganizationRead(d *schema.ResourceData, meta interface{}) error if err := d.Set("roots", FlattenRoots(roots)); err != nil { return fmt.Errorf("error setting roots: %w", err) } - } return nil } diff --git a/internal/service/organizations/organizational_unit.go b/internal/service/organizations/organizational_unit.go index 86ff5e5..789bf91 100644 --- a/internal/service/organizations/organizational_unit.go +++ b/internal/service/organizations/organizational_unit.go @@ -1,6 +1,8 @@ package organizations import ( + "context" + "errors" "fmt" "log" "regexp" @@ -18,6 +20,11 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) +var ( + errOUEmptyResponse = errors.New("empty response") + errOUNotFoundAfterCreate = errors.New("not found after creation") +) + func ResourceOrganizationalUnit() *schema.Resource { return &schema.Resource{ Create: resourceOrganizationalUnitCreate, @@ -25,7 +32,7 @@ func ResourceOrganizationalUnit() *schema.Resource { Update: resourceOrganizationalUnitUpdate, Delete: resourceOrganizationalUnitDelete, Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, + StateContext: schema.ImportStatePassthroughContext, }, Schema: map[string]*schema.Schema{ @@ -90,7 +97,7 @@ func resourceOrganizationalUnitCreate(d *schema.ResourceData, meta interface{}) var err error var resp *organizations.CreateOrganizationalUnitOutput - err = resource.Retry(4*time.Minute, func() *resource.RetryError { + err = resource.RetryContext(context.Background(), 4*time.Minute, func() *resource.RetryError { resp, err = conn.CreateOrganizationalUnit(createOpts) if tfawserr.ErrCodeEquals(err, organizations.ErrCodeFinalizingOrganizationException) { @@ -138,13 +145,13 @@ func resourceOrganizationalUnitRead(d *schema.ResourceData, meta interface{}) er } if resp == nil { - return fmt.Errorf("error reading Organizations Organizational Unit (%s): empty response", d.Id()) + return fmt.Errorf("error reading Organizations Organizational Unit (%s): %w", d.Id(), errOUEmptyResponse) } ou := resp.OrganizationalUnit if ou == nil { if d.IsNewResource() { - return fmt.Errorf("error reading Organizations Organizational Unit (%s): not found after creation", d.Id()) + return fmt.Errorf("error reading Organizations Organizational Unit (%s): %w", d.Id(), errOUNotFoundAfterCreate) } log.Printf("[WARN] Organizations Organizational Unit (%s) does not exist, removing from state", d.Id()) @@ -175,9 +182,15 @@ func resourceOrganizationalUnitRead(d *schema.ResourceData, meta interface{}) er return fmt.Errorf("error setting accounts: %w", err) } - d.Set("arn", ou.Arn) - d.Set("name", ou.Name) - d.Set("parent_id", parentId) + if err := d.Set("arn", ou.Arn); err != nil { + return fmt.Errorf("error setting arn: %w", err) + } + if err := d.Set("name", ou.Name); err != nil { + return fmt.Errorf("error setting name: %w", err) + } + if err := d.Set("parent_id", parentId); err != nil { + return fmt.Errorf("error setting parent_id: %w", err) + } tags, err := ListTags(conn, d.Id()) if err != nil { diff --git a/internal/service/organizations/policy.go b/internal/service/organizations/policy.go index ebdcf52..9bf941a 100644 --- a/internal/service/organizations/policy.go +++ b/internal/service/organizations/policy.go @@ -2,6 +2,7 @@ package organizations import ( "context" + "errors" "fmt" "log" "time" @@ -19,6 +20,8 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) +var errAWSManagedPolicyImport = errors.New("AWS-managed Organizations policy cannot be imported. Use the policy ID directly in your configuration") + func ResourcePolicy() *schema.Resource { return &schema.Resource{ CreateContext: resourcePolicyCreate, @@ -82,7 +85,7 @@ func resourcePolicyCreate(ctx context.Context, d *schema.ResourceData, meta inte var err error var resp *organizations.CreatePolicyOutput - err = resource.Retry(4*time.Minute, func() *resource.RetryError { + err = resource.RetryContext(ctx, 4*time.Minute, func() *resource.RetryError { resp, err = conn.CreatePolicy(input) if err != nil { if tfawserr.ErrCodeEquals(err, organizations.ErrCodeFinalizingOrganizationException) { @@ -134,11 +137,21 @@ func resourcePolicyRead(ctx context.Context, d *schema.ResourceData, meta interf return nil } - d.Set("arn", resp.Policy.PolicySummary.Arn) - d.Set("content", resp.Policy.Content) - d.Set("description", resp.Policy.PolicySummary.Description) - d.Set("name", resp.Policy.PolicySummary.Name) - d.Set("type", resp.Policy.PolicySummary.Type) + if err := d.Set("arn", resp.Policy.PolicySummary.Arn); err != nil { + return diag.FromErr(fmt.Errorf("error setting arn: %w", err)) + } + if err := d.Set("content", resp.Policy.Content); err != nil { + return diag.FromErr(fmt.Errorf("error setting content: %w", err)) + } + if err := d.Set("description", resp.Policy.PolicySummary.Description); err != nil { + return diag.FromErr(fmt.Errorf("error setting description: %w", err)) + } + if err := d.Set("name", resp.Policy.PolicySummary.Name); err != nil { + return diag.FromErr(fmt.Errorf("error setting name: %w", err)) + } + if err := d.Set("type", resp.Policy.PolicySummary.Type); err != nil { + return diag.FromErr(fmt.Errorf("error setting type: %w", err)) + } if aws.BoolValue(resp.Policy.PolicySummary.AwsManaged) { return diag.Diagnostics{ @@ -234,7 +247,7 @@ func resourcePolicyImport(ctx context.Context, d *schema.ResourceData, meta inte } if aws.BoolValue(resp.Policy.PolicySummary.AwsManaged) { - return nil, fmt.Errorf("AWS-managed Organizations policy (%s) cannot be imported. Use the policy ID directly in your configuration.", d.Id()) + return nil, fmt.Errorf("%w: %s", errAWSManagedPolicyImport, d.Id()) } return []*schema.ResourceData{d}, nil diff --git a/internal/service/organizations/policy_attachment.go b/internal/service/organizations/policy_attachment.go index 20506f7..39486ff 100644 --- a/internal/service/organizations/policy_attachment.go +++ b/internal/service/organizations/policy_attachment.go @@ -1,6 +1,8 @@ package organizations import ( + "context" + "errors" "fmt" "log" "strings" @@ -15,13 +17,15 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) +var errInvalidPolicyAttachmentID = errors.New("expected ID in format of TARGETID:POLICYID") + func ResourcePolicyAttachment() *schema.Resource { return &schema.Resource{ Create: resourcePolicyAttachmentCreate, Read: resourcePolicyAttachmentRead, Delete: resourcePolicyAttachmentDelete, Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, + StateContext: schema.ImportStatePassthroughContext, }, Schema: map[string]*schema.Schema{ @@ -52,7 +56,7 @@ func resourcePolicyAttachmentCreate(d *schema.ResourceData, meta interface{}) er log.Printf("[DEBUG] Creating Organizations Policy Attachment: %s", input) - err := resource.Retry(4*time.Minute, func() *resource.RetryError { + err := resource.RetryContext(context.Background(), 4*time.Minute, func() *resource.RetryError { _, err := conn.AttachPolicy(input) if err != nil { if tfawserr.ErrCodeEquals(err, organizations.ErrCodeFinalizingOrganizationException) { @@ -70,7 +74,7 @@ func resourcePolicyAttachmentCreate(d *schema.ResourceData, meta interface{}) er } if err != nil { - return fmt.Errorf("error creating Organizations Policy Attachment: %s", err) + return fmt.Errorf("error creating Organizations Policy Attachment: %w", err) } d.SetId(fmt.Sprintf("%s:%s", targetID, policyID)) @@ -117,8 +121,12 @@ func resourcePolicyAttachmentRead(d *schema.ResourceData, meta interface{}) erro return nil } - d.Set("policy_id", policyID) - d.Set("target_id", targetID) + if err := d.Set("policy_id", policyID); err != nil { + return fmt.Errorf("error setting policy_id: %w", err) + } + if err := d.Set("target_id", targetID); err != nil { + return fmt.Errorf("error setting target_id: %w", err) + } return nil } @@ -152,7 +160,7 @@ func resourcePolicyAttachmentDelete(d *schema.ResourceData, meta interface{}) er func DecodePolicyAttachmentID(id string) (string, string, error) { idParts := strings.Split(id, ":") if len(idParts) != 2 { - return "", "", fmt.Errorf("expected ID in format of TARGETID:POLICYID, received: %s", id) + return "", "", fmt.Errorf("%w, received: %s", errInvalidPolicyAttachmentID, id) } return idParts[0], idParts[1], nil } diff --git a/internal/service/organizations/resource_tags_data_source.go b/internal/service/organizations/resource_tags_data_source.go index 7cc3a38..b80af5d 100644 --- a/internal/service/organizations/resource_tags_data_source.go +++ b/internal/service/organizations/resource_tags_data_source.go @@ -51,8 +51,8 @@ func dataSourceResourceTagsRead(d *schema.ResourceData, meta interface{}) error if err := d.Set("tags", KeyValueTags(tags).Map()); err != nil { return fmt.Errorf("error setting tags: %w", err) } - } else { - d.Set("tags", nil) + } else if err := d.Set("tags", nil); err != nil { + return fmt.Errorf("error setting tags: %w", err) } return nil diff --git a/internal/service/securityhub/resource_control_disablement.go b/internal/service/securityhub/resource_control_disablement.go index 3fc6d94..2ce8a15 100644 --- a/internal/service/securityhub/resource_control_disablement.go +++ b/internal/service/securityhub/resource_control_disablement.go @@ -61,7 +61,7 @@ func resourceAwsSecurityHubControlDisablementCreate(d *schema.ResourceData, meta } if _, err := conn.UpdateStandardsControl(input); err != nil { - return fmt.Errorf("error disabling security hub control %s: %s", controlArn, err) + return fmt.Errorf("error disabling security hub control %s: %w", controlArn, err) } d.SetId(controlArn) @@ -75,7 +75,7 @@ func resourceAwsSecurityHubControlDisablementRead(d *schema.ResourceData, meta i control, err := FindSecurityHubControl(conn, controlArn) if err != nil { - return fmt.Errorf("error reading security hub control %s: %s", controlArn, err) + return fmt.Errorf("error reading security hub control %s: %w", controlArn, err) } log.Printf("[DEBUG] Received Security Hub Control: %s", control) @@ -106,7 +106,7 @@ func resourceAwsSecurityHubControlDisablementUpdate(d *schema.ResourceData, meta } if _, err := conn.UpdateStandardsControl(input); err != nil { - return fmt.Errorf("error disabling security hub control %s: %s", controlArn, err) + return fmt.Errorf("error disabling security hub control %s: %w", controlArn, err) } } @@ -124,7 +124,7 @@ func resourceAwsSecurityHubControlDisablementDelete(d *schema.ResourceData, meta } if _, err := conn.UpdateStandardsControl(input); err != nil { - return fmt.Errorf("error updating security hub control %s: %s", controlArn, err) + return fmt.Errorf("error enabling security hub control %s: %w", controlArn, err) } return nil diff --git a/internal/service/securityhub/resource_organization_settings.go b/internal/service/securityhub/resource_organization_settings.go index 656207f..38f448a 100644 --- a/internal/service/securityhub/resource_organization_settings.go +++ b/internal/service/securityhub/resource_organization_settings.go @@ -1,6 +1,7 @@ package securityhub import ( + "errors" "fmt" "github.com/aws/aws-sdk-go/aws" @@ -11,6 +12,11 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) +var ( + errDesignatingMembers = errors.New("error designating security hub administrator account members") + errRemovingMembers = errors.New("error removing security hub administrator account members") +) + func ResourceSecurityHubOrganizationSettings() *schema.Resource { return &schema.Resource{ Description: `Enables a list of accounts as Security Hub member accounts in an existing AWS Organization. @@ -69,10 +75,12 @@ func resourceAwsSecurityHubOrganizationSettingsRead(d *schema.ResourceData, meta enabled, err := IsSecurityHubOrganizationSettingsAutoEnabled(conn) if err != nil { - return fmt.Errorf("error reading security hub organization settings: %s", err) + return fmt.Errorf("error reading security hub organization settings: %w", err) } - d.Set("auto_enable_new_accounts", enabled) + if err := d.Set("auto_enable_new_accounts", enabled); err != nil { + return fmt.Errorf("error setting auto_enable_new_accounts: %w", err) + } return nil } @@ -84,7 +92,7 @@ func resourceAwsSecurityHubOrganizationSettingsUpdate(d *schema.ResourceData, me autoEnable := new.(bool) if err := updateSecurityHubOrganizationSettings(conn, autoEnable); err != nil { - return fmt.Errorf("error updating security hub organization settings: %s", err) + return fmt.Errorf("error updating security hub organization settings: %w", err) } } @@ -97,14 +105,14 @@ func resourceAwsSecurityHubOrganizationSettingsUpdate(d *schema.ResourceData, me membersToAdd := flex.Diff(newExpanded, oldExpanded) if len(membersToAdd) > 0 { if err := addSecurityHubOrganizationMembers(conn, membersToAdd); err != nil { - return fmt.Errorf("error setting security hub organization members: %s", err) + return fmt.Errorf("error setting security hub organization members: %w", err) } } membersToRemove := flex.Diff(oldExpanded, newExpanded) if len(membersToRemove) > 0 { if err := removeSecurityHubOrganizationMembers(conn, membersToRemove); err != nil { - return fmt.Errorf("error removing security hub organization members: %s", err) + return fmt.Errorf("error removing security hub organization members: %w", err) } } } @@ -120,7 +128,7 @@ func updateSecurityHubOrganizationSettings(conn *securityhub.SecurityHub, autoEn AutoEnable: aws.Bool(autoEnable), } if _, err := conn.UpdateOrganizationConfiguration(updateOrgSettingsInput); err != nil { - return fmt.Errorf("error updating security hub administrator account settings: %s", err) + return fmt.Errorf("error updating security hub administrator account settings: %w", err) } return nil } @@ -151,9 +159,9 @@ func addSecurityHubOrganizationMembers(conn *securityhub.SecurityHub, memberAcco if result, err := conn.CreateMembers(createMembersInput); err != nil || len(result.UnprocessedAccounts) > 0 { if err != nil { - return fmt.Errorf("error designating security hub administrator account members: %s", err) + return fmt.Errorf("error designating security hub administrator account members: %w", err) } - return fmt.Errorf("error designating security hub administrator account members: %s", result.UnprocessedAccounts) + return fmt.Errorf("%w: %v", errDesignatingMembers, result.UnprocessedAccounts) } } return nil @@ -171,16 +179,14 @@ func removeSecurityHubOrganizationMembers(conn *securityhub.SecurityHub, memberA } if _, err := conn.DisassociateMembers(disassociateMembersInput); err != nil { - if err != nil { - return fmt.Errorf("error disassociating security hub administrator account members: %s", err) - } + return fmt.Errorf("error disassociating security hub administrator account members: %w", err) } if result, err := conn.DeleteMembers(deleteMembersInput); err != nil || len(result.UnprocessedAccounts) > 0 { if err != nil { - return fmt.Errorf("error removing security hub administrator account members: %s", err) + return fmt.Errorf("error removing security hub administrator account members: %w", err) } - return fmt.Errorf("error removing security hub administrator account members: %s", result.UnprocessedAccounts) + return fmt.Errorf("%w: %v", errRemovingMembers, result.UnprocessedAccounts) } } return nil diff --git a/internal/service/sts/caller_identity_data_source.go b/internal/service/sts/caller_identity_data_source.go index 55f1992..6abc483 100644 --- a/internal/service/sts/caller_identity_data_source.go +++ b/internal/service/sts/caller_identity_data_source.go @@ -86,13 +86,25 @@ func dataSourceCallerIdentityRead(d *schema.ResourceData, meta interface{}) erro log.Printf("[DEBUG] Received Caller Identity: %s", res) d.SetId(aws.StringValue(res.Account)) - d.Set("account_id", res.Account) - d.Set("arn", res.Arn) - d.Set("user_id", res.UserId) + if err := d.Set("account_id", res.Account); err != nil { + return fmt.Errorf("error setting account_id: %w", err) + } + if err := d.Set("arn", res.Arn); err != nil { + return fmt.Errorf("error setting arn: %w", err) + } + if err := d.Set("user_id", res.UserId); err != nil { + return fmt.Errorf("error setting user_id: %w", err) + } - // If the caller identity is an assumed role, get the IAM role ARN and set it as the ARN - if strings.HasPrefix(aws.StringValue(res.Arn), "arn:aws:sts") { - d.Set("eks_role_arn", getIamRoleArnFromCallerRoleArn(aws.StringValue(res.Arn))) + // If the caller identity is an assumed role, get the IAM role ARN and set + // it as the ARN. The check is partition-agnostic so it works across the + // standard AWS partition as well as GovCloud (aws-us-gov) and China + // (aws-cn). + arn := aws.StringValue(res.Arn) + if strings.Contains(arn, ":sts:") && strings.Contains(arn, ":assumed-role/") { + if err := d.Set("eks_role_arn", getIamRoleArnFromCallerRoleArn(arn)); err != nil { + return fmt.Errorf("error setting eks_role_arn: %w", err) + } } return nil diff --git a/internal/tags/key_value_tags.go b/internal/tags/key_value_tags.go index 9409229..7ccee88 100644 --- a/internal/tags/key_value_tags.go +++ b/internal/tags/key_value_tags.go @@ -49,7 +49,7 @@ func (tags KeyValueTags) IgnoreAWS() KeyValueTags { return result } -// GetTags is convenience method that returns the DefaultConfig's Tags, if any +// GetTags is convenience method that returns the DefaultConfig's Tags, if any. func (dc *DefaultConfig) GetTags() KeyValueTags { if dc == nil { return nil @@ -71,7 +71,7 @@ func (dc *DefaultConfig) MergeTags(tags KeyValueTags) KeyValueTags { // TagsEqual returns true if the given configuration's Tags // are equal to those passed in as an argument; -// otherwise returns false +// otherwise returns false. func (dc *DefaultConfig) TagsEqual(tags KeyValueTags) bool { if dc == nil || dc.Tags == nil { return tags == nil @@ -457,11 +457,11 @@ func (tags KeyValueTags) Hash() int { for k, v := range tags { if v == nil || v.Value == nil { - hash = hash ^ create.StringHashcode(k) + hash ^= create.StringHashcode(k) continue } - hash = hash ^ create.StringHashcode(fmt.Sprintf("%s-%s", k, *v.Value)) + hash ^= create.StringHashcode(fmt.Sprintf("%s-%s", k, *v.Value)) } return hash diff --git a/internal/tags/tag_resources.go b/internal/tags/tag_resources.go index cc9971c..a44b47f 100644 --- a/internal/tags/tag_resources.go +++ b/internal/tags/tag_resources.go @@ -1,21 +1,24 @@ package tags import ( + "errors" "fmt" "strings" ) const ( - // Separator used in resource identifiers + // Separator used in resource identifiers. resourceIDSeparator = `,` ) +var errInvalidResourceIdentifier = errors.New("invalid resource identifier") + // GetResourceID parses a given resource identifier for tag identifier and tag key. func GetResourceID(resourceID string) (string, string, error) { parts := strings.SplitN(resourceID, resourceIDSeparator, 2) if len(parts) != 2 || parts[0] == "" || parts[1] == "" { - return "", "", fmt.Errorf("invalid resource identifier (%[1]s), expected ID%[2]sKEY", resourceID, resourceIDSeparator) + return "", "", fmt.Errorf("%w (%[2]s), expected ID%[3]sKEY", errInvalidResourceIdentifier, resourceID, resourceIDSeparator) } return parts[0], parts[1], nil diff --git a/internal/tfresource/not_found_error.go b/internal/tfresource/not_found_error.go index a270d77..1ea65e4 100644 --- a/internal/tfresource/not_found_error.go +++ b/internal/tfresource/not_found_error.go @@ -79,14 +79,19 @@ func (e *TooManyResultsError) As(target interface{}) bool { return true } +var ( + errMultipleResourcesMatched = errors.New("multiple resources matched; use additional constraints to reduce matches to a single resource") + errNoMatchingResource = errors.New("no matching resource found") +) + // SingularDataSourceFindError returns a standard error message for a singular data source's non-nil resource find error. func SingularDataSourceFindError(resourceType string, err error) error { if NotFound(err) { if errors.Is(err, &TooManyResultsError{}) { - return fmt.Errorf("multiple %[1]ss matched; use additional constraints to reduce matches to a single %[1]s", resourceType) + return fmt.Errorf("%w: %s", errMultipleResourcesMatched, resourceType) } - return fmt.Errorf("no matching %[1]s found", resourceType) + return fmt.Errorf("%w: %s", errNoMatchingResource, resourceType) } return fmt.Errorf("error reading %s: %w", resourceType, err) diff --git a/internal/tfresource/retry.go b/internal/tfresource/retry.go index 4927b8c..09b4288 100644 --- a/internal/tfresource/retry.go +++ b/internal/tfresource/retry.go @@ -22,7 +22,7 @@ type Retryable func(error) (bool, error) func RetryWhenContext(ctx context.Context, timeout time.Duration, f func() (interface{}, error), retryable Retryable) (interface{}, error) { var output interface{} - err := resource.Retry(timeout, func() *resource.RetryError { // nosemgrep:ci.helper-schema-resource-Retry-without-TimeoutError-check + err := resource.RetryContext(ctx, timeout, func() *resource.RetryError { // nosemgrep:ci.helper-schema-resource-Retry-without-TimeoutError-check var err error var retry bool @@ -89,6 +89,10 @@ func RetryWhenAWSErrMessageContains(timeout time.Duration, f func() (interface{} return RetryWhenAWSErrMessageContainsContext(context.Background(), timeout, f, code, message) } +// retryStatePlaceholder is an arbitrary, non-nil value returned by the +// state-change Refresh func to satisfy the resource SDK's interface{} contract. +const retryStatePlaceholder = 42 + var errFoundResource = errors.New(`found resource`) // RetryUntilNotFoundContext retries the specified function until it returns a resource.NotFoundError. @@ -147,7 +151,7 @@ func RetryWhenNewResourceNotFound(timeout time.Duration, f func() (interface{}, // This is especially useful for AWS services that are prone to throttling, such as Route53, where // the default durations cause problems. To not use a StateChangeConf argument and revert to the // default, pass in a zero value (i.e., 0*time.Second). -func RetryConfigContext(ctx context.Context, delay time.Duration, delayRand time.Duration, minTimeout time.Duration, pollInterval time.Duration, timeout time.Duration, f resource.RetryFunc) error { +func RetryConfigContext(ctx context.Context, delay time.Duration, delayRand time.Duration, minTimeout time.Duration, pollInterval time.Duration, timeout time.Duration, f resource.RetryFunc) error { //nolint:revive // argument-limit: exposes the StateChangeConf knobs as discrete parameters // These are used to pull the error out of the function; need a mutex to // avoid a data race. var resultErr error @@ -165,13 +169,13 @@ func RetryConfigContext(ctx context.Context, delay time.Duration, delayRand time if rerr == nil { resultErr = nil - return 42, "success", nil + return retryStatePlaceholder, "success", nil } resultErr = rerr.Err if rerr.Retryable { - return 42, "retryableerror", nil + return retryStatePlaceholder, "retryableerror", nil } return nil, "quit", rerr.Err @@ -185,9 +189,9 @@ func RetryConfigContext(ctx context.Context, delay time.Duration, delayRand time if delayRand.Milliseconds() > 0 { // Hitting the API at exactly the same time on each iteration of the retry is more likely to // cause Throttling problems. We introduce randomness in order to help AWS be happier. - rand.Seed(time.Now().UTC().UnixNano()) + r := rand.New(rand.NewSource(time.Now().UTC().UnixNano())) //nolint:gosec // G404: jitter for retry backoff, not security-sensitive - c.Delay = time.Duration(rand.Int63n(delayRand.Milliseconds())) * time.Millisecond + c.Delay = time.Duration(r.Int63n(delayRand.Milliseconds())) * time.Millisecond } if minTimeout.Milliseconds() > 0 { diff --git a/internal/vault/helper/pgpkeys/encrypt_decrypt.go b/internal/vault/helper/pgpkeys/encrypt_decrypt.go index ef767bc..0655d79 100644 --- a/internal/vault/helper/pgpkeys/encrypt_decrypt.go +++ b/internal/vault/helper/pgpkeys/encrypt_decrypt.go @@ -14,10 +14,10 @@ import ( // byte slice with the corresponding public key. // // Note: There is no corresponding test function; this functionality is -// thoroughly tested in the init and rekey command unit tests +// thoroughly tested in the init and rekey command unit tests. func EncryptShares(input [][]byte, pgpKeys []string) ([]string, [][]byte, error) { if len(input) != len(pgpKeys) { - return nil, nil, fmt.Errorf("mismatch between number items to encrypt and number of PGP keys") + return nil, nil, fmt.Errorf("%w: inputs=%d keys=%d", errPGPInputKeysMismatch, len(input), len(pgpKeys)) } encryptedShares := make([][]byte, 0, len(pgpKeys)) entities, err := GetEntities(pgpKeys) @@ -65,7 +65,7 @@ func GetFingerprints(pgpKeys []string, entities []*openpgp.Entity) ([]string, er } // GetEntities takes in a string array of base64-encoded PGP keys and returns -// the openpgp Entities +// the openpgp Entities. func GetEntities(pgpKeys []string) ([]*openpgp.Entity, error) { ret := make([]*openpgp.Entity, 0, len(pgpKeys)) for _, keystring := range pgpKeys { diff --git a/internal/vault/helper/pgpkeys/keybase.go b/internal/vault/helper/pgpkeys/keybase.go index 362d435..68803d8 100644 --- a/internal/vault/helper/pgpkeys/keybase.go +++ b/internal/vault/helper/pgpkeys/keybase.go @@ -3,6 +3,7 @@ package pgpkeys import ( "bytes" "encoding/base64" + "errors" "fmt" "strings" @@ -15,6 +16,15 @@ const ( kbPrefix = "keybase:" ) +var ( + errNoHTTPClient = errors.New("unable to create an http client") + errNonOKResponse = errors.New("got non-OK response") + errPrimaryKeyParseFailed = errors.New("primary key could not be parsed for user") + errPrimaryKeyNil = errors.New("primary key was nil for user") + errKeybaseFetchFailed = errors.New("unable to fetch keys for user(s) from keybase") + errPGPInputKeysMismatch = errors.New("mismatch between number items to encrypt and number of PGP keys") +) + // FetchKeybasePubkeys fetches public keys from Keybase given a set of // usernames, which are derived from correctly formatted input entries. It // doesn't use their client code due to both the API and the fact that it is @@ -23,7 +33,7 @@ const ( func FetchKeybasePubkeys(input []string) (map[string]string, error) { client := cleanhttp.DefaultClient() if client == nil { - return nil, fmt.Errorf("unable to create an http client") + return nil, errNoHTTPClient } if len(input) == 0 { @@ -75,7 +85,7 @@ func FetchKeybasePubkeys(input []string) (map[string]string, error) { } if out.Status.Name != "OK" { - return nil, fmt.Errorf("got non-OK response: %q", out.Status.Name) + return nil, fmt.Errorf("%w: %q", errNonOKResponse, out.Status.Name) } missingNames := make([]string, 0, len(usernames)) @@ -92,10 +102,10 @@ func FetchKeybasePubkeys(input []string) (map[string]string, error) { return nil, err } if len(entityList) != 1 { - return nil, fmt.Errorf("primary key could not be parsed for user %q", usernames[i]) + return nil, fmt.Errorf("%w: %q", errPrimaryKeyParseFailed, usernames[i]) } if entityList[0] == nil { - return nil, fmt.Errorf("primary key was nil for user %q", usernames[i]) + return nil, fmt.Errorf("%w: %q", errPrimaryKeyNil, usernames[i]) } serializedEntity.Reset() @@ -109,7 +119,7 @@ func FetchKeybasePubkeys(input []string) (map[string]string, error) { } if len(missingNames) > 0 { - return nil, fmt.Errorf("unable to fetch keys for user(s) %q from keybase", strings.Join(missingNames, ",")) + return nil, fmt.Errorf("%w: %q", errKeybaseFetchFailed, strings.Join(missingNames, ",")) } return ret, nil diff --git a/internal/vault/sdk/helper/jsonutil/json.go b/internal/vault/sdk/helper/jsonutil/json.go index 51cca5f..10f0c79 100644 --- a/internal/vault/sdk/helper/jsonutil/json.go +++ b/internal/vault/sdk/helper/jsonutil/json.go @@ -2,17 +2,22 @@ package jsonutil import ( "encoding/json" - "fmt" + "errors" "io" ) -// Decodes/Unmarshals the given io.Reader pointing to a JSON, into a desired object +var ( + errReaderNil = errors.New("'io.Reader' being decoded is nil") + errOutNil = errors.New("output parameter 'out' is nil") +) + +// Decodes/Unmarshals the given io.Reader pointing to a JSON, into a desired object. func DecodeJSONFromReader(r io.Reader, out interface{}) error { if r == nil { - return fmt.Errorf("'io.Reader' being decoded is nil") + return errReaderNil } if out == nil { - return fmt.Errorf("output parameter 'out' is nil") + return errOutNil } dec := json.NewDecoder(r) diff --git a/internal/verify/diff.go b/internal/verify/diff.go index 3949727..bde3388 100644 --- a/internal/verify/diff.go +++ b/internal/verify/diff.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "log" @@ -14,6 +15,8 @@ import ( awspolicy "github.com/jen20/awspolicyequivalence" ) +var errTagsIdenticalToDefault = errors.New(`"tags" are identical to those in the "default_tags" configuration block of the provider: please de-duplicate and try again`) + // SetTagsDiff sets the new plan difference with the result of // merging resource tags on to those defined at the provider-level; // returns an error if unsuccessful or if the resource tags are identical @@ -27,7 +30,7 @@ func SetTagsDiff(_ context.Context, diff *schema.ResourceDiff, meta interface{}) resourceTags := tftags.New(diff.Get("tags").(map[string]interface{})) if defaultTagsConfig.TagsEqual(resourceTags) { - return fmt.Errorf(`"tags" are identical to those in the "default_tags" configuration block of the provider: please de-duplicate and try again`) + return errTagsIdenticalToDefault } allTags := defaultTagsConfig.MergeTags(resourceTags).IgnoreConfig(ignoreTagsConfig) @@ -38,15 +41,16 @@ func SetTagsDiff(_ context.Context, diff *schema.ResourceDiff, meta interface{}) // or a change for "tags_all". // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/18366 // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/19005 - if len(allTags) > 0 { + switch { + case len(allTags) > 0: if err := diff.SetNew("tags_all", allTags.Map()); err != nil { return fmt.Errorf("error setting new tags_all diff: %w", err) } - } else if len(diff.Get("tags_all").(map[string]interface{})) > 0 { + case len(diff.Get("tags_all").(map[string]interface{})) > 0: if err := diff.SetNewComputed("tags_all"); err != nil { return fmt.Errorf("error setting tags_all to computed: %w", err) } - } else if diff.HasChange("tags_all") { + case diff.HasChange("tags_all"): if err := diff.SetNewComputed("tags_all"); err != nil { return fmt.Errorf("error setting tags_all to computed: %w", err) } diff --git a/internal/verify/resource_differ.go b/internal/verify/resource_differ.go index 2ce5b84..3909efa 100644 --- a/internal/verify/resource_differ.go +++ b/internal/verify/resource_differ.go @@ -4,7 +4,7 @@ package verify // Implementations: // * schema.ResourceData // * schema.ResourceDiff -// FIXME: can be removed if https://github.com/hashicorp/terraform-plugin-sdk/pull/626/files is merged +// FIXME: can be removed if https://github.com/hashicorp/terraform-plugin-sdk/pull/626/files is merged. type ResourceDiffer interface { HasChange(string) bool } diff --git a/internal/verify/retry.go b/internal/verify/retry.go index 5561710..0cfb5f3 100644 --- a/internal/verify/retry.go +++ b/internal/verify/retry.go @@ -1,6 +1,7 @@ package verify import ( + "context" "time" "github.com/cloudposse/terraform-provider-awsutils/internal/tfresource" @@ -10,7 +11,7 @@ import ( func RetryOnAWSCode(code string, f func() (interface{}, error)) (interface{}, error) { var resp interface{} - err := resource.Retry(2*time.Minute, func() *resource.RetryError { + err := resource.RetryContext(context.Background(), 2*time.Minute, func() *resource.RetryError { var err error resp, err = f() if err != nil { diff --git a/internal/verify/validate.go b/internal/verify/validate.go index 63a3d83..cb28ea4 100644 --- a/internal/verify/validate.go +++ b/internal/verify/validate.go @@ -1,6 +1,7 @@ package verify import ( + "errors" "fmt" "net" "regexp" @@ -19,6 +20,14 @@ var ( regionRegexp = regexp.MustCompile(`^[a-z]{2}(-[a-z]+)+-\d$`) ) +const ( + launchTemplateIDMaxLen = 255 + launchTemplatePrefixMaxLen = 99 + launchTemplateNameMaxLen = 125 +) + +var errValidation = errors.New("validation error") + func ValidARN(v interface{}, k string) (ws []string, errors []error) { value := v.(string) @@ -28,26 +37,26 @@ func ValidARN(v interface{}, k string) (ws []string, errors []error) { parsedARN, err := arn.Parse(value) if err != nil { - errors = append(errors, fmt.Errorf("%q (%s) is an invalid ARN: %s", k, value, err)) + errors = append(errors, fmt.Errorf("%w: %q (%s) is an invalid ARN: %w", errValidation, k, value, err)) return ws, errors } if parsedARN.Partition == "" { - errors = append(errors, fmt.Errorf("%q (%s) is an invalid ARN: missing partition value", k, value)) + errors = append(errors, fmt.Errorf("%w: %q (%s) is an invalid ARN: missing partition value", errValidation, k, value)) } else if !partitionRegexp.MatchString(parsedARN.Partition) { - errors = append(errors, fmt.Errorf("%q (%s) is an invalid ARN: invalid partition value (expecting to match regular expression: %s)", k, value, partitionRegexp)) + errors = append(errors, fmt.Errorf("%w: %q (%s) is an invalid ARN: invalid partition value (expecting to match regular expression: %s)", errValidation, k, value, partitionRegexp)) } if parsedARN.Region != "" && !regionRegexp.MatchString(parsedARN.Region) { - errors = append(errors, fmt.Errorf("%q (%s) is an invalid ARN: invalid region value (expecting to match regular expression: %s)", k, value, regionRegexp)) + errors = append(errors, fmt.Errorf("%w: %q (%s) is an invalid ARN: invalid region value (expecting to match regular expression: %s)", errValidation, k, value, regionRegexp)) } if parsedARN.AccountID != "" && !accountIDRegexp.MatchString(parsedARN.AccountID) { - errors = append(errors, fmt.Errorf("%q (%s) is an invalid ARN: invalid account ID value (expecting to match regular expression: %s)", k, value, accountIDRegexp)) + errors = append(errors, fmt.Errorf("%w: %q (%s) is an invalid ARN: invalid account ID value (expecting to match regular expression: %s)", errValidation, k, value, accountIDRegexp)) } if parsedARN.Resource == "" { - errors = append(errors, fmt.Errorf("%q (%s) is an invalid ARN: missing resource value", k, value)) + errors = append(errors, fmt.Errorf("%w: %q (%s) is an invalid ARN: missing resource value", errValidation, k, value)) } return ws, errors @@ -60,8 +69,8 @@ func ValidAccountID(v interface{}, k string) (ws []string, errors []error) { pattern := `^\d{12}$` if !regexp.MustCompile(pattern).MatchString(value) { errors = append(errors, fmt.Errorf( - "%q doesn't look like AWS Account ID (exactly 12 digits): %q", - k, value)) + "%w: %q doesn't look like AWS Account ID (exactly 12 digits): %q", + errValidation, k, value)) } return ws, errors @@ -69,22 +78,22 @@ func ValidAccountID(v interface{}, k string) (ws []string, errors []error) { // validateCIDRBlock validates that the specified CIDR block is valid: // - The CIDR block parses to an IP address and network -// - The CIDR block is the CIDR block for the network +// - The CIDR block is the CIDR block for the network. func validateCIDRBlock(cidr string) error { _, ipnet, err := net.ParseCIDR(cidr) if err != nil { - return fmt.Errorf("%q is not a valid CIDR block: %w", cidr, err) + return fmt.Errorf("%w: %q is not a valid CIDR block: %w", errValidation, cidr, err) } if !CIDRBlocksEqual(cidr, ipnet.String()) { - return fmt.Errorf("%q is not a valid CIDR block; did you mean %q?", cidr, ipnet) + return fmt.Errorf("%w: %q is not a valid CIDR block; did you mean %q?", errValidation, cidr, ipnet) } return nil } // ValidCIDRNetworkAddress ensures that the string value is a valid CIDR that -// represents a network address - it adds an error otherwise +// represents a network address - it adds an error otherwise. func ValidCIDRNetworkAddress(v interface{}, k string) (ws []string, errors []error) { if err := validateCIDRBlock(v.(string)); err != nil { errors = append(errors, err) @@ -98,15 +107,15 @@ func ValidIAMPolicyJSON(v interface{}, k string) (ws []string, errors []error) { // IAM Policy documents need to be valid JSON, and pass legacy parsing value := v.(string) if len(value) < 1 { - errors = append(errors, fmt.Errorf("%q contains an invalid JSON policy", k)) + errors = append(errors, fmt.Errorf("%w: %q contains an invalid JSON policy", errValidation, k)) return ws, errors } if value[:1] != "{" { - errors = append(errors, fmt.Errorf("%q contains an invalid JSON policy", k)) + errors = append(errors, fmt.Errorf("%w: %q contains an invalid JSON policy", errValidation, k)) return ws, errors } if _, err := structure.NormalizeJsonString(v); err != nil { - errors = append(errors, fmt.Errorf("%q contains an invalid JSON: %s", k, err)) + errors = append(errors, fmt.Errorf("%w: %q contains an invalid JSON: %w", errValidation, k, err)) } return ws, errors } @@ -114,20 +123,20 @@ func ValidIAMPolicyJSON(v interface{}, k string) (ws []string, errors []error) { // ValidateIPv4CIDRBlock validates that the specified CIDR block is valid: // - The CIDR block parses to an IP address and network // - The IP address is an IPv4 address -// - The CIDR block is the CIDR block for the network +// - The CIDR block is the CIDR block for the network. func ValidateIPv4CIDRBlock(cidr string) error { ip, ipnet, err := net.ParseCIDR(cidr) if err != nil { - return fmt.Errorf("%q is not a valid CIDR block: %w", cidr, err) + return fmt.Errorf("%w: %q is not a valid CIDR block: %w", errValidation, cidr, err) } ipv4 := ip.To4() if ipv4 == nil { - return fmt.Errorf("%q is not a valid IPv4 CIDR block", cidr) + return fmt.Errorf("%w: %q is not a valid IPv4 CIDR block", errValidation, cidr) } if !CIDRBlocksEqual(cidr, ipnet.String()) { - return fmt.Errorf("%q is not a valid IPv4 CIDR block; did you mean %q?", cidr, ipnet) + return fmt.Errorf("%w: %q is not a valid IPv4 CIDR block; did you mean %q?", errValidation, cidr, ipnet) } return nil @@ -136,27 +145,27 @@ func ValidateIPv4CIDRBlock(cidr string) error { // ValidateIPv6CIDRBlock validates that the specified CIDR block is valid: // - The CIDR block parses to an IP address and network // - The IP address is an IPv6 address -// - The CIDR block is the CIDR block for the network +// - The CIDR block is the CIDR block for the network. func ValidateIPv6CIDRBlock(cidr string) error { ip, ipnet, err := net.ParseCIDR(cidr) if err != nil { - return fmt.Errorf("%q is not a valid CIDR block: %w", cidr, err) + return fmt.Errorf("%w: %q is not a valid CIDR block: %w", errValidation, cidr, err) } ipv4 := ip.To4() if ipv4 != nil { - return fmt.Errorf("%q is not a valid IPv6 CIDR block", cidr) + return fmt.Errorf("%w: %q is not a valid IPv6 CIDR block", errValidation, cidr) } if !CIDRBlocksEqual(cidr, ipnet.String()) { - return fmt.Errorf("%q is not a valid IPv6 CIDR block; did you mean %q?", cidr, ipnet) + return fmt.Errorf("%w: %q is not a valid IPv6 CIDR block; did you mean %q?", errValidation, cidr, ipnet) } return nil } // ValidIPv4CIDRNetworkAddress ensures that the string value is a valid IPv4 CIDR that -// represents a network address - it adds an error otherwise +// represents a network address - it adds an error otherwise. func ValidIPv4CIDRNetworkAddress(v interface{}, k string) (ws []string, errors []error) { if err := ValidateIPv4CIDRBlock(v.(string)); err != nil { errors = append(errors, err) @@ -167,7 +176,7 @@ func ValidIPv4CIDRNetworkAddress(v interface{}, k string) (ws []string, errors [ } // ValidIPv6CIDRNetworkAddress ensures that the string value is a valid IPv6 CIDR that -// represents a network address - it adds an error otherwise +// represents a network address - it adds an error otherwise. func ValidIPv6CIDRNetworkAddress(v interface{}, k string) (ws []string, errors []error) { if err := ValidateIPv6CIDRBlock(v.(string)); err != nil { errors = append(errors, err) @@ -179,27 +188,29 @@ func ValidIPv6CIDRNetworkAddress(v interface{}, k string) (ws []string, errors [ func ValidLaunchTemplateID(v interface{}, k string) (ws []string, errors []error) { value := v.(string) - if len(value) < 1 { - errors = append(errors, fmt.Errorf("%q cannot be shorter than 1 character", k)) - } else if len(value) > 255 { - errors = append(errors, fmt.Errorf("%q cannot be longer than 255 characters", k)) - } else if !regexp.MustCompile(`^lt\-[a-z0-9]+$`).MatchString(value) { + switch { + case len(value) < 1: + errors = append(errors, fmt.Errorf("%w: %q cannot be shorter than 1 character", errValidation, k)) + case len(value) > launchTemplateIDMaxLen: + errors = append(errors, fmt.Errorf("%w: %q cannot be longer than %d characters", errValidation, k, launchTemplateIDMaxLen)) + case !regexp.MustCompile(`^lt\-[a-z0-9]+$`).MatchString(value): errors = append(errors, fmt.Errorf( - "%q must begin with 'lt-' and be comprised of only alphanumeric characters: %v", k, value)) + "%w: %q must begin with 'lt-' and be comprised of only alphanumeric characters: %v", errValidation, k, value)) } return ws, errors } func ValidLaunchTemplateName(v interface{}, k string) (ws []string, errors []error) { value := v.(string) - if len(value) < 3 { - errors = append(errors, fmt.Errorf("%q cannot be less than 3 characters", k)) - } else if strings.HasSuffix(k, "prefix") && len(value) > 99 { - errors = append(errors, fmt.Errorf("%q cannot be longer than 99 characters, name is limited to 125", k)) - } else if !strings.HasSuffix(k, "prefix") && len(value) > 125 { - errors = append(errors, fmt.Errorf("%q cannot be longer than 125 characters", k)) - } else if !regexp.MustCompile(`^[0-9a-zA-Z()./_\-]+$`).MatchString(value) { - errors = append(errors, fmt.Errorf("%q can only alphanumeric characters and ()./_- symbols", k)) + switch { + case len(value) < 3: + errors = append(errors, fmt.Errorf("%w: %q cannot be less than 3 characters", errValidation, k)) + case strings.HasSuffix(k, "prefix") && len(value) > launchTemplatePrefixMaxLen: + errors = append(errors, fmt.Errorf("%w: %q cannot be longer than %d characters, name is limited to %d", errValidation, k, launchTemplatePrefixMaxLen, launchTemplateNameMaxLen)) + case !strings.HasSuffix(k, "prefix") && len(value) > launchTemplateNameMaxLen: + errors = append(errors, fmt.Errorf("%w: %q cannot be longer than %d characters", errValidation, k, launchTemplateNameMaxLen)) + case !regexp.MustCompile(`^[0-9a-zA-Z()./_\-]+$`).MatchString(value): + errors = append(errors, fmt.Errorf("%w: %q can only alphanumeric characters and ()./_- symbols", errValidation, k)) } return ws, errors } @@ -212,7 +223,7 @@ func ValidOnceADayWindowFormat(v interface{}, k string) (ws []string, errors []e value := v.(string) if !regexp.MustCompile(validTimeFormatConsolidated).MatchString(value) { errors = append(errors, fmt.Errorf( - "%q must satisfy the format of \"hh24:mi-hh24:mi\".", k)) + "%w: %q must satisfy the format of \"hh24:mi-hh24:mi\"", errValidation, k)) } return ws, errors } @@ -225,7 +236,7 @@ func ValidOnceAWeekWindowFormat(v interface{}, k string) (ws []string, errors [] value := strings.ToLower(v.(string)) if !regexp.MustCompile(validTimeFormatConsolidated).MatchString(value) { errors = append(errors, fmt.Errorf( - "%q must satisfy the format of \"ddd:hh24:mi-ddd:hh24:mi\".", k)) + "%w: %q must satisfy the format of \"ddd:hh24:mi-ddd:hh24:mi\"", errValidation, k)) } return ws, errors } @@ -233,12 +244,10 @@ func ValidOnceAWeekWindowFormat(v interface{}, k string) (ws []string, errors [] func ValidStringIsJSONOrYAML(v interface{}, k string) (ws []string, errors []error) { if looksLikeJsonString(v) { if _, err := structure.NormalizeJsonString(v); err != nil { - errors = append(errors, fmt.Errorf("%q contains an invalid JSON: %s", k, err)) - } - } else { - if _, err := checkYAMLString(v); err != nil { - errors = append(errors, fmt.Errorf("%q contains an invalid YAML: %s", k, err)) + errors = append(errors, fmt.Errorf("%w: %q contains an invalid JSON: %w", errValidation, k, err)) } + } else if _, err := checkYAMLString(v); err != nil { + errors = append(errors, fmt.Errorf("%w: %q contains an invalid YAML: %w", errValidation, k, err)) } return ws, errors } @@ -247,11 +256,11 @@ func ValidStringIsJSONOrYAML(v interface{}, k string) (ws []string, errors []err // Some arguments require three values: true, false, and "" (unspecified). // This ValidateFunc returns a custom message since the message with // validation.StringInSlice([]string{"", "false", "true"}, false) is confusing: -// to be one of [ false true], got 1 +// to be one of [ false true], got 1. func ValidTypeStringNullableBoolean(v interface{}, k string) (ws []string, es []error) { value, ok := v.(string) if !ok { - es = append(es, fmt.Errorf("expected type of %s to be string", k)) + es = append(es, fmt.Errorf("%w: expected type of %s to be string", errValidation, k)) return ws, es } @@ -261,7 +270,7 @@ func ValidTypeStringNullableBoolean(v interface{}, k string) (ws []string, es [] } } - es = append(es, fmt.Errorf("expected %s to be one of [\"\", false, true], got %s", k, value)) + es = append(es, fmt.Errorf("%w: expected %s to be one of [\"\", false, true], got %s", errValidation, k, value)) return ws, es } @@ -270,7 +279,7 @@ func ValidTypeStringNullableBoolean(v interface{}, k string) (ws []string, es [] func ValidTypeStringNullableFloat(v interface{}, k string) (ws []string, es []error) { value, ok := v.(string) if !ok { - es = append(es, fmt.Errorf("expected type of %s to be string", k)) + es = append(es, fmt.Errorf("%w: expected type of %s to be string", errValidation, k)) return ws, es } @@ -279,7 +288,7 @@ func ValidTypeStringNullableFloat(v interface{}, k string) (ws []string, es []er } if _, err := strconv.ParseFloat(value, 64); err != nil { - es = append(es, fmt.Errorf("%s: cannot parse '%s' as float: %s", k, value, err)) + es = append(es, fmt.Errorf("%w: %s: cannot parse '%s' as float: %w", errValidation, k, value, err)) } return ws, es @@ -292,7 +301,7 @@ func ValidUTCTimestamp(v interface{}, k string) (ws []string, errors []error) { value := v.(string) _, err := time.Parse(time.RFC3339, value) if err != nil { - errors = append(errors, fmt.Errorf("%q must be in RFC3339 time format %q. Example: %s", k, time.RFC3339, err)) + errors = append(errors, fmt.Errorf("%w: %q must be in RFC3339 time format %q. Example: %w", errValidation, k, time.RFC3339, err)) } return ws, errors } diff --git a/main.go b/main.go index 8fe3289..ef7af09 100644 --- a/main.go +++ b/main.go @@ -25,7 +25,7 @@ func main() { } logFlags := log.Flags() - logFlags = logFlags &^ (log.Ldate | log.Ltime) + logFlags &^= (log.Ldate | log.Ltime) log.SetFlags(logFlags) err = tf5server.Serve( diff --git a/names/errors.go b/names/errors.go index 983b938..b926e20 100644 --- a/names/errors.go +++ b/names/errors.go @@ -25,7 +25,12 @@ const ( ErrActionWaitingForUpdate = "waiting for update" ) -// ProblemStandardMessage is a standardized message for reporting errors and warnings +var ( + errProviderError = errors.New("provider error") + errNotFoundRemovingFromState = errors.New("not found, removing from state") +) + +// ProblemStandardMessage is a standardized message for reporting errors and warnings. func ProblemStandardMessage(service, action, resource, id string, gotError error) string { hf, err := FullHumanFriendly(service) if err != nil { @@ -39,13 +44,13 @@ func ProblemStandardMessage(service, action, resource, id string, gotError error return fmt.Sprintf("%s %s %s (%s): %s", action, hf, resource, id, gotError) } -// Error returns an errors.Error with a standardized error message +// Error returns an errors.Error with a standardized error message. func Error(service, action, resource, id string, gotError error) error { - return errors.New(ProblemStandardMessage(service, action, resource, id, gotError)) + return fmt.Errorf("%w: %s", errProviderError, ProblemStandardMessage(service, action, resource, id, gotError)) } // DiagError returns a 1-length diag.Diagnostics with a diag.Error-level diag.Diagnostic -// with a standardized error message +// with a standardized error message. func DiagError(service, action, resource, id string, gotError error) diag.Diagnostics { return diag.Diagnostics{ diag.Diagnostic{ @@ -58,7 +63,7 @@ func DiagError(service, action, resource, id string, gotError error) diag.Diagno // ErrorSetting returns an errors.Error with a standardized error message when setting // arguments and attributes values. func ErrorSetting(service, resource, id, argument string, gotError error) error { - return errors.New(ProblemStandardMessage(service, fmt.Sprintf("%s %s", ErrActionSetting, argument), resource, id, gotError)) + return fmt.Errorf("%w: %s", errProviderError, ProblemStandardMessage(service, fmt.Sprintf("%s %s", ErrActionSetting, argument), resource, id, gotError)) } // DiagErrorSetting returns an errors.Error with a standardized error message when setting @@ -68,8 +73,8 @@ func DiagErrorSetting(service, resource, id, argument string, gotError error) di } // AddWarning returns diag.Diagnostics with an additional diag.Diagnostic containing -// a warning using a standardized problem message -func AddWarning(diags diag.Diagnostics, service, action, resource, id string, gotError error) diag.Diagnostics { +// a warning using a standardized problem message. +func AddWarning(diags diag.Diagnostics, service, action, resource, id string, gotError error) diag.Diagnostics { //nolint:revive // argument-limit: signature matches DiagError for parity return append(diags, diag.Diagnostic{ Severity: diag.Warning, @@ -79,21 +84,21 @@ func AddWarning(diags diag.Diagnostics, service, action, resource, id string, go } // AddWarningNotFoundRemoveState returns diag.Diagnostics with an additional diag.Diagnostic containing -// a warning using a standardized problem message +// a warning using a standardized problem message. func AddWarningNotFoundRemoveState(service, action, resource, id string) diag.Diagnostics { return append(diag.Diagnostics{}, diag.Diagnostic{ Severity: diag.Warning, - Summary: ProblemStandardMessage(service, action, resource, id, errors.New("not found, removing from state")), + Summary: ProblemStandardMessage(service, action, resource, id, errNotFoundRemovingFromState), }, ) } -// WarnLog logs to the default logger a standardized problem message +// WarnLog logs to the default logger a standardized problem message. func WarnLog(service, action, resource, id string, gotError error) { log.Printf("[WARN] %s", ProblemStandardMessage(service, action, resource, id, gotError)) } func LogNotFoundRemoveState(service, action, resource, id string) { - WarnLog(service, action, resource, id, errors.New("not found, removing from state")) + WarnLog(service, action, resource, id, errNotFoundRemovingFromState) } diff --git a/names/names.go b/names/names.go index 5da8fae..ee94b9a 100644 --- a/names/names.go +++ b/names/names.go @@ -16,11 +16,23 @@ package names import ( _ "embed" "encoding/csv" + "errors" "fmt" "log" "strings" ) +const errFmtSentinelWithDetail = "%w: %s" + +var ( + errServiceAliasNotFound = errors.New("unable to find service for service alias") + errNoServiceData = errors.New("no service data found") + errUnsupportedSDKGoVersion = errors.New("unsupported AWS SDK Go version") + errSDKGoV1PackageNotFound = errors.New("getting AWS SDK Go v1 package: not found") + errSDKGoV2PackageNotFound = errors.New("getting AWS SDK Go v2 package: not found") + errSDKGoV1ClientTypeNotFound = errors.New("getting AWS SDK Go v1 client type name: not found") +) + // This "should" be defined by the AWS Go SDK v2, but currently isn't. const ( KendraEndpointID = "kendra" @@ -43,7 +55,7 @@ type ServiceDatum struct { ProviderNameUpper string } -// serviceData key is the AWS provider service package +// serviceData key is the AWS provider service package. var serviceData map[string]*ServiceDatum func init() { @@ -120,7 +132,7 @@ func ProviderPackageForAlias(serviceAlias string) (string, error) { } } - return "", fmt.Errorf("unable to find service for service alias %s", serviceAlias) + return "", fmt.Errorf(errFmtSentinelWithDetail, errServiceAliasNotFound, serviceAlias) } func ProviderPackages() []string { @@ -150,7 +162,7 @@ func ProviderNameUpper(service string) (string, error) { return v.ProviderNameUpper, nil } - return "", fmt.Errorf("no service data found for %s", service) + return "", fmt.Errorf(errFmtSentinelWithDetail, errNoServiceData, service) } func DeprecatedEnvVar(service string) string { @@ -182,7 +194,7 @@ func FullHumanFriendly(service string) (string, error) { return FullHumanFriendly(s) } - return "", fmt.Errorf("no service data found for %s", service) + return "", fmt.Errorf(errFmtSentinelWithDetail, errNoServiceData, service) } func AWSGoPackage(providerPackage string, version int) (string, error) { @@ -192,7 +204,7 @@ func AWSGoPackage(providerPackage string, version int) (string, error) { case 2: return AWSGoV2Package(providerPackage) default: - return "", fmt.Errorf("unsupported AWS SDK Go version: %d", version) + return "", fmt.Errorf("%w: %d", errUnsupportedSDKGoVersion, version) } } @@ -201,7 +213,7 @@ func AWSGoV1Package(providerPackage string) (string, error) { return v.GoV1Package, nil } - return "", fmt.Errorf("getting AWS SDK Go v1 package, %s not found", providerPackage) + return "", fmt.Errorf(errFmtSentinelWithDetail, errSDKGoV1PackageNotFound, providerPackage) } func AWSGoV2Package(providerPackage string) (string, error) { @@ -209,7 +221,7 @@ func AWSGoV2Package(providerPackage string) (string, error) { return v.GoV2Package, nil } - return "", fmt.Errorf("getting AWS SDK Go v2 package, %s not found", providerPackage) + return "", fmt.Errorf(errFmtSentinelWithDetail, errSDKGoV2PackageNotFound, providerPackage) } func AWSGoClientTypeName(providerPackage string, version int) (string, error) { @@ -219,7 +231,7 @@ func AWSGoClientTypeName(providerPackage string, version int) (string, error) { case 2: return "Client", nil default: - return "", fmt.Errorf("unsupported AWS SDK Go version: %d", version) + return "", fmt.Errorf("%w: %d", errUnsupportedSDKGoVersion, version) } } @@ -228,5 +240,5 @@ func AWSGoV1ClientTypeName(providerPackage string) (string, error) { return v.GoV1ClientTypeName, nil } - return "", fmt.Errorf("getting AWS SDK Go v1 client type name, %s not found", providerPackage) + return "", fmt.Errorf(errFmtSentinelWithDetail, errSDKGoV1ClientTypeNotFound, providerPackage) } diff --git a/version/version.go b/version/version.go index 081f194..7f14571 100644 --- a/version/version.go +++ b/version/version.go @@ -1,4 +1,4 @@ package version -// ProviderVersion is set during the release process to the release version of the binary +// ProviderVersion is set during the release process to the release version of the binary. var ProviderVersion = "dev"