github.com/khulnasoft-lab/defsec@v1.0.5-0.20230827010352-5e9f46893d95/rules/cloud/policies/google/sql/no_public_access_test.go (about) 1 package sql 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/sql" 11 "github.com/khulnasoft-lab/defsec/pkg/scan" 12 13 "github.com/stretchr/testify/assert" 14 ) 15 16 func TestCheckNoPublicAccess(t *testing.T) { 17 tests := []struct { 18 name string 19 input sql.SQL 20 expected bool 21 }{ 22 { 23 name: "Instance settings set with IPv4 enabled", 24 input: sql.SQL{ 25 Instances: []sql.DatabaseInstance{ 26 { 27 Metadata: defsecTypes.NewTestMetadata(), 28 Settings: sql.Settings{ 29 Metadata: defsecTypes.NewTestMetadata(), 30 IPConfiguration: sql.IPConfiguration{ 31 Metadata: defsecTypes.NewTestMetadata(), 32 EnableIPv4: defsecTypes.Bool(true, defsecTypes.NewTestMetadata()), 33 }, 34 }, 35 }, 36 }, 37 }, 38 expected: true, 39 }, 40 { 41 name: "Instance settings set with IPv4 disabled but public CIDR in authorized networks", 42 input: sql.SQL{ 43 Instances: []sql.DatabaseInstance{ 44 { 45 Metadata: defsecTypes.NewTestMetadata(), 46 Settings: sql.Settings{ 47 Metadata: defsecTypes.NewTestMetadata(), 48 IPConfiguration: sql.IPConfiguration{ 49 Metadata: defsecTypes.NewTestMetadata(), 50 EnableIPv4: defsecTypes.Bool(false, defsecTypes.NewTestMetadata()), 51 AuthorizedNetworks: []struct { 52 Name defsecTypes.StringValue 53 CIDR defsecTypes.StringValue 54 }{ 55 { 56 CIDR: defsecTypes.String("0.0.0.0/0", defsecTypes.NewTestMetadata()), 57 }, 58 }, 59 }, 60 }, 61 }, 62 }, 63 }, 64 expected: true, 65 }, 66 { 67 name: "Instance settings set with IPv4 disabled and private CIDR", 68 input: sql.SQL{ 69 Instances: []sql.DatabaseInstance{ 70 { 71 Metadata: defsecTypes.NewTestMetadata(), 72 Settings: sql.Settings{ 73 Metadata: defsecTypes.NewTestMetadata(), 74 IPConfiguration: sql.IPConfiguration{ 75 Metadata: defsecTypes.NewTestMetadata(), 76 EnableIPv4: defsecTypes.Bool(false, defsecTypes.NewTestMetadata()), 77 AuthorizedNetworks: []struct { 78 Name defsecTypes.StringValue 79 CIDR defsecTypes.StringValue 80 }{ 81 { 82 CIDR: defsecTypes.String("10.0.0.1/24", defsecTypes.NewTestMetadata()), 83 }, 84 }, 85 }, 86 }, 87 }, 88 }, 89 }, 90 expected: false, 91 }, 92 } 93 for _, test := range tests { 94 t.Run(test.name, func(t *testing.T) { 95 var testState state.State 96 testState.Google.SQL = test.input 97 results := CheckNoPublicAccess.Evaluate(&testState) 98 var found bool 99 for _, result := range results { 100 if result.Status() == scan.StatusFailed && result.Rule().LongID() == CheckNoPublicAccess.Rule().LongID() { 101 found = true 102 } 103 } 104 if test.expected { 105 assert.True(t, found, "Rule should have been found") 106 } else { 107 assert.False(t, found, "Rule should not have been found") 108 } 109 }) 110 } 111 }