github.com/khulnasoft-lab/defsec@v1.0.5-0.20230827010352-5e9f46893d95/internal/adapters/cloud/aws/iam/policy_test.go (about) 1 package iam 2 3 import ( 4 "testing" 5 6 "github.com/khulnasoft-lab/defsec/internal/adapters/cloud/aws" 7 8 iamapi "github.com/aws/aws-sdk-go-v2/service/iam" 9 10 "github.com/khulnasoft-lab/defsec/internal/adapters/cloud/aws/test" 11 "github.com/khulnasoft-lab/defsec/pkg/providers/aws/iam" 12 "github.com/khulnasoft-lab/defsec/pkg/state" 13 "github.com/stretchr/testify/assert" 14 "github.com/stretchr/testify/require" 15 ) 16 17 type policyDetails struct { 18 policyName string 19 policyDocument string 20 } 21 22 func Test_IAMPolicies(t *testing.T) { 23 tests := []struct { 24 name string 25 details policyDetails 26 }{ 27 { 28 name: "basic policy", 29 details: policyDetails{ 30 policyName: "test-policy", 31 policyDocument: `{ 32 "Version": "2012-10-17", 33 "Statement": [ 34 { 35 "Action": [ 36 "iam:GetContextKeysForCustomPolicy", 37 "iam:GetContextKeysForPrincipalPolicy", 38 "iam:SimulateCustomPolicy", 39 "iam:SimulatePrincipalPolicy" 40 ], 41 "Effect": "Allow", 42 "Resource": "*" 43 } 44 ] 45 }`, 46 }, 47 }, 48 } 49 50 ra, stack, err := test.CreateLocalstackAdapter(t) 51 defer func() { _ = stack.Stop() }() 52 require.NoError(t, err) 53 54 for _, tt := range tests { 55 t.Run(tt.name, func(t *testing.T) { 56 arn := bootstrapIAMPolicy(t, ra, tt.details) 57 testState := &state.State{} 58 iamAdapter := &adapter{} 59 err := iamAdapter.Adapt(ra, testState) 60 require.NoError(t, err) 61 62 var found int 63 var match iam.Policy 64 for _, policy := range testState.AWS.IAM.Policies { 65 if policy.Name.EqualTo(tt.details.policyName) { 66 found++ 67 match = policy 68 } 69 } 70 require.Equal(t, 1, found) 71 assert.Equal(t, arn, match.Metadata.Range().GetLocalFilename()) 72 }) 73 } 74 } 75 76 func bootstrapIAMPolicy(t *testing.T, ra *aws.RootAdapter, details policyDetails) string { 77 api := iamapi.NewFromConfig(ra.SessionConfig()) 78 output, err := api.CreatePolicy(ra.Context(), &iamapi.CreatePolicyInput{ 79 PolicyDocument: &details.policyDocument, 80 PolicyName: &details.policyName, 81 }) 82 require.NoError(t, err) 83 return *output.Policy.Arn 84 }