github.com/khulnasoft-lab/defsec@v1.0.5-0.20230827010352-5e9f46893d95/rules/cloud/policies/digitalocean/compute/use_ssh_keys_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 TestCheckUseSshKeys(t *testing.T) {
    17  	tests := []struct {
    18  		name     string
    19  		input    compute.Compute
    20  		expected bool
    21  	}{
    22  		{
    23  			name: "Droplet missing SSH keys",
    24  			input: compute.Compute{
    25  				Droplets: []compute.Droplet{
    26  					{
    27  						Metadata: defsecTypes.NewTestMetadata(),
    28  						SSHKeys:  []defsecTypes.StringValue{},
    29  					},
    30  				},
    31  			},
    32  			expected: true,
    33  		},
    34  		{
    35  			name: "Droplet with an SSH key provided",
    36  			input: compute.Compute{
    37  				Droplets: []compute.Droplet{
    38  					{
    39  						Metadata: defsecTypes.NewTestMetadata(),
    40  						SSHKeys: []defsecTypes.StringValue{
    41  							defsecTypes.String("my-ssh-key", defsecTypes.NewTestMetadata()),
    42  						},
    43  					},
    44  				},
    45  			},
    46  			expected: false,
    47  		},
    48  	}
    49  	for _, test := range tests {
    50  		t.Run(test.name, func(t *testing.T) {
    51  			var testState state.State
    52  			testState.DigitalOcean.Compute = test.input
    53  			results := CheckUseSshKeys.Evaluate(&testState)
    54  			var found bool
    55  			for _, result := range results {
    56  				if result.Status() == scan.StatusFailed && result.Rule().LongID() == CheckUseSshKeys.Rule().LongID() {
    57  					found = true
    58  				}
    59  			}
    60  			if test.expected {
    61  				assert.True(t, found, "Rule should have been found")
    62  			} else {
    63  				assert.False(t, found, "Rule should not have been found")
    64  			}
    65  		})
    66  	}
    67  }