-
Notifications
You must be signed in to change notification settings - Fork 42
/
provider.go
546 lines (473 loc) · 18.2 KB
/
provider.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package inventory
import (
"context"
"fmt"
"strings"
"sync"
asset "cloud.google.com/go/asset/apiv1"
"cloud.google.com/go/asset/apiv1/assetpb"
"github.com/elastic/elastic-agent-libs/logp"
"github.com/googleapis/gax-go/v2"
"github.com/samber/lo"
"google.golang.org/api/cloudresourcemanager/v3"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"google.golang.org/protobuf/types/known/structpb"
"github.com/elastic/cloudbeat/internal/resources/fetching"
"github.com/elastic/cloudbeat/internal/resources/providers/gcplib/auth"
)
type Provider struct {
log *logp.Logger
config auth.GcpFactoryConfig
inventory *AssetsInventoryWrapper
crm *ResourceManagerWrapper
cloudAccountMetadataCache *MapCache[*fetching.CloudAccountMetadata]
}
type AssetsInventoryWrapper struct {
Close func() error
ListAssets func(ctx context.Context, req *assetpb.ListAssetsRequest, opts ...gax.CallOption) Iterator
}
type ResourceManagerWrapper struct {
// returns project display name or an empty string
getProjectDisplayName func(ctx context.Context, parent string) string
// returns org display name or an empty string
getOrganizationDisplayName func(ctx context.Context, parent string) string
}
type MonitoringAsset struct {
CloudAccount *fetching.CloudAccountMetadata
LogMetrics []*ExtendedGcpAsset `json:"log_metrics,omitempty"`
Alerts []*ExtendedGcpAsset `json:"alerts,omitempty"`
}
type LoggingAsset struct {
CloudAccount *fetching.CloudAccountMetadata
LogSinks []*ExtendedGcpAsset `json:"log_sinks,omitempty"`
}
type ProjectPoliciesAsset struct {
CloudAccount *fetching.CloudAccountMetadata
Policies []*ExtendedGcpAsset `json:"policies,omitempty"`
}
type ServiceUsageAsset struct {
CloudAccount *fetching.CloudAccountMetadata
Services []*ExtendedGcpAsset `json:"services,omitempty"`
}
type ExtendedGcpAsset struct {
*assetpb.Asset
CloudAccount *fetching.CloudAccountMetadata
}
type ProviderInitializer struct{}
type dnsPolicyFields struct {
networks []string
enableLogging bool
}
type TypeGenerator[T any] func(assets []*ExtendedGcpAsset, projectId, projectName, orgId, orgName string) *T
type Iterator interface {
Next() (*assetpb.Asset, error)
}
type ServiceAPI interface {
// ListAllAssetTypesByName List all content types of the given assets types
ListAllAssetTypesByName(ctx context.Context, assets []string) ([]*ExtendedGcpAsset, error)
// ListMonitoringAssets List all monitoring assets by project id
ListMonitoringAssets(ctx context.Context, monitoringAssetTypes map[string][]string) ([]*MonitoringAsset, error)
// ListLoggingAssets returns a list of logging assets grouped by project id, extended with folder and org level log sinks
ListLoggingAssets(ctx context.Context) ([]*LoggingAsset, error)
// ListServiceUsageAssets returns a list of service usage assets grouped by project id
ListServiceUsageAssets(ctx context.Context) ([]*ServiceUsageAsset, error)
// returns a project policies for all its ancestors
ListProjectsAncestorsPolicies(ctx context.Context) ([]*ProjectPoliciesAsset, error)
// Close the GCP asset client
Close() error
}
type ProviderInitializerAPI interface {
// Init initializes the GCP asset client
Init(ctx context.Context, log *logp.Logger, gcpConfig auth.GcpFactoryConfig) (ServiceAPI, error)
}
func (p *ProviderInitializer) Init(ctx context.Context, log *logp.Logger, gcpConfig auth.GcpFactoryConfig) (ServiceAPI, error) {
limiter := NewAssetsInventoryRateLimiter(log)
// initialize GCP assets inventory client
client, err := asset.NewClient(ctx, append(gcpConfig.ClientOpts, option.WithGRPCDialOption(limiter.GetInterceptorDialOption()))...)
if err != nil {
return nil, err
}
// wrap the assets inventory client for mocking
assetsInventoryWrapper := &AssetsInventoryWrapper{
Close: client.Close,
ListAssets: func(ctx context.Context, req *assetpb.ListAssetsRequest, opts ...gax.CallOption) Iterator {
return client.ListAssets(ctx, req, append(opts, RetryOnResourceExhausted)...)
},
}
// initialize GCP resource manager client
var gcpClientOpt []option.ClientOption
gcpClientOpt = append(append(gcpClientOpt, option.WithScopes(cloudresourcemanager.CloudPlatformReadOnlyScope)), gcpConfig.ClientOpts...)
crmService, err := cloudresourcemanager.NewService(ctx, gcpClientOpt...)
if err != nil {
return nil, err
}
displayNamesCache := NewMapCache[string]()
// wrap the resource manager client for mocking
crmServiceWrapper := &ResourceManagerWrapper{
getProjectDisplayName: func(ctx context.Context, parent string) string {
return displayNamesCache.Get(func() string {
prj, err := crmService.Projects.Get(parent).Context(ctx).Do()
if err != nil {
log.Errorf("error fetching GCP Project: %s, error: %s", parent, err)
return ""
}
return prj.DisplayName
}, parent)
},
getOrganizationDisplayName: func(ctx context.Context, parent string) string {
return displayNamesCache.Get(func() string {
org, err := crmService.Organizations.Get(parent).Context(ctx).Do()
if err != nil {
log.Errorf("error fetching GCP Org: %s, error: %s", parent, err)
return ""
}
return org.DisplayName
}, parent)
},
}
return &Provider{
config: gcpConfig,
log: log,
inventory: assetsInventoryWrapper,
crm: crmServiceWrapper,
cloudAccountMetadataCache: NewMapCache[*fetching.CloudAccountMetadata](),
}, nil
}
func (p *Provider) ListAllAssetTypesByName(ctx context.Context, assetTypes []string) ([]*ExtendedGcpAsset, error) {
wg := sync.WaitGroup{}
var resourceAssets []*assetpb.Asset
var policyAssets []*assetpb.Asset
wg.Add(1)
go func() {
resourceAssets = p.getAllAssets(ctx, &assetpb.ListAssetsRequest{
Parent: p.config.Parent,
AssetTypes: assetTypes,
ContentType: assetpb.ContentType_RESOURCE,
})
wg.Done()
}()
wg.Add(1)
go func() {
policyAssets = p.getAllAssets(ctx, &assetpb.ListAssetsRequest{
Parent: p.config.Parent,
AssetTypes: assetTypes,
ContentType: assetpb.ContentType_IAM_POLICY,
})
wg.Done()
}()
wg.Wait()
var assets []*assetpb.Asset
assets = append(append(assets, resourceAssets...), policyAssets...)
mergedAssets := mergeAssetContentType(assets)
extendedAssets := p.extendWithCloudMetadata(ctx, mergedAssets)
// Enrich network assets with dns policy
p.enrichNetworkAssets(ctx, extendedAssets)
return extendedAssets, nil
}
// ListMonitoringAssets returns a list of monitoring assets grouped by project id
func (p *Provider) ListMonitoringAssets(ctx context.Context, monitoringAssetTypes map[string][]string) ([]*MonitoringAsset, error) {
logMetrics, err := p.ListAllAssetTypesByName(ctx, monitoringAssetTypes["LogMetric"])
if err != nil {
return nil, err
}
alertPolicies, err := p.ListAllAssetTypesByName(ctx, monitoringAssetTypes["AlertPolicy"])
if err != nil {
return nil, err
}
typeGenerator := func(assets []*ExtendedGcpAsset, projectId, projectName, orgId, orgName string) *MonitoringAsset {
return &MonitoringAsset{
LogMetrics: getAssetsByType(assets, MonitoringLogMetricAssetType),
Alerts: getAssetsByType(assets, MonitoringAlertPolicyAssetType),
CloudAccount: &fetching.CloudAccountMetadata{
AccountId: projectId,
AccountName: projectName,
OrganisationId: orgId,
OrganizationName: orgName,
},
}
}
var assets []*ExtendedGcpAsset
assets = append(append(assets, logMetrics...), alertPolicies...)
monitoringAssets := getAssetsByProject[MonitoringAsset](assets, p.log, typeGenerator)
return monitoringAssets, nil
}
// ListLoggingAssets returns a list of logging assets grouped by project id, extended with folder and org level log sinks
func (p *Provider) ListLoggingAssets(ctx context.Context) ([]*LoggingAsset, error) {
logSinks, err := p.ListAllAssetTypesByName(ctx, []string{LogSinkAssetType})
if err != nil {
return nil, err
}
typeGenerator := func(assets []*ExtendedGcpAsset, projectId, projectName, orgId, orgName string) *LoggingAsset {
return &LoggingAsset{
LogSinks: assets,
CloudAccount: &fetching.CloudAccountMetadata{
AccountId: projectId,
AccountName: projectName,
OrganisationId: orgId,
OrganizationName: orgName,
},
}
}
loggingAssets := getAssetsByProject[LoggingAsset](logSinks, p.log, typeGenerator)
return loggingAssets, nil
}
// ListServiceUsageAssets returns a list of service usage assets grouped by project id
func (p *Provider) ListServiceUsageAssets(ctx context.Context) ([]*ServiceUsageAsset, error) {
services, err := p.ListAllAssetTypesByName(ctx, []string{ServiceUsageAssetType})
if err != nil {
return nil, err
}
typeGenerator := func(assets []*ExtendedGcpAsset, projectId, projectName, orgId, orgName string) *ServiceUsageAsset {
return &ServiceUsageAsset{
Services: assets,
CloudAccount: &fetching.CloudAccountMetadata{
AccountId: projectId,
AccountName: projectName,
OrganisationId: orgId,
OrganizationName: orgName,
},
}
}
assets := getAssetsByProject[ServiceUsageAsset](services, p.log, typeGenerator)
return assets, nil
}
func (p *Provider) Close() error {
return p.inventory.Close()
}
// enrichNetworkAssets enriches the network assets with dns policy if exists
func (p *Provider) enrichNetworkAssets(ctx context.Context, assets []*ExtendedGcpAsset) {
networkAssets := getAssetsByType(assets, ComputeNetworkAssetType)
if len(networkAssets) == 0 {
p.log.Infof("no %s assets were listed", ComputeNetworkAssetType)
return
}
dnsPolicyAssets := p.getAllAssets(ctx, &assetpb.ListAssetsRequest{
Parent: p.config.Parent,
AssetTypes: []string{DnsPolicyAssetType},
ContentType: assetpb.ContentType_RESOURCE,
})
if len(dnsPolicyAssets) == 0 {
p.log.Infof("no %s assets were listed, return original assets", DnsPolicyAssetType)
return
}
dnsPolicies := decodeDnsPolicies(dnsPolicyAssets)
p.log.Infof("attempting to enrich %d %s assets with dns policy", len(assets), ComputeNetworkAssetType)
for _, networkAsset := range networkAssets {
networkAssetFields := networkAsset.GetResource().GetData().GetFields()
networkIdentifier := strings.TrimPrefix(networkAsset.GetName(), "//compute.googleapis.com")
dnsPolicy := findDnsPolicyByNetwork(dnsPolicies, networkIdentifier)
if dnsPolicy != nil {
p.log.Infof("enrich a %s asset with dns policy, name: %s", ComputeNetworkAssetType, networkIdentifier)
networkAssetFields["enabledDnsLogging"] = &structpb.Value{Kind: &structpb.Value_BoolValue{BoolValue: dnsPolicy.enableLogging}}
}
}
}
// findDnsPolicyByNetwork finds DNS policy by network identifier
func findDnsPolicyByNetwork(dnsPolicies []*dnsPolicyFields, networkIdentifier string) *dnsPolicyFields {
for _, dnsPolicy := range dnsPolicies {
if lo.SomeBy(dnsPolicy.networks, func(networkUrl string) bool {
return strings.HasSuffix(networkUrl, networkIdentifier)
}) {
return dnsPolicy
}
}
return nil
}
// decodeDnsPolicies gets the required fields from the dns policies assets
func decodeDnsPolicies(dnsPolicyAssets []*assetpb.Asset) []*dnsPolicyFields {
dnsPolicies := make([]*dnsPolicyFields, 0)
for _, dnsPolicyAsset := range dnsPolicyAssets {
fields := new(dnsPolicyFields)
dnsPolicyData := dnsPolicyAsset.GetResource().GetData().GetFields()
if attachedNetworks, exist := dnsPolicyData["networks"]; exist {
networks := attachedNetworks.GetListValue().GetValues()
for _, network := range networks {
if networkUrl, found := network.GetStructValue().GetFields()["networkUrl"]; found {
fields.networks = append(fields.networks, networkUrl.GetStringValue())
}
}
}
if enableLogging, exist := dnsPolicyData["enableLogging"]; exist {
fields.enableLogging = enableLogging.GetBoolValue()
}
dnsPolicies = append(dnsPolicies, fields)
}
return dnsPolicies
}
// getAssetsByProject groups assets by project, extracts metadata for each project, and adds folder and organization-level resources for each group.
func getAssetsByProject[T any](assets []*ExtendedGcpAsset, log *logp.Logger, f TypeGenerator[T]) []*T {
assetsByProject := lo.GroupBy(assets, func(asset *ExtendedGcpAsset) string { return asset.CloudAccount.AccountId })
enrichedAssets := make([]*T, 0, len(assetsByProject))
for projectId, projectAssets := range assetsByProject {
if projectId == "" {
continue
}
if len(projectAssets) == 0 {
log.Errorf("no assets were listed for project: %s", projectId)
continue
}
cloudAccount := projectAssets[0].CloudAccount
// add folder and org level log sinks for each project
projectAssets = append(projectAssets, assetsByProject[""]...)
enrichedAssets = append(enrichedAssets, f(
projectAssets,
projectId,
cloudAccount.AccountName,
cloudAccount.OrganisationId,
cloudAccount.OrganizationName,
))
}
return enrichedAssets
}
func (p *Provider) getAllAssets(ctx context.Context, request *assetpb.ListAssetsRequest) []*assetpb.Asset {
p.log.Infof("Listing asset types: %v of type %v for %v", request.AssetTypes, request.ContentType, request.Parent)
results := make([]*assetpb.Asset, 0)
it := p.inventory.ListAssets(ctx, request)
for {
response, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
p.log.Errorf("Error fetching GCP Asset: %s", err)
return results
}
p.log.Debugf("Fetched GCP Asset: %+v", response.Name)
results = append(results, response)
}
return results
}
func mergeAssetContentType(assets []*assetpb.Asset) []*assetpb.Asset {
resultsMap := make(map[string]*assetpb.Asset)
for _, asset := range assets {
assetKey := asset.Name
if _, ok := resultsMap[assetKey]; !ok {
resultsMap[assetKey] = asset
continue
}
item := resultsMap[assetKey]
if asset.Resource != nil {
item.Resource = asset.Resource
}
if asset.IamPolicy != nil {
item.IamPolicy = asset.IamPolicy
}
}
results := make([]*assetpb.Asset, 0, len(resultsMap))
for _, asset := range resultsMap {
results = append(results, asset)
}
return results
}
// extends the assets with the project and organization display name
func (p *Provider) extendWithCloudMetadata(ctx context.Context, assets []*assetpb.Asset) []*ExtendedGcpAsset {
extendedAssets := make([]*ExtendedGcpAsset, 0, len(assets))
for _, asset := range assets {
orgId := getOrganizationId(asset.Ancestors)
projectId := getProjectId(asset.Ancestors)
cacheKey := fmt.Sprintf("%s/%s", projectId, orgId)
cloudAccount := p.cloudAccountMetadataCache.Get(func() *fetching.CloudAccountMetadata {
return p.getCloudAccountMetadata(ctx, projectId, orgId)
}, cacheKey)
extendedAssets = append(extendedAssets, &ExtendedGcpAsset{
Asset: asset,
CloudAccount: cloudAccount,
})
}
return extendedAssets
}
func (p *Provider) ListProjectsAncestorsPolicies(ctx context.Context) ([]*ProjectPoliciesAsset, error) {
projects := p.getAllAssets(ctx, &assetpb.ListAssetsRequest{
ContentType: assetpb.ContentType_IAM_POLICY,
Parent: p.config.Parent,
AssetTypes: []string{CrmProjectAssetType},
})
p.log.Infof("Listed %d GCP projects", len(projects))
ancestorsPoliciesCache := NewMapCache[[]*ExtendedGcpAsset]()
return lo.Map(projects, func(project *assetpb.Asset, _ int) *ProjectPoliciesAsset {
projectAsset := p.extendWithCloudMetadata(ctx, []*assetpb.Asset{project})[0]
// Skip first ancestor it as we already got it
policiesAssets := append([]*ExtendedGcpAsset{projectAsset}, getAncestorsAssets(ctx, ancestorsPoliciesCache, p, project.Ancestors[1:])...)
return &ProjectPoliciesAsset{CloudAccount: projectAsset.CloudAccount, Policies: policiesAssets}
}), nil
}
func getAncestorsAssets(ctx context.Context, ancestorsPoliciesCache *MapCache[[]*ExtendedGcpAsset], p *Provider, ancestors []string) []*ExtendedGcpAsset {
return lo.Flatten(lo.Map(ancestors, func(parent string, _ int) []*ExtendedGcpAsset {
return ancestorsPoliciesCache.Get(func() []*ExtendedGcpAsset {
var assetType string
if strings.HasPrefix(parent, "folders") {
assetType = CrmFolderAssetType
}
if strings.HasPrefix(parent, "organizations") {
assetType = CrmOrgAssetType
}
return p.extendWithCloudMetadata(ctx, p.getAllAssets(ctx, &assetpb.ListAssetsRequest{
ContentType: assetpb.ContentType_IAM_POLICY,
Parent: parent,
AssetTypes: []string{assetType},
}))
}, parent)
}))
}
func (p *Provider) getCloudAccountMetadata(ctx context.Context, projectId string, orgId string) *fetching.CloudAccountMetadata {
var orgName string
var projectName string
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
orgName = p.crm.getOrganizationDisplayName(ctx, fmt.Sprintf("organizations/%s", orgId))
wg.Done()
}()
wg.Add(1)
go func() {
// some assets are not associated with a project
if projectId != "" {
projectName = p.crm.getProjectDisplayName(ctx, fmt.Sprintf("projects/%s", projectId))
}
wg.Done()
}()
wg.Wait()
return &fetching.CloudAccountMetadata{
AccountId: projectId,
AccountName: projectName,
OrganisationId: orgId,
OrganizationName: orgName,
}
}
func getOrganizationId(ancestors []string) string {
last := ancestors[len(ancestors)-1]
parts := strings.Split(last, "/") // organizations/1234567890
if parts[0] == "organizations" {
return parts[1]
}
return ""
}
func getProjectId(ancestors []string) string {
parts := strings.Split(ancestors[0], "/") // projects/1234567890
if parts[0] == "projects" {
return parts[1]
}
return ""
}
func getAssetsByType(projectAssets []*ExtendedGcpAsset, assetType string) []*ExtendedGcpAsset {
return lo.Filter(projectAssets, func(asset *ExtendedGcpAsset, _ int) bool {
return asset.AssetType == assetType
})
}