github.com/khulnasoft-lab/defsec@v1.0.5-0.20230827010352-5e9f46893d95/rules/cloud/policies/aws/ec2/restrict_all_in_default_sg_test.go (about) 1 package ec2 2 3 import ( 4 "testing" 5 6 "github.com/khulnasoft-lab/defsec/pkg/types" 7 8 "github.com/khulnasoft-lab/defsec/pkg/providers/aws/ec2" 9 10 "github.com/khulnasoft-lab/defsec/pkg/state" 11 12 "github.com/khulnasoft-lab/defsec/pkg/scan" 13 14 "github.com/stretchr/testify/assert" 15 ) 16 17 func TestCheckRestrictAllInDefaultSG(t *testing.T) { 18 tests := []struct { 19 name string 20 input ec2.EC2 21 expected bool 22 }{ 23 { 24 name: "default sg restricts all", 25 input: ec2.EC2{ 26 VPCs: []ec2.VPC{ 27 { 28 Metadata: types.NewTestMetadata(), 29 SecurityGroups: []ec2.SecurityGroup{ 30 { 31 Metadata: types.NewTestMetadata(), 32 IsDefault: types.Bool(true, types.NewTestMetadata()), 33 IngressRules: nil, 34 EgressRules: nil, 35 }, 36 }, 37 }, 38 }, 39 }, 40 expected: false, 41 }, 42 { 43 name: "default sg allows ingress", 44 input: ec2.EC2{ 45 VPCs: []ec2.VPC{ 46 { 47 Metadata: types.NewTestMetadata(), 48 SecurityGroups: []ec2.SecurityGroup{ 49 { 50 Metadata: types.NewTestMetadata(), 51 IsDefault: types.Bool(true, types.NewTestMetadata()), 52 IngressRules: []ec2.SecurityGroupRule{ 53 {}, 54 }, 55 EgressRules: nil, 56 }, 57 }, 58 }, 59 }, 60 }, 61 expected: true, 62 }, 63 { 64 name: "default sg allows egress", 65 input: ec2.EC2{ 66 VPCs: []ec2.VPC{ 67 { 68 Metadata: types.NewTestMetadata(), 69 SecurityGroups: []ec2.SecurityGroup{ 70 { 71 Metadata: types.NewTestMetadata(), 72 IsDefault: types.Bool(true, types.NewTestMetadata()), 73 IngressRules: nil, 74 EgressRules: []ec2.SecurityGroupRule{ 75 {}, 76 }, 77 }, 78 }, 79 }, 80 }, 81 }, 82 expected: true, 83 }, 84 } 85 for _, test := range tests { 86 t.Run(test.name, func(t *testing.T) { 87 var testState state.State 88 testState.AWS.EC2 = test.input 89 results := CheckRestrictAllInDefaultSG.Evaluate(&testState) 90 var found bool 91 for _, result := range results { 92 if result.Status() == scan.StatusFailed && result.Rule().LongID() == CheckRestrictAllInDefaultSG.Rule().LongID() { 93 found = true 94 } 95 } 96 if test.expected { 97 assert.True(t, found, "Rule should have been found") 98 } else { 99 assert.False(t, found, "Rule should not have been found") 100 } 101 }) 102 } 103 }