github.com/khulnasoft-lab/defsec@v1.0.5-0.20230827010352-5e9f46893d95/rules/cloud/policies/aws/ec2/no_public_egress_sgr_test.go (about)

     1  package ec2
     2  
     3  import (
     4  	"testing"
     5  
     6  	defsecTypes "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 TestCheckNoPublicEgressSgr(t *testing.T) {
    18  	tests := []struct {
    19  		name     string
    20  		input    ec2.EC2
    21  		expected bool
    22  	}{
    23  		{
    24  			name: "AWS VPC security group rule with wildcard address",
    25  			input: ec2.EC2{
    26  				SecurityGroups: []ec2.SecurityGroup{
    27  					{
    28  						Metadata: defsecTypes.NewTestMetadata(),
    29  						EgressRules: []ec2.SecurityGroupRule{
    30  							{
    31  								Metadata: defsecTypes.NewTestMetadata(),
    32  								CIDRs: []defsecTypes.StringValue{
    33  									defsecTypes.String("0.0.0.0/0", defsecTypes.NewTestMetadata()),
    34  								},
    35  							},
    36  						},
    37  					},
    38  				},
    39  			},
    40  			expected: true,
    41  		},
    42  		{
    43  			name: "AWS VPC security group rule with private address",
    44  			input: ec2.EC2{
    45  				SecurityGroups: []ec2.SecurityGroup{
    46  					{
    47  						Metadata: defsecTypes.NewTestMetadata(),
    48  						EgressRules: []ec2.SecurityGroupRule{
    49  							{
    50  								Metadata: defsecTypes.NewTestMetadata(),
    51  								CIDRs: []defsecTypes.StringValue{
    52  									defsecTypes.String("10.0.0.0/16", defsecTypes.NewTestMetadata()),
    53  								},
    54  							},
    55  						},
    56  					},
    57  				},
    58  			},
    59  			expected: false,
    60  		},
    61  	}
    62  	for _, test := range tests {
    63  		t.Run(test.name, func(t *testing.T) {
    64  			var testState state.State
    65  			testState.AWS.EC2 = test.input
    66  			results := CheckNoPublicEgressSgr.Evaluate(&testState)
    67  			var found bool
    68  			for _, result := range results {
    69  				if result.Status() == scan.StatusFailed && result.Rule().LongID() == CheckNoPublicEgressSgr.Rule().LongID() {
    70  					found = true
    71  				}
    72  			}
    73  			if test.expected {
    74  				assert.True(t, found, "Rule should have been found")
    75  			} else {
    76  				assert.False(t, found, "Rule should not have been found")
    77  			}
    78  		})
    79  	}
    80  }