From 42bb5faa912c55bed95e4e35bc308eddb0eebde6 Mon Sep 17 00:00:00 2001 From: Dirk Avery Date: Wed, 22 Jul 2020 17:50:59 -0400 Subject: [PATCH] Improve static check for hardcoded partition in ARN --- awsproviderlint/passes/AWSAT005/AWSAT005.go | 13 +++++++++++-- .../passes/AWSAT005/testdata/src/a/main.go | 3 ++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/awsproviderlint/passes/AWSAT005/AWSAT005.go b/awsproviderlint/passes/AWSAT005/AWSAT005.go index f823c66b0ee..f3d3416d38f 100644 --- a/awsproviderlint/passes/AWSAT005/AWSAT005.go +++ b/awsproviderlint/passes/AWSAT005/AWSAT005.go @@ -5,8 +5,10 @@ package AWSAT005 import ( "go/ast" "go/token" + "regexp" "strings" + "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/bflad/tfproviderlint/passes/commentignore" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" @@ -38,6 +40,13 @@ func run(pass *analysis.Pass) (interface{}, error) { nodeFilter := []ast.Node{ (*ast.BasicLit)(nil), } + + var partitions []string + for _, p := range endpoints.DefaultPartitions() { + partitions = append(partitions, p.ID()) + } + + re := regexp.MustCompile(`arn:(` + strings.Join(partitions, "|") + `):`) inspect.Preorder(nodeFilter, func(n ast.Node) { x := n.(*ast.BasicLit) @@ -49,11 +58,11 @@ func run(pass *analysis.Pass) (interface{}, error) { return } - if !strings.Contains(x.Value, `arn:aws:`) { + if !re.MatchString(x.Value) { return } - pass.Reportf(x.ValuePos, "%s: avoid hardcoding an AWS partition in an ARN, instead use the aws_partition data source", analyzerName) + pass.Reportf(x.ValuePos, "%s: avoid hardcoded ARN AWS partitions, use aws_partition data source", analyzerName) }) return nil, nil } diff --git a/awsproviderlint/passes/AWSAT005/testdata/src/a/main.go b/awsproviderlint/passes/AWSAT005/testdata/src/a/main.go index ab166852404..2069f325eaf 100644 --- a/awsproviderlint/passes/AWSAT005/testdata/src/a/main.go +++ b/awsproviderlint/passes/AWSAT005/testdata/src/a/main.go @@ -24,6 +24,7 @@ resource "aws_iam_role_policy_attachment" "test-AmazonEKSClusterPolicy" { /* Failing cases */ - fmt.Sprintf(`policy_arn = "arn:aws:iam::aws:%v"`, "policy/AmazonEKSClusterPolicy") // want "avoid hardcoding an AWS partition in an ARN" + fmt.Sprintf(`policy_arn = "arn:aws:iam::aws:%v"`, "policy/AmazonEKSClusterPolicy") // want "avoid hardcoded ARN AWS partitions" + fmt.Sprintf(`policy_arn = "arn:aws-us-gov:iam::aws:%v"`, "policy/AmazonEKSClusterPolicy") // want "avoid hardcoded ARN AWS partitions" }