github.com/khulnasoft-lab/defsec@v1.0.5-0.20230827010352-5e9f46893d95/rules/cloud/policies/google/compute/vm_disk_encryption_customer_key_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 TestCheckVmDiskEncryptionCustomerKey(t *testing.T) {
    17  	tests := []struct {
    18  		name     string
    19  		input    compute.Compute
    20  		expected bool
    21  	}{
    22  		{
    23  			name: "Instance disk missing encryption key link",
    24  			input: compute.Compute{
    25  				Instances: []compute.Instance{
    26  					{
    27  						Metadata: defsecTypes.NewTestMetadata(),
    28  						BootDisks: []compute.Disk{
    29  							{
    30  								Metadata: defsecTypes.NewTestMetadata(),
    31  								Encryption: compute.DiskEncryption{
    32  									Metadata:   defsecTypes.NewTestMetadata(),
    33  									KMSKeyLink: defsecTypes.String("", defsecTypes.NewTestMetadata()),
    34  								},
    35  							},
    36  						},
    37  					},
    38  				},
    39  			},
    40  			expected: true,
    41  		},
    42  		{
    43  			name: "Instance disk encryption key link provided",
    44  			input: compute.Compute{
    45  				Instances: []compute.Instance{
    46  					{
    47  						Metadata: defsecTypes.NewTestMetadata(),
    48  						AttachedDisks: []compute.Disk{
    49  							{
    50  								Metadata: defsecTypes.NewTestMetadata(),
    51  								Encryption: compute.DiskEncryption{
    52  									Metadata:   defsecTypes.NewTestMetadata(),
    53  									KMSKeyLink: defsecTypes.String("kms-key-link", defsecTypes.NewTestMetadata()),
    54  								},
    55  							},
    56  						},
    57  					},
    58  				},
    59  			},
    60  			expected: false,
    61  		},
    62  	}
    63  	for _, test := range tests {
    64  		t.Run(test.name, func(t *testing.T) {
    65  			var testState state.State
    66  			testState.Google.Compute = test.input
    67  			results := CheckVmDiskEncryptionCustomerKey.Evaluate(&testState)
    68  			var found bool
    69  			for _, result := range results {
    70  				if result.Status() == scan.StatusFailed && result.Rule().LongID() == CheckVmDiskEncryptionCustomerKey.Rule().LongID() {
    71  					found = true
    72  				}
    73  			}
    74  			if test.expected {
    75  				assert.True(t, found, "Rule should have been found")
    76  			} else {
    77  				assert.False(t, found, "Rule should not have been found")
    78  			}
    79  		})
    80  	}
    81  }