feat: google compute global forwarding rule

main
Almog Ben-David 2022-03-30 21:57:33 +03:00
parent 28dffc6fe4
commit e9f906e8fc
No known key found for this signature in database
GPG Key ID: 21600149F8AFCF03
15 changed files with 392 additions and 23 deletions

View File

@ -379,6 +379,7 @@ func TestTerraformStateReader_Google_Resources(t *testing.T) {
{name: "compute node group", dirName: "google_compute_node_group", wantErr: false},
{name: "compute forwarding rule", dirName: "google_compute_forwarding_rule", wantErr: false},
{name: "compute instance group manager", dirName: "google_compute_instance_group_manager", wantErr: false},
{name: "compute global forwarding rule", dirName: "google_compute_global_forwarding_rule", wantErr: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {

View File

@ -0,0 +1,19 @@
[
{
"Id": "projects/driftctl-qa-1/global/forwardingRules/global-rule",
"Type": "google_compute_global_forwarding_rule",
"Attrs": {
"description": "",
"id": "projects/driftctl-qa-1/global/forwardingRules/global-rule",
"ip_address": "34.120.169.13",
"ip_protocol": "TCP",
"ip_version": "",
"load_balancing_scheme": "EXTERNAL",
"name": "global-rule",
"port_range": "80",
"project": "driftctl-qa-1",
"self_link": "https://www.googleapis.com/compute/v1/projects/driftctl-qa-1/global/forwardingRules/global-rule",
"target": "projects/driftctl-qa-1/global/targetHttpProxies/target-proxy"
}
}
]

View File

@ -0,0 +1,46 @@
{
"version": 4,
"terraform_version": "0.14.6",
"serial": 35,
"lineage": "49d84423-0f98-9ac4-ffe0-84ef3126d36f",
"outputs": {},
"resources": [
{
"mode": "managed",
"type": "google_compute_global_forwarding_rule",
"name": "default",
"provider": "provider[\"registry.terraform.io/hashicorp/google\"]",
"instances": [
{
"schema_version": 0,
"attributes": {
"description": "",
"id": "projects/driftctl-qa-1/global/forwardingRules/global-rule",
"ip_address": "34.120.169.13",
"ip_protocol": "TCP",
"ip_version": "",
"label_fingerprint": "42WmSpB8rSM=",
"labels": null,
"load_balancing_scheme": "EXTERNAL",
"metadata_filters": [],
"name": "global-rule",
"network": "",
"port_range": "80",
"project": "driftctl-qa-1",
"self_link": "https://www.googleapis.com/compute/v1/projects/driftctl-qa-1/global/forwardingRules/global-rule",
"target": "projects/driftctl-qa-1/global/targetHttpProxies/target-proxy",
"timeouts": null
},
"sensitive_attributes": [],
"private": "eyJlMmJmYjczMC1lY2FhLTExZTYtOGY4OC0zNDM2M2JjN2M0YzAiOnsiY3JlYXRlIjoxMjAwMDAwMDAwMDAwLCJkZWxldGUiOjEyMDAwMDAwMDAwMDAsInVwZGF0ZSI6MTIwMDAwMDAwMDAwMH19",
"dependencies": [
"google_compute_backend_service.default",
"google_compute_http_health_check.default",
"google_compute_target_http_proxy.default",
"google_compute_url_map.default"
]
}
]
}
]
}

View File

@ -0,0 +1,46 @@
package google
import (
remoteerror "github.com/snyk/driftctl/pkg/remote/error"
"github.com/snyk/driftctl/pkg/remote/google/repository"
"github.com/snyk/driftctl/pkg/resource"
"github.com/snyk/driftctl/pkg/resource/google"
)
type GoogleComputeGlobalForwardingRuleEnumerator struct {
repository repository.AssetRepository
factory resource.ResourceFactory
}
func NewGoogleComputeGlobalForwardingRuleEnumerator(repo repository.AssetRepository, factory resource.ResourceFactory) *GoogleComputeGlobalForwardingRuleEnumerator {
return &GoogleComputeGlobalForwardingRuleEnumerator{
repository: repo,
factory: factory,
}
}
func (e *GoogleComputeGlobalForwardingRuleEnumerator) SupportedType() resource.ResourceType {
return google.GoogleComputeGlobalForwardingRuleResourceType
}
func (e *GoogleComputeGlobalForwardingRuleEnumerator) Enumerate() ([]*resource.Resource, error) {
nodeGroups, err := e.repository.SearchAllGlobalForwardingRules() //Change the name
if err != nil {
return nil, remoteerror.NewResourceListingError(err, string(e.SupportedType()))
}
results := make([]*resource.Resource, 0, len(nodeGroups))
for _, res := range nodeGroups {
results = append(
results,
e.factory.CreateAbstractResource(
string(e.SupportedType()),
trimResourceName(res.GetName()),
map[string]interface{}{},
),
)
}
return results, err
}

View File

@ -101,6 +101,7 @@ func Init(version string, alerter *alerter.Alerter,
remoteLibrary.AddEnumerator(NewGoogleComputeNodeGroupEnumerator(assetRepository, factory))
remoteLibrary.AddEnumerator(NewGoogleComputeForwardingRuleEnumerator(assetRepository, factory))
remoteLibrary.AddEnumerator(NewGoogleComputeInstanceGroupManagerEnumerator(assetRepository, factory))
remoteLibrary.AddEnumerator(NewGoogleComputeGlobalForwardingRuleEnumerator(assetRepository, factory))
err = resourceSchemaRepository.Init(terraform.GOOGLE, provider.Version(), provider.Schema())
if err != nil {

View File

@ -13,29 +13,30 @@ import (
// https://cloud.google.com/asset-inventory/docs/supported-asset-types#supported_resource_types
const (
storageBucketAssetType = "storage.googleapis.com/Bucket"
computeFirewallAssetType = "compute.googleapis.com/Firewall"
computeRouterAssetType = "compute.googleapis.com/Router"
computeInstanceAssetType = "compute.googleapis.com/Instance"
computeNetworkAssetType = "compute.googleapis.com/Network"
computeSubnetworkAssetType = "compute.googleapis.com/Subnetwork"
computeDiskAssetType = "compute.googleapis.com/Disk"
computeImageAssetType = "compute.googleapis.com/Image"
dnsManagedZoneAssetType = "dns.googleapis.com/ManagedZone"
computeInstanceGroupAssetType = "compute.googleapis.com/InstanceGroup"
bigqueryDatasetAssetType = "bigquery.googleapis.com/Dataset"
bigqueryTableAssetType = "bigquery.googleapis.com/Table"
computeAddressAssetType = "compute.googleapis.com/Address"
computeGlobalAddressAssetType = "compute.googleapis.com/GlobalAddress"
cloudFunctionsFunction = "cloudfunctions.googleapis.com/CloudFunction"
bigtableInstanceAssetType = "bigtableadmin.googleapis.com/Instance"
bigtableTableAssetType = "bigtableadmin.googleapis.com/Table"
sqlDatabaseInstanceAssetType = "sqladmin.googleapis.com/Instance"
healthCheckAssetType = "compute.googleapis.com/HealthCheck"
cloudRunServiceAssetType = "run.googleapis.com/Service"
nodeGroupAssetType = "compute.googleapis.com/NodeGroup"
computeForwardingRuleAssetType = "compute.googleapis.com/ForwardingRule"
instanceGroupManagerAssetType = "compute.googleapis.com/InstanceGroupManager"
storageBucketAssetType = "storage.googleapis.com/Bucket"
computeFirewallAssetType = "compute.googleapis.com/Firewall"
computeRouterAssetType = "compute.googleapis.com/Router"
computeInstanceAssetType = "compute.googleapis.com/Instance"
computeNetworkAssetType = "compute.googleapis.com/Network"
computeSubnetworkAssetType = "compute.googleapis.com/Subnetwork"
computeDiskAssetType = "compute.googleapis.com/Disk"
computeImageAssetType = "compute.googleapis.com/Image"
dnsManagedZoneAssetType = "dns.googleapis.com/ManagedZone"
computeInstanceGroupAssetType = "compute.googleapis.com/InstanceGroup"
bigqueryDatasetAssetType = "bigquery.googleapis.com/Dataset"
bigqueryTableAssetType = "bigquery.googleapis.com/Table"
computeAddressAssetType = "compute.googleapis.com/Address"
computeGlobalAddressAssetType = "compute.googleapis.com/GlobalAddress"
cloudFunctionsFunction = "cloudfunctions.googleapis.com/CloudFunction"
bigtableInstanceAssetType = "bigtableadmin.googleapis.com/Instance"
bigtableTableAssetType = "bigtableadmin.googleapis.com/Table"
sqlDatabaseInstanceAssetType = "sqladmin.googleapis.com/Instance"
healthCheckAssetType = "compute.googleapis.com/HealthCheck"
cloudRunServiceAssetType = "run.googleapis.com/Service"
nodeGroupAssetType = "compute.googleapis.com/NodeGroup"
computeForwardingRuleAssetType = "compute.googleapis.com/ForwardingRule"
instanceGroupManagerAssetType = "compute.googleapis.com/InstanceGroupManager"
computeGlobalForwardingRuleAssetType = "compute.googleapis.com/GlobalForwardingRule"
)
type AssetRepository interface {
@ -62,6 +63,7 @@ type AssetRepository interface {
SearchAllNodeGroups() ([]*assetpb.Asset, error)
SearchAllForwardingRules() ([]*assetpb.Asset, error)
SearchAllInstanceGroupManagers() ([]*assetpb.Asset, error)
SearchAllGlobalForwardingRules() ([]*assetpb.Asset, error)
}
type assetRepository struct {
@ -91,6 +93,7 @@ func (s assetRepository) listAllResources(ty string) ([]*assetpb.Asset, error) {
nodeGroupAssetType,
computeForwardingRuleAssetType,
instanceGroupManagerAssetType,
computeGlobalForwardingRuleAssetType,
},
}
var results []*assetpb.Asset
@ -273,3 +276,7 @@ func (s assetRepository) SearchAllForwardingRules() ([]*assetpb.Asset, error) {
func (s assetRepository) SearchAllInstanceGroupManagers() ([]*assetpb.Asset, error) {
return s.listAllResources(instanceGroupManagerAssetType)
}
func (s assetRepository) SearchAllGlobalForwardingRules() ([]*assetpb.Asset, error) {
return s.listAllResources(computeGlobalForwardingRuleAssetType)
}

View File

@ -449,6 +449,29 @@ func (_m *MockAssetRepository) SearchAllNodeGroups() ([]*asset.Asset, error) {
return r0, r1
}
// SearchAllGlobalForwardingRules provides a mock function with given fields:
func (_m *MockAssetRepository) SearchAllGlobalForwardingRules() ([]*asset.ResourceSearchResult, error) {
ret := _m.Called()
var r0 []*asset.ResourceSearchResult
if rf, ok := ret.Get(0).(func() []*asset.ResourceSearchResult); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]*asset.ResourceSearchResult)
}
}
var r1 error
if rf, ok := ret.Get(1).(func() error); ok {
r1 = rf()
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// SearchAllRouters provides a mock function with given fields:
func (_m *MockAssetRepository) SearchAllRouters() ([]*asset.ResourceSearchResult, error) {
ret := _m.Called()

View File

@ -1652,3 +1652,112 @@ func TestGoogleComputeInstanceGroupManager(t *testing.T) {
})
}
}
func TestGoogleComputeGlobalForwardingRule(t *testing.T) {
cases := []struct {
test string
assertExpected func(t *testing.T, got []*resource.Resource)
response []*assetpb.Asset
responseErr error
setupAlerterMock func(alerter *mocks.AlerterInterface)
wantErr error
}{
{
test: "no compute global forwarding rules",
response: []*assetpb.Asset{},
assertExpected: func(t *testing.T, got []*resource.Resource) {
assert.Len(t, got, 0)
},
},
{
test: "multiple compute global forwarding rules",
assertExpected: func(t *testing.T, got []*resource.Resource) {
assert.Len(t, got, 2)
assert.Equal(t, "//projects/driftctl-qa-1/global/forwardingRules/global-rule-foo", got[0].ResourceId())
assert.Equal(t, "google_compute_global_forwarding_rule", got[0].ResourceType())
assert.Equal(t, "//projects/driftctl-qa-1/global/forwardingRules/global-rule-bar", got[1].ResourceId())
assert.Equal(t, "google_compute_global_forwarding_rule", got[1].ResourceType())
},
response: []*assetpb.Asset{
{
AssetType: "compute.googleapis.com/GlobalForwardingRule",
Name: "//projects/driftctl-qa-1/global/forwardingRules/global-rule-foo",
},
{
AssetType: "compute.googleapis.com/GlobalForwardingRule",
Name: "//projects/driftctl-qa-1/global/forwardingRules/global-rule-bar",
},
},
},
{
test: "cannot list compute global forwarding rules",
assertExpected: func(t *testing.T, got []*resource.Resource) {
assert.Len(t, got, 0)
},
responseErr: status.Error(codes.PermissionDenied, "The caller does not have permission"),
setupAlerterMock: func(alerter *mocks.AlerterInterface) {
alerter.On(
"SendAlert",
"google_compute_global_forwarding_rule",
alerts.NewRemoteAccessDeniedAlert(
common.RemoteGoogleTerraform,
remoteerr.NewResourceListingError(
status.Error(codes.PermissionDenied, "The caller does not have permission"),
"google_compute_global_forwarding_rule",
),
alerts.EnumerationPhase,
),
).Once()
},
},
}
providerVersion := "3.78.0"
schemaRepository := testresource.InitFakeSchemaRepository(terraform.GOOGLE, providerVersion)
googleresource.InitResourcesMetadata(schemaRepository)
factory := terraform.NewTerraformResourceFactory(schemaRepository)
for _, c := range cases {
t.Run(c.test, func(tt *testing.T) {
scanOptions := ScannerOptions{}
providerLibrary := terraform.NewProviderLibrary()
remoteLibrary := common.NewRemoteLibrary()
// Initialize mocks
alerter := &mocks.AlerterInterface{}
if c.setupAlerterMock != nil {
c.setupAlerterMock(alerter)
}
assetClient, err := testgoogle.NewFakeAssertServerWithList(c.response, c.responseErr)
if err != nil {
tt.Fatal(err)
}
realProvider, err := terraform2.InitTestGoogleProvider(providerLibrary, providerVersion)
if err != nil {
tt.Fatal(err)
}
repo := repository.NewAssetRepository(assetClient, realProvider.GetConfig(), cache.New(0))
remoteLibrary.AddEnumerator(google.NewGoogleComputeGlobalForwardingRuleEnumerator(repo, factory))
testFilter := &filter.MockFilter{}
testFilter.On("IsTypeIgnored", mock.Anything).Return(false)
s := NewScanner(remoteLibrary, alerter, scanOptions, testFilter)
got, err := s.Resources()
assert.Equal(tt, err, c.wantErr)
if err != nil {
return
}
alerter.AssertExpectations(tt)
testFilter.AssertExpectations(tt)
if c.assertExpected != nil {
c.assertExpected(t, got)
}
})
}
}

View File

@ -0,0 +1,3 @@
package google
const GoogleComputeGlobalForwardingRuleResourceType = "google_compute_global_forwarding_rule"

View File

@ -0,0 +1,30 @@
package google_test
import (
"testing"
"github.com/snyk/driftctl/test"
"github.com/snyk/driftctl/test/acceptance"
)
func TestAcc_Google_ComputeGlobalForwardingRule(t *testing.T) {
acceptance.Run(t, acceptance.AccTestCase{
TerraformVersion: "0.15.5",
Paths: []string{"./testdata/acc/google_compute_global_forwarding_rule"},
Args: []string{
"scan",
"--to", "gcp+tf",
},
Checks: []acceptance.AccCheck{
{
Check: func(result *test.ScanResult, stdout string, err error) {
if err != nil {
t.Fatal(err)
}
result.AssertInfrastructureIsInSync()
result.AssertManagedCount(1)
},
},
},
})
}

View File

@ -33,6 +33,7 @@ func TestGoogle_Metadata_Flags(t *testing.T) {
GoogleComputeNodeGroupResourceType: {},
GoogleComputeForwardingRuleResourceType: {},
GoogleComputeInstanceGroupManagerResourceType: {},
GoogleComputeGlobalForwardingRuleResourceType: {},
}
schemaRepository := testresource.InitFakeSchemaRepository(tf.GOOGLE, "3.78.0")

View File

@ -0,0 +1,2 @@
*
!google_compute_global_forwarding_rule

View File

@ -0,0 +1,21 @@
# This file is maintained automatically by "terraform init".
# Manual edits may be lost in future updates.
provider "registry.terraform.io/hashicorp/google" {
version = "3.78.0"
constraints = "3.78.0"
hashes = [
"h1:Seut9gKb/KzzUMxa9Qo59LRWcgURfBWMarqNTRjxnXE=",
"zh:027971c4689b6130619827fe57ce260aaca060db3446817d3a92869dba7cc07f",
"zh:0876dbecc0d441bf2479edd17fe9141d77274b5071ea5f68ac26a2994bff66f3",
"zh:2a5363ed6b1b880f5284e604567cfdabecca809584c30bbe7f19ff568d1ea4cd",
"zh:2f5af69b70654bda91199f6393253e3e479107deebfeddc3fe5850b3a1e83dfb",
"zh:52e6816ef11f5f799a6626dfff384e2153b37450d8320f1ef1eee8f71a2a87b2",
"zh:59ae534607db13db35c0015c06d1ae6d4886f01f7e8fd4e07bc120236a01c494",
"zh:65ab2ed1746ea02d0b1bbd8a22ff3a95d09dc8bdb3841fbc17e45e9feccfb327",
"zh:877a71d24ff65ede3f0c5973168acfeaea0f2fea3757cab5600efcddfd3171d5",
"zh:8b10c9643a4a53148f6758bfd60804b33c2b838482f2c39ed210b729e6b1e2e8",
"zh:ba682648d9f6c11a6d04a250ac79eec39271f615f3ff60c5ae73ebfcc2cdb450",
"zh:e946561921e0279450e9b9f705de9354ce35562ed4cc0d4cd3512aa9eb1f6486",
]
}

View File

@ -0,0 +1,59 @@
provider "google" {}
terraform {
required_version = "~> 0.15.0"
required_providers {
google = {
version = "3.78.0"
}
}
}
resource "google_compute_global_forwarding_rule" "default" {
name = "global-rule"
target = google_compute_target_http_proxy.default.id
port_range = "80"
}
resource "google_compute_target_http_proxy" "default" {
name = "target-proxy"
description = "a description"
url_map = google_compute_url_map.default.id
}
resource "google_compute_url_map" "default" {
name = "url-map-target-proxy"
description = "a description"
default_service = google_compute_backend_service.default.id
host_rule {
hosts = ["mysite.com"]
path_matcher = "allpaths"
}
path_matcher {
name = "allpaths"
default_service = google_compute_backend_service.default.id
path_rule {
paths = ["/*"]
service = google_compute_backend_service.default.id
}
}
}
resource "google_compute_backend_service" "default" {
name = "backend"
port_name = "http"
protocol = "HTTP"
timeout_sec = 10
health_checks = [google_compute_http_health_check.default.id]
}
resource "google_compute_http_health_check" "default" {
name = "check-backend"
request_path = "/"
check_interval_sec = 1
timeout_sec = 1
}

View File

@ -200,6 +200,7 @@ var supportedTypes = map[string]ResourceTypeMeta{
"google_cloud_run_service": {},
"google_compute_forwarding_rule": {},
"google_compute_instance_group_manager": {},
"google_compute_global_forwarding_rule": {},
"azurerm_storage_account": {},
"azurerm_storage_container": {},