Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Azure activity logs #1372

Merged
merged 5 commits into from
Oct 2, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions flavors/benchmark/azure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ func TestAzure_Initialize(t *testing.T) {
inventoryInitializer: mockAzureInventoryInitializerService(nil),
want: []string{
"azure_cloud_assets_fetcher",
"azure_cloud_activity_log_alerts_assets_fetcher",
},
},
{
Expand Down
9 changes: 6 additions & 3 deletions resources/fetching/fetcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,12 @@ const (
DataProcessing = "data-processing"

// Azure resource types
AzureDiskType = "azure-disk"
AzureStorageAccountType = "azure-storage-account"
AzureVMType = "azure-vm"
AzureDiskType = "azure-disk"
AzureVMType = "azure-vm"
AzureClassicVMType = "azure-classic-vm"
AzureStorageAccountType = "azure-storage-account"
AzureClassicStorageAccountType = "azure-classic-storage-account"
AzureActivityLogAlertType = "azure-activity-log-alert"
)

// Fetcher represents a data fetcher.
Expand Down
116 changes: 116 additions & 0 deletions resources/fetching/fetchers/azure/activity_log_alerts_fetcher.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// 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 fetchers

import (
"context"
"fmt"

"github.com/elastic/elastic-agent-libs/logp"
"golang.org/x/exp/maps"

"github.com/elastic/cloudbeat/resources/fetching"
"github.com/elastic/cloudbeat/resources/providers/azurelib/inventory"
)

type AzureActivityLogAlertsFetcher struct {
log *logp.Logger
resourceCh chan fetching.ResourceInfo
provider inventory.ServiceAPI
}

type AzureActivityLogAlertsAsset struct {
ActivityLogAlerts []inventory.AzureAsset `json:"activity_log_alerts,omitempty"`
}

type AzureActivityLogAlertsResource struct {
Type string
SubType string
Asset AzureActivityLogAlertsAsset `json:"asset,omitempty"`
}

var AzureActivityLogAlertsResourceTypes = map[string]string{
inventory.ActivityLogAlertAssetType: fetching.AzureActivityLogAlertType,
}

func NewAzureActivityLogAlertsFetcher(log *logp.Logger, ch chan fetching.ResourceInfo, provider inventory.ServiceAPI) *AzureActivityLogAlertsFetcher {
return &AzureActivityLogAlertsFetcher{
log: log,
resourceCh: ch,
provider: provider,
}
}

func (f *AzureActivityLogAlertsFetcher) Fetch(ctx context.Context, cMetadata fetching.CycleMetadata) error {
f.log.Info("Starting AzureActivityLogAlertsFetcher.Fetch")
assets, err := f.provider.ListAllAssetTypesByName(maps.Keys(AzureActivityLogAlertsResourceTypes))
if err != nil {
return err
}

if len(assets) == 0 {
return nil
}

select {
case <-ctx.Done():
f.log.Infof("AzureActivityLogAlertsFetcher.Fetch context err: %s", ctx.Err().Error())
return nil
// TODO: Groups by subscription id to create multiple batches of assets
case f.resourceCh <- fetching.ResourceInfo{
CycleMetadata: cMetadata,
Resource: &AzureActivityLogAlertsResource{
// Every asset in the list has the same type and subtype
Type: AzureActivityLogAlertsResourceTypes[assets[0].Type],
SubType: getAzureActivityLogAlertsSubType(assets[0].Type),
Asset: AzureActivityLogAlertsAsset{
ActivityLogAlerts: assets,
},
},
}:
}

return nil
}

func getAzureActivityLogAlertsSubType(assetType string) string {
return ""
}

func (f *AzureActivityLogAlertsFetcher) Stop() {}

func (r *AzureActivityLogAlertsResource) GetData() any {
return r.Asset
}

func (r *AzureActivityLogAlertsResource) GetMetadata() (fetching.ResourceMetadata, error) {
// Assuming all batch in not empty includes assets of the same subscription
id := fmt.Sprintf("%s-%s", r.Type, r.Asset.ActivityLogAlerts[0].SubscriptionId)
return fetching.ResourceMetadata{
ID: id,
Type: r.Type,
SubType: r.SubType,
Name: id,
// TODO: Make sure ActivityLogAlerts are not location scoped (benchmarks do not check location)
Region: "",
}, nil
}

func (r *AzureActivityLogAlertsResource) GetElasticCommonData() (map[string]any, error) {
return nil, nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// 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 fetchers

import (
"context"
"testing"

"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/suite"

"github.com/elastic/cloudbeat/resources/fetching"
"github.com/elastic/cloudbeat/resources/providers/azurelib/inventory"
"github.com/elastic/cloudbeat/resources/utils/testhelper"
)

type AzureActivityLogAlertsFetcherTestSuite struct {
suite.Suite

resourceCh chan fetching.ResourceInfo
}

func TestAzureActivityLogAlertsFetcherTestSuite(t *testing.T) {
s := new(AzureActivityLogAlertsFetcherTestSuite)

suite.Run(t, s)
}

func (s *AzureActivityLogAlertsFetcherTestSuite) SetupTest() {
s.resourceCh = make(chan fetching.ResourceInfo, 50)
}

func (s *AzureActivityLogAlertsFetcherTestSuite) TearDownTest() {
close(s.resourceCh)
}

func (s *AzureActivityLogAlertsFetcherTestSuite) TestFetcher_Fetch() {
ctx := context.Background()

subId := "subId1"

mockInventoryService := &inventory.MockServiceAPI{}
mockAssets := []inventory.AzureAsset{
{
Id: "id1",
Name: "name1",
Location: "location1",
Properties: map[string]interface{}{"key1": "value1"},
ResourceGroup: "rg1",
SubscriptionId: subId,
TenantId: "tenantId1",
Type: inventory.ActivityLogAlertAssetType,
},
{
Id: "id2",
Name: "name2",
Location: "location2",
Properties: map[string]interface{}{"key2": "value2"},
ResourceGroup: "rg2",
SubscriptionId: subId,
TenantId: "tenantId2",
Type: inventory.ActivityLogAlertAssetType,
},
}

mockInventoryService.EXPECT().
ListAllAssetTypesByName(mock.AnythingOfType("[]string")).
Return(mockAssets, nil).Once()
defer mockInventoryService.AssertExpectations(s.T())

fetcher := AzureActivityLogAlertsFetcher{
log: testhelper.NewLogger(s.T()),
resourceCh: s.resourceCh,
provider: mockInventoryService,
}
err := fetcher.Fetch(ctx, fetching.CycleMetadata{})
s.Require().NoError(err)
results := testhelper.CollectResources(s.resourceCh)

s.Require().Len(results, 1)

activityLogAlerts := results[0].GetData().(AzureActivityLogAlertsAsset).ActivityLogAlerts
for index, r := range activityLogAlerts {
expected := mockAssets[index]
s.Run(expected.Type, func() {
s.Equal(expected, r)
})
}

meta, err := results[0].GetMetadata()
s.Require().NoError(err)
exNameAndId := AzureActivityLogAlertsResourceTypes[mockAssets[0].Type] + "-" + subId
s.Equal(fetching.ResourceMetadata{
ID: exNameAndId,
Type: AzureActivityLogAlertsResourceTypes[mockAssets[0].Type],
SubType: "",
Name: exNameAndId,
Region: "",
AwsAccountId: "",
AwsAccountAlias: "",
AwsOrganizationId: "",
AwsOrganizationName: "",
}, meta)
}
3 changes: 3 additions & 0 deletions resources/fetching/preset/azure_factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,8 @@ func NewCisAzureFactory(log *logp.Logger, ch chan fetching.ResourceInfo, invento
assetsFetcher := fetchers.NewAzureAssetsFetcher(log, ch, inventory)
m["azure_cloud_assets_fetcher"] = registry.RegisteredFetcher{Fetcher: assetsFetcher}

activityLogAlertsFetcher := fetchers.NewAzureActivityLogAlertsFetcher(log, ch, inventory)
m["azure_cloud_activity_log_alerts_assets_fetcher"] = registry.RegisteredFetcher{Fetcher: activityLogAlertsFetcher}

return m, nil
}
9 changes: 6 additions & 3 deletions resources/providers/azurelib/inventory/asset.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@
package inventory

const (
DiskAssetType = "microsoft.compute/disks"
StorageAccountAssetType = "microsoft.storage/storageaccounts"
VirtualMachineAssetType = "microsoft.compute/virtualmachines"
DiskAssetType = "microsoft.compute/disks"
StorageAccountAssetType = "microsoft.storage/storageaccounts"
VirtualMachineAssetType = "microsoft.compute/virtualmachines"
ClassicVirtualMachineAssetType = "microsoft.classiccompute/virtualmachines"
ClassicStorageAccountAssetType = "microsoft.classicstorage/storageaccounts"
ActivityLogAlertAssetType = "microsoft.insights/activitylogalerts"
)
1 change: 1 addition & 0 deletions resources/providers/azurelib/inventory/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ type AzureAsset struct {
SubscriptionId string `json:"subscription_id,omitempty"`
TenantId string `json:"tenant_id,omitempty"`
Type string `json:"type,omitempty"`
Sku string `json:"sku,omitempty"`
}

type ServiceAPI interface {
Expand Down