github.com/khulnasoft-lab/defsec@v1.0.5-0.20230827010352-5e9f46893d95/rules/cloud/policies/aws/sam/no_function_policy_wildcards_test.go (about) 1 package sam 2 3 import ( 4 "testing" 5 6 "github.com/khulnasoft-lab/defsec/pkg/types" 7 8 "github.com/khulnasoft-lab/defsec/pkg/state" 9 10 "github.com/khulnasoft-lab/defsec/pkg/providers/aws/iam" 11 "github.com/khulnasoft-lab/defsec/pkg/providers/aws/sam" 12 "github.com/khulnasoft-lab/defsec/pkg/scan" 13 14 "github.com/liamg/iamgo" 15 16 "github.com/stretchr/testify/assert" 17 ) 18 19 func TestCheckNoFunctionPolicyWildcards(t *testing.T) { 20 tests := []struct { 21 name string 22 input sam.SAM 23 expected bool 24 }{ 25 { 26 name: "Wildcard action in function policy", 27 input: sam.SAM{ 28 Functions: []sam.Function{ 29 { 30 Metadata: types.NewTestMetadata(), 31 Policies: func() []iam.Policy { 32 33 sb := iamgo.NewStatementBuilder() 34 sb.WithSid("new policy") 35 sb.WithEffect("Allow") 36 sb.WithActions([]string{ 37 "s3:*", 38 }) 39 sb.WithResources([]string{"arn:aws:s3:::my-bucket/*"}) 40 sb.WithAWSPrincipals([]string{"*"}) 41 42 builder := iamgo.NewPolicyBuilder() 43 builder.WithVersion("2012-10-17") 44 builder.WithStatement(sb.Build()) 45 46 return []iam.Policy{ 47 { 48 Document: iam.Document{ 49 Metadata: types.NewTestMetadata(), 50 Parsed: builder.Build(), 51 }, 52 }, 53 } 54 }(), 55 }, 56 }, 57 }, 58 expected: true, 59 }, 60 { 61 name: "Specific action in function policy", 62 input: sam.SAM{ 63 Functions: []sam.Function{ 64 { 65 Metadata: types.NewTestMetadata(), 66 Policies: func() []iam.Policy { 67 68 sb := iamgo.NewStatementBuilder() 69 sb.WithSid("new policy") 70 sb.WithEffect("Allow") 71 sb.WithActions([]string{ 72 "s3:GetObject", 73 }) 74 sb.WithResources([]string{"arn:aws:s3:::my-bucket/*"}) 75 sb.WithAWSPrincipals([]string{"proper-value"}) 76 77 builder := iamgo.NewPolicyBuilder() 78 builder.WithVersion("2012-10-17") 79 builder.WithStatement(sb.Build()) 80 81 return []iam.Policy{ 82 { 83 Document: iam.Document{ 84 Metadata: types.NewTestMetadata(), 85 Parsed: builder.Build(), 86 }, 87 }, 88 } 89 }(), 90 }, 91 }, 92 }, 93 expected: false, 94 }, 95 } 96 for _, test := range tests { 97 t.Run(test.name, func(t *testing.T) { 98 var testState state.State 99 testState.AWS.SAM = test.input 100 results := CheckNoFunctionPolicyWildcards.Evaluate(&testState) 101 var found bool 102 for _, result := range results { 103 if result.Status() == scan.StatusFailed && result.Rule().LongID() == CheckNoFunctionPolicyWildcards.Rule().LongID() { 104 found = true 105 } 106 } 107 if test.expected { 108 assert.True(t, found, "Rule should have been found") 109 } else { 110 assert.False(t, found, "Rule should not have been found") 111 } 112 }) 113 } 114 }