Skip to content
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 43 additions & 1 deletion pkg/cmd/scan.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,22 @@ func NewScanCmd(opts *pkg.ScanOptions) *cobra.Command {
)
}

GCPScope, _ := cmd.Flags().GetStringSlice("gcp-scope")
limitScope := make([]string, 0)

if to == common.RemoteGoogleTerraform && len(GCPScope) > 0 {
limitScope, err = parseScopeFlag(GCPScope)
if err != nil {
return err
}
} else if to != common.RemoteGoogleTerraform && len(GCPScope) > 0 {
return errors.New("gcp-scope can only be utilized when using " + common.RemoteGoogleTerraform + " flag")
} else if to == common.RemoteGoogleTerraform && len(GCPScope) == 0 {
return errors.New("gcp-scope must be specified when using " + common.RemoteGoogleTerraform + " flag")
}
Comment on lines +73 to +77
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Plea try to avoid else-if statements, there is not reason do use them here


opts.GCPScope = limitScope

outputFlag, _ := cmd.Flags().GetStringSlice("output")

out, err := parseOutputFlags(outputFlag)
Expand Down Expand Up @@ -124,6 +140,12 @@ func NewScanCmd(opts *pkg.ScanOptions) *cobra.Command {
false,
"Do not display anything but scan results",
)
fl.StringSliceP(
"gcp-scope",
"s",
[]string{},
"Set the GCP scope for search",
)
fl.StringArray(
"filter",
[]string{},
Expand Down Expand Up @@ -239,7 +261,7 @@ func scanRun(opts *pkg.ScanOptions) error {

resFactory := terraform.NewTerraformResourceFactory(resourceSchemaRepository)

err := remote.Activate(opts.To, opts.ProviderVersion, alerter, providerLibrary, remoteLibrary, scanProgress, resourceSchemaRepository, resFactory, opts.ConfigDir)
err := remote.Activate(opts.To, opts.ProviderVersion, opts.GCPScope, alerter, providerLibrary, remoteLibrary, scanProgress, resourceSchemaRepository, resFactory, opts.ConfigDir)
if err != nil {
return err
}
Expand Down Expand Up @@ -323,6 +345,26 @@ func scanRun(opts *pkg.ScanOptions) error {
return nil
}

func parseScopeFlag(scope []string) ([]string, error) {

scopeRegex := `projects/\S*$|folders/\d*$|organizations/\S*$`
r := regexp.MustCompile(scopeRegex)

for _, v := range scope {
if !r.MatchString(v) {
return nil, errors.Wrapf(
cmderrors.NewUsageError(
"\nAccepted formats are: projects/<project-id>, folders/<folder-number>, organizations/<org-id>",
),
"Unable to parse GCP scope '%s'",
v,
)
}
}

return scope, nil
}

func parseFromFlag(from []string) ([]config.SupplierConfig, error) {

configs := make([]config.SupplierConfig, 0, len(from))
Expand Down
4 changes: 2 additions & 2 deletions pkg/cmd/scan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -356,14 +356,14 @@ func Test_Options(t *testing.T) {
},
{
name: "should not find provider version in lockfile",
args: []string{"scan", "--to", "gcp+tf", "--tf-lockfile", "testdata/terraform_valid.lock.hcl"},
args: []string{"scan", "--to", "gcp+tf", "--gcp-scope", "organizations/123", "--tf-lockfile", "testdata/terraform_valid.lock.hcl"},
assertOptions: func(t *testing.T, opts *pkg.ScanOptions) {
assert.Equal(t, "", opts.ProviderVersion)
},
},
{
name: "should fail to read lockfile with silent error",
args: []string{"scan", "--to", "gcp+tf", "--tf-lockfile", "testdata/terraform_invalid.lock.hcl"},
args: []string{"scan", "--to", "gcp+tf", "--gcp-scope", "organizations/123", "--tf-lockfile", "testdata/terraform_invalid.lock.hcl"},
assertOptions: func(t *testing.T, opts *pkg.ScanOptions) {
assert.Equal(t, "", opts.ProviderVersion)
},
Expand Down
1 change: 1 addition & 0 deletions pkg/driftctl.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type ScanOptions struct {
Detect bool
From []config.SupplierConfig
To string
GCPScope []string
Output []output.OutputConfig
Filter *jmespath.JMESPath
Quiet bool
Expand Down
4 changes: 1 addition & 3 deletions pkg/remote/google/config/config.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package config

type GCPTerraformConfig struct {
Project string `cty:"project"`
Region string `cty:"region"`
Zone string `cty:"zone"`
Scope []string `cty:"scope"`
}
6 changes: 3 additions & 3 deletions pkg/remote/google/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
"google.golang.org/api/cloudresourcemanager/v1"
)

func Init(version string, alerter *alerter.Alerter,
func Init(version string, gcpScope []string, alerter *alerter.Alerter,
providerLibrary *terraform.ProviderLibrary,
remoteLibrary *common.RemoteLibrary,
progress output.Progress,
Expand Down Expand Up @@ -51,9 +51,9 @@ func Init(version string, alerter *alerter.Alerter,
return err
}

assetRepository := repository.NewAssetRepository(assetClient, provider.GetConfig(), repositoryCache)
assetRepository := repository.NewAssetRepository(assetClient, provider.SetConfig(gcpScope), repositoryCache)
storageRepository := repository.NewStorageRepository(storageClient, repositoryCache)
iamRepository := repository.NewCloudResourceManagerRepository(crmService, provider.GetConfig(), repositoryCache)
iamRepository := repository.NewCloudResourceManagerRepository(crmService, provider.SetConfig(gcpScope), repositoryCache)

providerLibrary.AddProvider(terraform.GOOGLE, provider)
deserializer := resource.NewDeserializer(factory)
Expand Down
10 changes: 3 additions & 7 deletions pkg/remote/google/provider.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package google

import (
"os"

"github.com/snyk/driftctl/pkg/output"
"github.com/snyk/driftctl/pkg/remote/google/config"
"github.com/snyk/driftctl/pkg/remote/terraform"
Expand Down Expand Up @@ -34,7 +32,7 @@ func NewGCPTerraformProvider(version string, progress output.Progress, configDir
tfProvider, err := terraform.NewTerraformProvider(installer, terraform.TerraformProviderConfig{
Name: p.name,
GetProviderConfig: func(alias string) interface{} {
return p.GetConfig()
return p.SetConfig(nil)
},
}, progress)

Expand All @@ -55,10 +53,8 @@ func (p *GCPTerraformProvider) Version() string {
return p.version
}

func (p *GCPTerraformProvider) GetConfig() config.GCPTerraformConfig {
func (p *GCPTerraformProvider) SetConfig(scope []string) config.GCPTerraformConfig {
return config.GCPTerraformConfig{
Project: os.Getenv("CLOUDSDK_CORE_PROJECT"),
Region: os.Getenv("CLOUDSDK_COMPUTE_REGION"),
Zone: os.Getenv("CLOUDSDK_COMPUTE_ZONE"),
Comment on lines -61 to -62
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do you removed Region and Zone parameters ?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because they are not needed since we use scopes.

Scope: scope,
}
}
169 changes: 89 additions & 80 deletions pkg/remote/google/repository/asset.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package repository

import (
"context"
"fmt"

asset "cloud.google.com/go/asset/apiv1"
"github.com/snyk/driftctl/pkg/remote/cache"
Expand Down Expand Up @@ -75,101 +74,111 @@ func NewAssetRepository(client *asset.Client, config config.GCPTerraformConfig,
}

func (s assetRepository) listAllResources(ty string) ([]*assetpb.Asset, error) {
req := &assetpb.ListAssetsRequest{
Parent: fmt.Sprintf("projects/%s", s.config.Project),
ContentType: assetpb.ContentType_RESOURCE,
AssetTypes: []string{
cloudFunctionsFunction,
bigtableInstanceAssetType,
bigtableTableAssetType,
sqlDatabaseInstanceAssetType,
computeGlobalAddressAssetType,
nodeGroupAssetType,
},
}
var results []*assetpb.Asset

cacheKey := "listAllResources"
cachedResults := s.cache.GetAndLock(cacheKey)
defer s.cache.Unlock(cacheKey)
if cachedResults != nil {
results = cachedResults.([]*assetpb.Asset)
}
filteredResults := []*assetpb.Asset{}

if results == nil {
it := s.client.ListAssets(context.Background(), req)
for {
resource, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
for _, scope := range s.config.Scope {
cacheKey := "listAllResources" + scope
cachedResults := s.cache.GetAndLock(cacheKey)
defer s.cache.Unlock(cacheKey)

req := &assetpb.ListAssetsRequest{
Parent: scope,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure that a folder is supported for listAssets call according to the documentation here : https://cloud.google.com/asset-inventory/docs/reference/rpc/google.cloud.asset.v1#google.cloud.asset.v1.ListAssetsRequest

Can you double check that ?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed. Ideally we should not use listAssets but only searchAssets as the main difference is that list takes a snapshot of how the assets were at a particular time, which could result in a diff from what it's actually present.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where did you get this info ? I asked this question here a couple of month ago and I didn't get any answer.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From here there are a couple of hints about it:

Listing assets might not meet the performance requirements for large scale customers. If this is the case for you and calling list API encounters timeout, it's recommended to use export API instead.

Also in the API it's mentioned the purpose is to list resources from a specific timeframe

Lists assets with time and resource types and returns paged results in response.
readTime:  Timestamp to take an asset snapshot.  If not specified, the current time will be used. Due to delays in resource data collection and indexing, there is a volatile window during which running the same query may get different results.

While the search is more appropriate for our intent:

The Cloud Asset API allows you to use a custom query language to query resource metadata on a project, folder, or organization.
Method: searchAllResources. Searches all Cloud resources within the specified scope, such as a project, folder, or organization. 

ContentType: assetpb.ContentType_RESOURCE,
AssetTypes: []string{
cloudFunctionsFunction,
bigtableInstanceAssetType,
bigtableTableAssetType,
sqlDatabaseInstanceAssetType,
computeGlobalAddressAssetType,
nodeGroupAssetType,
},
}

var results []*assetpb.Asset

if cachedResults != nil {
results = cachedResults.([]*assetpb.Asset)
}

if results == nil {
it := s.client.ListAssets(context.Background(), req)
for {
resource, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
results = append(results, resource)
}
results = append(results, resource)
s.cache.Put(cacheKey, results)
}
s.cache.Put(cacheKey, results)
}

filteredResults := []*assetpb.Asset{}
for _, result := range results {
if result.AssetType == ty {
filteredResults = append(filteredResults, result)
for _, result := range results {
if result.AssetType == ty {
filteredResults = append(filteredResults, result)
}
}
}

return filteredResults, nil
}

func (s assetRepository) searchAllResources(ty string) ([]*assetpb.ResourceSearchResult, error) {
req := &assetpb.SearchAllResourcesRequest{
Scope: fmt.Sprintf("projects/%s", s.config.Project),
AssetTypes: []string{
storageBucketAssetType,
computeFirewallAssetType,
computeRouterAssetType,
computeInstanceAssetType,
computeNetworkAssetType,
computeSubnetworkAssetType,
dnsManagedZoneAssetType,
computeInstanceGroupAssetType,
bigqueryDatasetAssetType,
bigqueryTableAssetType,
computeAddressAssetType,
computeDiskAssetType,
computeImageAssetType,
healthCheckAssetType,
cloudRunServiceAssetType,
},
}
var results []*assetpb.ResourceSearchResult

cacheKey := "SearchAllResources"
cachedResults := s.cache.GetAndLock(cacheKey)
defer s.cache.Unlock(cacheKey)
if cachedResults != nil {
results = cachedResults.([]*assetpb.ResourceSearchResult)
}
filteredResults := []*assetpb.ResourceSearchResult{}

if results == nil {
it := s.client.SearchAllResources(context.Background(), req)
for {
resource, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
for _, scope := range s.config.Scope {
cacheKey := "SearchAllResources" + scope
cachedResults := s.cache.GetAndLock(cacheKey)
defer s.cache.Unlock(cacheKey)

req := &assetpb.SearchAllResourcesRequest{
Scope: scope,
AssetTypes: []string{
storageBucketAssetType,
computeFirewallAssetType,
computeRouterAssetType,
computeInstanceAssetType,
computeNetworkAssetType,
computeSubnetworkAssetType,
dnsManagedZoneAssetType,
computeInstanceGroupAssetType,
bigqueryDatasetAssetType,
bigqueryTableAssetType,
computeAddressAssetType,
computeDiskAssetType,
computeImageAssetType,
healthCheckAssetType,
cloudRunServiceAssetType,
},
}
var results []*assetpb.ResourceSearchResult

if cachedResults != nil {
results = cachedResults.([]*assetpb.ResourceSearchResult)
}

if results == nil {
it := s.client.SearchAllResources(context.Background(), req)
for {
resource, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
results = append(results, resource)
}
results = append(results, resource)
s.cache.Put(cacheKey, results)
}
s.cache.Put(cacheKey, results)
}

filteredResults := []*assetpb.ResourceSearchResult{}
for _, result := range results {
if result.AssetType == ty {
filteredResults = append(filteredResults, result)
for _, result := range results {
if result.AssetType == ty {
filteredResults = append(filteredResults, result)
}
}
}

Expand Down
4 changes: 2 additions & 2 deletions pkg/remote/google/repository/asset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func Test_assetRepository_searchAllResources_CacheHit(t *testing.T) {
c := &cache.MockCache{}
c.On("GetAndLock", "SearchAllResources").Return(expectedResults).Times(1)
c.On("Unlock", "SearchAllResources").Times(1)
repo := NewAssetRepository(nil, config.GCPTerraformConfig{Project: ""}, c)
repo := NewAssetRepository(nil, config.GCPTerraformConfig{Scope: []string{""}}, c)

got, err := repo.searchAllResources("google_fake_type")
c.AssertExpectations(t)
Expand Down Expand Up @@ -55,7 +55,7 @@ func Test_assetRepository_searchAllResources_CacheMiss(t *testing.T) {
c.On("GetAndLock", "SearchAllResources").Return(nil).Times(1)
c.On("Unlock", "SearchAllResources").Times(1)
c.On("Put", "SearchAllResources", mock.IsType([]*assetpb.ResourceSearchResult{})).Return(false).Times(1)
repo := NewAssetRepository(assetClient, config.GCPTerraformConfig{Project: ""}, c)
repo := NewAssetRepository(assetClient, config.GCPTerraformConfig{Scope: []string{""}}, c)

got, err := repo.searchAllResources("google_fake_type")
c.AssertExpectations(t)
Expand Down
Loading