Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 13 additions & 15 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,27 +29,25 @@ 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("<reason>")` with a descriptive reason; do not use `t.Skip`/`t.SkipNow`
- pattern: ^path\.Join$
msg: Use `filepath.Join` for OS-appropriate path separators instead of `path.Join` (which always uses forward slashes)
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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
150 changes: 86 additions & 64 deletions internal/acctest/acctest.go

Large diffs are not rendered by default.

20 changes: 10 additions & 10 deletions internal/acctest/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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 {
Expand All @@ -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))

Expand All @@ -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))

Expand Down Expand Up @@ -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))

Expand All @@ -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 {
Expand Down Expand Up @@ -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))

Expand All @@ -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 {
Expand Down Expand Up @@ -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))

Expand Down Expand Up @@ -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 {
Expand Down
10 changes: 5 additions & 5 deletions internal/acctest/ec2_classic.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand All @@ -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.
Expand Down Expand Up @@ -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)

Expand All @@ -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{
Expand Down
7 changes: 4 additions & 3 deletions internal/conns/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
}
Expand Down
6 changes: 4 additions & 2 deletions internal/conns/conns.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package conns

import (
"fmt"
"errors"
"strings"

"github.com/aws/aws-sdk-go/aws"
Expand All @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
44 changes: 25 additions & 19 deletions internal/conns/envvar.go
Original file line number Diff line number Diff line change
@@ -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"
)

Expand All @@ -95,15 +101,15 @@ 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.
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
Expand Down
Loading
Loading