github.com/khulnasoft-lab/defsec@v1.0.5-0.20230827010352-5e9f46893d95/rules/cloud/policies/google/compute/no_public_ip_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/google/compute"
    11  	"github.com/khulnasoft-lab/defsec/pkg/scan"
    12  
    13  	"github.com/stretchr/testify/assert"
    14  )
    15  
    16  func TestCheckInstancesDoNotHavePublicIPs(t *testing.T) {
    17  	tests := []struct {
    18  		name     string
    19  		input    compute.Compute
    20  		expected bool
    21  	}{
    22  		{
    23  			name: "Network interface with public IP",
    24  			input: compute.Compute{
    25  				Instances: []compute.Instance{
    26  					{
    27  						Metadata: defsecTypes.NewTestMetadata(),
    28  						NetworkInterfaces: []compute.NetworkInterface{
    29  							{
    30  								Metadata:    defsecTypes.NewTestMetadata(),
    31  								HasPublicIP: defsecTypes.Bool(true, defsecTypes.NewTestMetadata()),
    32  							},
    33  						},
    34  					},
    35  				},
    36  			},
    37  			expected: true,
    38  		},
    39  		{
    40  			name: "Network interface without public IP",
    41  			input: compute.Compute{
    42  				Instances: []compute.Instance{
    43  					{
    44  						Metadata: defsecTypes.NewTestMetadata(),
    45  						NetworkInterfaces: []compute.NetworkInterface{
    46  							{
    47  								Metadata:    defsecTypes.NewTestMetadata(),
    48  								HasPublicIP: defsecTypes.Bool(false, defsecTypes.NewTestMetadata()),
    49  							},
    50  						},
    51  					},
    52  				}},
    53  			expected: false,
    54  		},
    55  	}
    56  	for _, test := range tests {
    57  		t.Run(test.name, func(t *testing.T) {
    58  			var testState state.State
    59  			testState.Google.Compute = test.input
    60  			results := CheckInstancesDoNotHavePublicIPs.Evaluate(&testState)
    61  			var found bool
    62  			for _, result := range results {
    63  				if result.Status() == scan.StatusFailed && result.Rule().LongID() == CheckInstancesDoNotHavePublicIPs.Rule().LongID() {
    64  					found = true
    65  				}
    66  			}
    67  			if test.expected {
    68  				assert.True(t, found, "Rule should have been found")
    69  			} else {
    70  				assert.False(t, found, "Rule should not have been found")
    71  			}
    72  		})
    73  	}
    74  }