/
storage_provider.go
285 lines (248 loc) · 11.6 KB
/
storage_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
// 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"
"errors"
"fmt"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/monitor/armmonitor"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage"
"github.com/elastic/elastic-agent-libs/logp"
"github.com/samber/lo"
"github.com/elastic/cloudbeat/internal/resources/fetching/cycle"
"github.com/elastic/cloudbeat/internal/resources/utils/maps"
"github.com/elastic/cloudbeat/internal/resources/utils/pointers"
)
type storageAccountAzureClientWrapper struct {
AssetDiagnosticSettings func(ctx context.Context, subID string, options *armmonitor.DiagnosticSettingsClientListOptions) ([]armmonitor.DiagnosticSettingsClientListResponse, error)
AssetBlobServices func(ctx context.Context, subID string, clientOptions *arm.ClientOptions, resourceGroup, storageAccountName string, options *armstorage.BlobServicesClientListOptions) ([]armstorage.BlobServicesClientListResponse, error)
AssetAccountStorage func(ctx context.Context, subID string, clientOptions *arm.ClientOptions) ([]armstorage.AccountsClientListResponse, error)
}
type StorageAccountProviderAPI interface {
ListDiagnosticSettingsAssetTypes(ctx context.Context, cycleMetadata cycle.Metadata, subscriptionIDs []string) ([]AzureAsset, error)
ListStorageAccountBlobServices(ctx context.Context, storageAccounts []AzureAsset) ([]AzureAsset, error)
ListStorageAccountsBlobDiagnosticSettings(ctx context.Context, storageAccounts []AzureAsset) ([]AzureAsset, error)
ListStorageAccountsTableDiagnosticSettings(ctx context.Context, storageAccounts []AzureAsset) ([]AzureAsset, error)
ListStorageAccountsQueueDiagnosticSettings(ctx context.Context, storageAccounts []AzureAsset) ([]AzureAsset, error)
ListStorageAccounts(ctx context.Context, storageAccountsSubscriptionsIds []string) ([]AzureAsset, error)
}
type storageAccountProvider struct {
client *storageAccountAzureClientWrapper
log *logp.Logger
diagnosticSettingsCache *cycle.Cache[[]AzureAsset]
}
func NewStorageAccountProvider(log *logp.Logger, diagnosticSettingsClient *armmonitor.DiagnosticSettingsClient, credentials azcore.TokenCredential) StorageAccountProviderAPI {
// We wrap the client, so we can mock it in tests
wrapper := &storageAccountAzureClientWrapper{
AssetDiagnosticSettings: func(ctx context.Context, resourceURI string, options *armmonitor.DiagnosticSettingsClientListOptions) ([]armmonitor.DiagnosticSettingsClientListResponse, error) {
pager := diagnosticSettingsClient.NewListPager(resourceURI, options)
return readPager(ctx, pager)
},
AssetBlobServices: func(ctx context.Context, subID string, clientOptions *arm.ClientOptions, resourceGroupName, storageAccountName string, options *armstorage.BlobServicesClientListOptions) ([]armstorage.BlobServicesClientListResponse, error) {
cl, err := armstorage.NewBlobServicesClient(subID, credentials, clientOptions)
if err != nil {
return nil, err
}
return readPager(ctx, cl.NewListPager(resourceGroupName, storageAccountName, options))
},
AssetAccountStorage: func(ctx context.Context, subID string, clientOptions *arm.ClientOptions) ([]armstorage.AccountsClientListResponse, error) {
accountsClient, err := armstorage.NewAccountsClient(subID, credentials, clientOptions)
if err != nil {
return nil, err
}
return readPager(ctx, accountsClient.NewListPager(&armstorage.AccountsClientListOptions{}))
},
}
return &storageAccountProvider{
log: log,
client: wrapper,
diagnosticSettingsCache: cycle.NewCache[[]AzureAsset](log),
}
}
func (p *storageAccountProvider) ListStorageAccounts(ctx context.Context, storageAccountsSubscriptionsIds []string) ([]AzureAsset, error) {
var assets []AzureAsset
for _, saID := range storageAccountsSubscriptionsIds {
res, err := p.client.AssetAccountStorage(ctx, saID, nil)
if err != nil {
p.log.Errorf("error while fetching storage accounts for subscriptionId: %s, error: %v", saID, err)
continue
}
storageAccountsAssets, err := transformStorageAccounts(res, saID)
if err != nil {
p.log.Errorf("error while transforming storage for subscriptionId: %s, error: %v", saID, err)
continue
}
assets = append(assets, storageAccountsAssets...)
}
return assets, nil
}
func transformStorageAccounts(accountPages []armstorage.AccountsClientListResponse, storageAccountId string) ([]AzureAsset, error) {
var errs error
return lo.FlatMap(accountPages, func(response armstorage.AccountsClientListResponse, _ int) []AzureAsset {
return lo.Map(response.Value, func(item *armstorage.Account, _ int) AzureAsset {
properties, err := maps.AsMapStringAny(item.Properties)
if err != nil {
errs = errors.Join(errs, err)
}
return AzureAsset{
Id: pointers.Deref(item.ID),
Name: pointers.Deref(item.Name),
Type: strings.ToLower(pointers.Deref(item.Type)),
// These are kept empty because:
// 1. they are not used for evaluation
// 2. only subscriptionId is required for the request issued by armstorage.NewAccountsClient
ResourceGroup: "",
TenantId: "",
SubscriptionId: storageAccountId,
Properties: properties,
Extension: map[string]any{
ExtensionStorageAccountID: pointers.Deref(item.ID),
ExtensionStorageAccountName: pointers.Deref(item.Name),
},
}
})
}), errs
}
func (p *storageAccountProvider) ListStorageAccountBlobServices(ctx context.Context, storageAccounts []AzureAsset) ([]AzureAsset, error) {
var assets []AzureAsset
for _, sa := range storageAccounts {
responses, err := p.client.AssetBlobServices(ctx, sa.SubscriptionId, nil, sa.ResourceGroup, sa.Name, nil)
if err != nil {
return nil, fmt.Errorf("error while fetching azure blob services for storage accounts %s: %w", sa.Id, err)
}
blobServices, err := transformBlobServices(responses, sa)
if err != nil {
return nil, fmt.Errorf("error while transforming azure blob services for storage accounts %s: %w", sa.Id, err)
}
assets = append(assets, blobServices...)
}
return assets, nil
}
func transformBlobServices(servicesPages []armstorage.BlobServicesClientListResponse, storageAccount AzureAsset) ([]AzureAsset, error) {
var errs error
return lo.FlatMap(servicesPages, func(response armstorage.BlobServicesClientListResponse, _ int) []AzureAsset {
return lo.Map(response.Value, func(item *armstorage.BlobServiceProperties, _ int) AzureAsset {
properties, err := maps.AsMapStringAny(item.BlobServiceProperties)
if err != nil {
errs = errors.Join(errs, err)
}
return AzureAsset{
Id: pointers.Deref(item.ID),
Name: pointers.Deref(item.Name),
Type: strings.ToLower(pointers.Deref(item.Type)),
ResourceGroup: storageAccount.ResourceGroup,
SubscriptionId: storageAccount.SubscriptionId,
TenantId: storageAccount.TenantId,
Properties: properties,
Extension: map[string]any{
ExtensionStorageAccountID: storageAccount.Id,
ExtensionStorageAccountName: storageAccount.Name,
},
}
})
}), errs
}
func (p *storageAccountProvider) ListStorageAccountsBlobDiagnosticSettings(ctx context.Context, storageAccounts []AzureAsset) ([]AzureAsset, error) {
return p.serviceDiagnosticSettings(ctx, "blobServices/default", storageAccounts)
}
func (p *storageAccountProvider) ListStorageAccountsTableDiagnosticSettings(ctx context.Context, storageAccounts []AzureAsset) ([]AzureAsset, error) {
return p.serviceDiagnosticSettings(ctx, "tableServices/default", storageAccounts)
}
func (p *storageAccountProvider) ListStorageAccountsQueueDiagnosticSettings(ctx context.Context, storageAccounts []AzureAsset) ([]AzureAsset, error) {
return p.serviceDiagnosticSettings(ctx, "queueServices/default", storageAccounts)
}
func (p *storageAccountProvider) ListDiagnosticSettingsAssetTypes(ctx context.Context, cycleMetadata cycle.Metadata, subscriptionIDs []string) ([]AzureAsset, error) {
p.log.Info("Listing Azure Diagnostic Monitor Settings")
return p.diagnosticSettingsCache.GetValue(ctx, cycleMetadata, func(ctx context.Context) ([]AzureAsset, error) {
return p.getDiagnosticSettings(ctx, subscriptionIDs)
})
}
func (p *storageAccountProvider) getDiagnosticSettings(ctx context.Context, subscriptionIDs []string) ([]AzureAsset, error) {
var assets []AzureAsset
for _, subID := range subscriptionIDs {
responses, err := p.client.AssetDiagnosticSettings(ctx, fmt.Sprintf("/subscriptions/%s/", subID), nil)
if err != nil {
return nil, err
}
a, err := transformDiagnosticSettingsClientListResponses(responses, subID)
if err != nil {
return nil, err
}
assets = append(assets, a...)
}
return assets, nil
}
func (p *storageAccountProvider) serviceDiagnosticSettings(ctx context.Context, serviceIDPostfix string, storageAccounts []AzureAsset) ([]AzureAsset, error) {
var assets []AzureAsset
for _, sa := range storageAccounts {
queueDiagSettings, err := p.storageAccountServiceDiagnosticSettings(ctx, serviceIDPostfix, sa)
if err != nil {
return nil, err
}
assets = append(assets, queueDiagSettings...)
}
return assets, nil
}
func (p *storageAccountProvider) storageAccountServiceDiagnosticSettings(ctx context.Context, idPostfix string, storageAccount AzureAsset) ([]AzureAsset, error) {
res, err := p.client.AssetDiagnosticSettings(ctx, fmt.Sprintf("%s/%s", storageAccount.Id, idPostfix), nil)
if err != nil {
return nil, fmt.Errorf("error while fetching storage account service %s diagnostic settings: %w", idPostfix, err)
}
assets, err := transformDiagnosticSettingsClientListResponses(res, storageAccount.SubscriptionId)
if err != nil {
return nil, fmt.Errorf("error while transforming storage account service %s diagnostic settings: %w", idPostfix, err)
}
for i := range assets {
(&assets[i]).AddExtension(ExtensionStorageAccountID, storageAccount.Id)
}
return assets, nil
}
func transformDiagnosticSettingsClientListResponses(response []armmonitor.DiagnosticSettingsClientListResponse, subID string) ([]AzureAsset, error) {
var assets []AzureAsset
for _, settingsCollection := range response {
for _, v := range settingsCollection.Value {
if v == nil {
continue
}
a, err := transformDiagnosticSettingsResource(v, subID)
if err != nil {
return nil, fmt.Errorf("error parsing azure asset model: %w", err)
}
assets = append(assets, a)
}
}
return assets, nil
}
func transformDiagnosticSettingsResource(v *armmonitor.DiagnosticSettingsResource, subID string) (AzureAsset, error) {
properties, err := maps.AsMapStringAny(v.Properties)
if err != nil {
return AzureAsset{}, err
}
return AzureAsset{
Id: pointers.Deref(v.ID),
Name: pointers.Deref(v.Name),
Location: "global",
Properties: properties,
ResourceGroup: "",
SubscriptionId: subID,
TenantId: "",
Type: pointers.Deref(v.Type),
}, nil
}