github.com/khulnasoft-lab/defsec@v1.0.5-0.20230827010352-5e9f46893d95/rules/cloud/policies/digitalocean/compute/no_public_egress_test.go (about)

     1  package compute
     2  
     3  import (
     4  	"testing"
     5  
     6  	defsecTypes "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/digitalocean/compute"
    11  	"github.com/khulnasoft-lab/defsec/pkg/scan"
    12  
    13  	"github.com/stretchr/testify/assert"
    14  )
    15  
    16  func TestCheckNoPublicEgress(t *testing.T) {
    17  	tests := []struct {
    18  		name     string
    19  		input    compute.Compute
    20  		expected bool
    21  	}{
    22  		{
    23  			name: "Firewall outbound rule with multiple public destination addresses",
    24  			input: compute.Compute{
    25  				Firewalls: []compute.Firewall{
    26  					{
    27  						Metadata: defsecTypes.NewTestMetadata(),
    28  						OutboundRules: []compute.OutboundFirewallRule{
    29  							{
    30  								Metadata: defsecTypes.NewTestMetadata(),
    31  								DestinationAddresses: []defsecTypes.StringValue{
    32  									defsecTypes.String("0.0.0.0/0", defsecTypes.NewTestMetadata()),
    33  									defsecTypes.String("::/0", defsecTypes.NewTestMetadata()),
    34  								},
    35  							},
    36  						},
    37  					},
    38  				},
    39  			},
    40  			expected: true,
    41  		},
    42  		{
    43  			name: "Firewall outbound rule with a private destination address",
    44  			input: compute.Compute{
    45  				Firewalls: []compute.Firewall{
    46  					{
    47  						Metadata: defsecTypes.NewTestMetadata(),
    48  						OutboundRules: []compute.OutboundFirewallRule{
    49  							{
    50  								Metadata: defsecTypes.NewTestMetadata(),
    51  								DestinationAddresses: []defsecTypes.StringValue{
    52  									defsecTypes.String("192.168.1.0/24", 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.DigitalOcean.Compute = test.input
    66  			results := CheckNoPublicEgress.Evaluate(&testState)
    67  			var found bool
    68  			for _, result := range results {
    69  				if result.Status() == scan.StatusFailed && result.Rule().LongID() == CheckNoPublicEgress.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  }