diff --git a/internal/services/sentinel/client/client.go b/internal/services/sentinel/client/client.go index e71307000a15..ece9790e58e4 100644 --- a/internal/services/sentinel/client/client.go +++ b/internal/services/sentinel/client/client.go @@ -2,13 +2,14 @@ package client import ( alertruletemplates "github.com/Azure/azure-sdk-for-go/services/preview/securityinsight/mgmt/2021-09-01-preview/securityinsight" // nolint: staticcheck + "github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules" "github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-11-01/sentinelonboardingstates" "github.com/hashicorp/terraform-provider-azurerm/internal/common" securityinsight "github.com/tombuildsstuff/kermit/sdk/securityinsights/2022-10-01-preview/securityinsights" ) type Client struct { - AlertRulesClient *securityinsight.AlertRulesClient + AlertRulesClient *alertrules.AlertRulesClient AlertRuleTemplatesClient *alertruletemplates.AlertRuleTemplatesClient AutomationRulesClient *securityinsight.AutomationRulesClient DataConnectorsClient *securityinsight.DataConnectorsClient @@ -18,7 +19,7 @@ type Client struct { } func NewClient(o *common.ClientOptions) *Client { - alertRulesClient := securityinsight.NewAlertRulesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + alertRulesClient := alertrules.NewAlertRulesClientWithBaseURI(o.ResourceManagerEndpoint) o.ConfigureClient(&alertRulesClient.Client, o.ResourceManagerAuthorizer) alertRuleTemplatesClient := alertruletemplates.NewAlertRuleTemplatesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) diff --git a/internal/services/sentinel/parse/alert_rule.go b/internal/services/sentinel/parse/alert_rule.go deleted file mode 100644 index f3806161cb35..000000000000 --- a/internal/services/sentinel/parse/alert_rule.go +++ /dev/null @@ -1,75 +0,0 @@ -package parse - -// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten - -import ( - "fmt" - "strings" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" -) - -type AlertRuleId struct { - SubscriptionId string - ResourceGroup string - WorkspaceName string - Name string -} - -func NewAlertRuleID(subscriptionId, resourceGroup, workspaceName, name string) AlertRuleId { - return AlertRuleId{ - SubscriptionId: subscriptionId, - ResourceGroup: resourceGroup, - WorkspaceName: workspaceName, - Name: name, - } -} - -func (id AlertRuleId) String() string { - segments := []string{ - fmt.Sprintf("Name %q", id.Name), - fmt.Sprintf("Workspace Name %q", id.WorkspaceName), - fmt.Sprintf("Resource Group %q", id.ResourceGroup), - } - segmentsStr := strings.Join(segments, " / ") - return fmt.Sprintf("%s: (%s)", "Alert Rule", segmentsStr) -} - -func (id AlertRuleId) ID() string { - fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.OperationalInsights/workspaces/%s/providers/Microsoft.SecurityInsights/alertRules/%s" - return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.WorkspaceName, id.Name) -} - -// AlertRuleID parses a AlertRule ID into an AlertRuleId struct -func AlertRuleID(input string) (*AlertRuleId, error) { - id, err := resourceids.ParseAzureResourceID(input) - if err != nil { - return nil, err - } - - resourceId := AlertRuleId{ - SubscriptionId: id.SubscriptionID, - ResourceGroup: id.ResourceGroup, - } - - if resourceId.SubscriptionId == "" { - return nil, fmt.Errorf("ID was missing the 'subscriptions' element") - } - - if resourceId.ResourceGroup == "" { - return nil, fmt.Errorf("ID was missing the 'resourceGroups' element") - } - - if resourceId.WorkspaceName, err = id.PopSegment("workspaces"); err != nil { - return nil, err - } - if resourceId.Name, err = id.PopSegment("alertRules"); err != nil { - return nil, err - } - - if err := id.ValidateNoEmptySegments(input); err != nil { - return nil, err - } - - return &resourceId, nil -} diff --git a/internal/services/sentinel/parse/alert_rule_test.go b/internal/services/sentinel/parse/alert_rule_test.go deleted file mode 100644 index 4a9eef7ec267..000000000000 --- a/internal/services/sentinel/parse/alert_rule_test.go +++ /dev/null @@ -1,128 +0,0 @@ -package parse - -// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten - -import ( - "testing" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" -) - -var _ resourceids.Id = AlertRuleId{} - -func TestAlertRuleIDFormatter(t *testing.T) { - actual := NewAlertRuleID("12345678-1234-9876-4563-123456789012", "resGroup1", "workspace1", "rule1").ID() - expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.OperationalInsights/workspaces/workspace1/providers/Microsoft.SecurityInsights/alertRules/rule1" - if actual != expected { - t.Fatalf("Expected %q but got %q", expected, actual) - } -} - -func TestAlertRuleID(t *testing.T) { - testData := []struct { - Input string - Error bool - Expected *AlertRuleId - }{ - - { - // empty - Input: "", - Error: true, - }, - - { - // missing SubscriptionId - Input: "/", - Error: true, - }, - - { - // missing value for SubscriptionId - Input: "/subscriptions/", - Error: true, - }, - - { - // missing ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", - Error: true, - }, - - { - // missing value for ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", - Error: true, - }, - - { - // missing WorkspaceName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.OperationalInsights/", - Error: true, - }, - - { - // missing value for WorkspaceName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.OperationalInsights/workspaces/", - Error: true, - }, - - { - // missing Name - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.OperationalInsights/workspaces/workspace1/providers/Microsoft.SecurityInsights/", - Error: true, - }, - - { - // missing value for Name - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.OperationalInsights/workspaces/workspace1/providers/Microsoft.SecurityInsights/alertRules/", - Error: true, - }, - - { - // valid - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.OperationalInsights/workspaces/workspace1/providers/Microsoft.SecurityInsights/alertRules/rule1", - Expected: &AlertRuleId{ - SubscriptionId: "12345678-1234-9876-4563-123456789012", - ResourceGroup: "resGroup1", - WorkspaceName: "workspace1", - Name: "rule1", - }, - }, - - { - // upper-cased - Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/RESGROUP1/PROVIDERS/MICROSOFT.OPERATIONALINSIGHTS/WORKSPACES/WORKSPACE1/PROVIDERS/MICROSOFT.SECURITYINSIGHTS/ALERTRULES/RULE1", - Error: true, - }, - } - - for _, v := range testData { - t.Logf("[DEBUG] Testing %q", v.Input) - - actual, err := AlertRuleID(v.Input) - if err != nil { - if v.Error { - continue - } - - t.Fatalf("Expect a value but got an error: %s", err) - } - if v.Error { - t.Fatal("Expect an error but didn't get one") - } - - if actual.SubscriptionId != v.Expected.SubscriptionId { - t.Fatalf("Expected %q but got %q for SubscriptionId", v.Expected.SubscriptionId, actual.SubscriptionId) - } - if actual.ResourceGroup != v.Expected.ResourceGroup { - t.Fatalf("Expected %q but got %q for ResourceGroup", v.Expected.ResourceGroup, actual.ResourceGroup) - } - if actual.WorkspaceName != v.Expected.WorkspaceName { - t.Fatalf("Expected %q but got %q for WorkspaceName", v.Expected.WorkspaceName, actual.WorkspaceName) - } - if actual.Name != v.Expected.Name { - t.Fatalf("Expected %q but got %q for Name", v.Expected.Name, actual.Name) - } - } -} diff --git a/internal/services/sentinel/resourceids.go b/internal/services/sentinel/resourceids.go index dc5677e2a9eb..0d0381f93fde 100644 --- a/internal/services/sentinel/resourceids.go +++ b/internal/services/sentinel/resourceids.go @@ -1,6 +1,5 @@ package sentinel -//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=AlertRule -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.OperationalInsights/workspaces/workspace1/providers/Microsoft.SecurityInsights/alertRules/rule1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=SentinelAlertRuleTemplate -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.OperationalInsights/workspaces/workspace1/providers/Microsoft.SecurityInsights/alertRuleTemplates/template1 -rewrite=true //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=DataConnector -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.OperationalInsights/workspaces/workspace1/providers/Microsoft.SecurityInsights/dataConnectors/dc1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=AutomationRule -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.OperationalInsights/workspaces/workspace1/providers/Microsoft.SecurityInsights/automationRules/rule1 -rewrite=true diff --git a/internal/services/sentinel/sentinel_alert_rule.go b/internal/services/sentinel/sentinel_alert_rule.go index 8183dd6539ea..57860debd3ae 100644 --- a/internal/services/sentinel/sentinel_alert_rule.go +++ b/internal/services/sentinel/sentinel_alert_rule.go @@ -4,66 +4,50 @@ import ( "context" "fmt" + "github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/sentinel/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" - securityinsight "github.com/tombuildsstuff/kermit/sdk/securityinsights/2022-10-01-preview/securityinsights" ) -func alertRuleID(rule securityinsight.BasicAlertRule) *string { - if rule == nil { - return nil - } - switch rule := rule.(type) { - case securityinsight.FusionAlertRule: - return rule.ID - case securityinsight.MicrosoftSecurityIncidentCreationAlertRule: - return rule.ID - case securityinsight.ScheduledAlertRule: - return rule.ID - case securityinsight.MLBehaviorAnalyticsAlertRule: - return rule.ID - case securityinsight.NrtAlertRule: - return rule.ID - default: - return nil - } -} - -func importSentinelAlertRule(expectKind securityinsight.AlertRuleKind) pluginsdk.ImporterFunc { +func importSentinelAlertRule(expectKind alertrules.AlertRuleKind) pluginsdk.ImporterFunc { return func(ctx context.Context, d *pluginsdk.ResourceData, meta interface{}) (data []*pluginsdk.ResourceData, err error) { - id, err := parse.AlertRuleID(d.Id()) + id, err := alertrules.ParseAlertRuleID(d.Id()) if err != nil { return nil, err } client := meta.(*clients.Client).Sentinel.AlertRulesClient - resp, err := client.Get(ctx, id.ResourceGroup, id.WorkspaceName, id.Name) + resp, err := client.AlertRulesGet(ctx, *id) if err != nil { return nil, fmt.Errorf("retrieving Sentinel Alert Rule %q: %+v", id, err) } - if err := assertAlertRuleKind(resp.Value, expectKind); err != nil { + if err = assertAlertRuleKind(resp.Model, expectKind); err != nil { return nil, err } return []*pluginsdk.ResourceData{d}, nil } } -func assertAlertRuleKind(rule securityinsight.BasicAlertRule, expectKind securityinsight.AlertRuleKind) error { - var kind securityinsight.AlertRuleKind - switch rule.(type) { - case securityinsight.MLBehaviorAnalyticsAlertRule: - kind = securityinsight.AlertRuleKindMLBehaviorAnalytics - case securityinsight.FusionAlertRule: - kind = securityinsight.AlertRuleKindFusion - case securityinsight.MicrosoftSecurityIncidentCreationAlertRule: - kind = securityinsight.AlertRuleKindMicrosoftSecurityIncidentCreation - case securityinsight.ScheduledAlertRule: - kind = securityinsight.AlertRuleKindScheduled - case securityinsight.NrtAlertRule: - kind = securityinsight.AlertRuleKindNRT +func assertAlertRuleKind(rule *alertrules.AlertRule, expectKind alertrules.AlertRuleKind) error { + if rule == nil { + return fmt.Errorf("model was nil") + } + + rulePtr := *rule + var kind alertrules.AlertRuleKind + switch rulePtr.(type) { + case alertrules.MLBehaviorAnalyticsAlertRule: + kind = alertrules.AlertRuleKindMLBehaviorAnalytics + case alertrules.FusionAlertRule: + kind = alertrules.AlertRuleKindFusion + case alertrules.MicrosoftSecurityIncidentCreationAlertRule: + kind = alertrules.AlertRuleKindMicrosoftSecurityIncidentCreation + case alertrules.ScheduledAlertRule: + kind = alertrules.AlertRuleKindScheduled + case alertrules.NrtAlertRule: + kind = alertrules.AlertRuleKindNRT } if expectKind != kind { return fmt.Errorf("Sentinel Alert Rule has mismatched kind, expected: %q, got %q", expectKind, kind) @@ -71,17 +55,17 @@ func assertAlertRuleKind(rule securityinsight.BasicAlertRule, expectKind securit return nil } -func expandAlertRuleTactics(input []interface{}) *[]securityinsight.AttackTactic { - result := make([]securityinsight.AttackTactic, 0) +func expandAlertRuleTactics(input []interface{}) *[]alertrules.AttackTactic { + result := make([]alertrules.AttackTactic, 0) for _, e := range input { - result = append(result, securityinsight.AttackTactic(e.(string))) + result = append(result, alertrules.AttackTactic(e.(string))) } return &result } -func flattenAlertRuleTactics(input *[]securityinsight.AttackTactic) []interface{} { +func flattenAlertRuleTactics(input *[]alertrules.AttackTactic) []interface{} { if input == nil { return []interface{}{} } @@ -105,51 +89,46 @@ func expandAlertRuleTechnicals(input []interface{}) *[]string { return &result } -func expandAlertRuleIncidentConfiguration(input []interface{}, createIncidentKey string, withGroupByPrefix bool) *securityinsight.IncidentConfiguration { +func expandAlertRuleIncidentConfiguration(input []interface{}, createIncidentKey string, withGroupByPrefix bool) *alertrules.IncidentConfiguration { if len(input) == 0 || input[0] == nil { return nil } raw := input[0].(map[string]interface{}) - output := &securityinsight.IncidentConfiguration{ - CreateIncident: utils.Bool(raw[createIncidentKey].(bool)), + output := &alertrules.IncidentConfiguration{ + CreateIncident: raw[createIncidentKey].(bool), GroupingConfiguration: expandAlertRuleGrouping(raw["grouping"].([]interface{}), withGroupByPrefix), } return output } -func flattenAlertRuleIncidentConfiguration(input *securityinsight.IncidentConfiguration, createIncidentKey string, withGroupByPrefix bool) []interface{} { +func flattenAlertRuleIncidentConfiguration(input *alertrules.IncidentConfiguration, createIncidentKey string, withGroupByPrefix bool) []interface{} { if input == nil { return []interface{}{} } - createIncident := false - if input.CreateIncident != nil { - createIncident = *input.CreateIncident - } - return []interface{}{ map[string]interface{}{ - createIncidentKey: createIncident, + createIncidentKey: input.CreateIncident, "grouping": flattenAlertRuleGrouping(input.GroupingConfiguration, withGroupByPrefix), }, } } -func expandAlertRuleGrouping(input []interface{}, withGroupPrefix bool) *securityinsight.GroupingConfiguration { +func expandAlertRuleGrouping(input []interface{}, withGroupPrefix bool) *alertrules.GroupingConfiguration { if len(input) == 0 || input[0] == nil { return nil } raw := input[0].(map[string]interface{}) - output := &securityinsight.GroupingConfiguration{ - Enabled: utils.Bool(raw["enabled"].(bool)), - ReopenClosedIncident: utils.Bool(raw["reopen_closed_incidents"].(bool)), - LookbackDuration: utils.String(raw["lookback_duration"].(string)), - MatchingMethod: securityinsight.MatchingMethod(raw["entity_matching_method"].(string)), + output := &alertrules.GroupingConfiguration{ + Enabled: raw["enabled"].(bool), + ReopenClosedIncident: raw["reopen_closed_incidents"].(bool), + LookbackDuration: raw["lookback_duration"].(string), + MatchingMethod: alertrules.MatchingMethod(raw["entity_matching_method"].(string)), } key := "by_entities" @@ -157,9 +136,9 @@ func expandAlertRuleGrouping(input []interface{}, withGroupPrefix bool) *securit key = "group_" + key } groupByEntitiesList := raw[key].([]interface{}) - groupByEntities := make([]securityinsight.EntityMappingType, len(groupByEntitiesList)) + groupByEntities := make([]alertrules.EntityMappingType, len(groupByEntitiesList)) for idx, t := range groupByEntitiesList { - groupByEntities[idx] = securityinsight.EntityMappingType(t.(string)) + groupByEntities[idx] = alertrules.EntityMappingType(t.(string)) } output.GroupByEntities = &groupByEntities @@ -168,9 +147,9 @@ func expandAlertRuleGrouping(input []interface{}, withGroupPrefix bool) *securit key = "group_" + key } groupByAlertDetailsList := raw[key].([]interface{}) - groupByAlertDetails := make([]securityinsight.AlertDetail, len(groupByAlertDetailsList)) + groupByAlertDetails := make([]alertrules.AlertDetail, len(groupByAlertDetailsList)) for idx, t := range groupByAlertDetailsList { - groupByAlertDetails[idx] = securityinsight.AlertDetail(t.(string)) + groupByAlertDetails[idx] = alertrules.AlertDetail(t.(string)) } output.GroupByAlertDetails = &groupByAlertDetails @@ -183,26 +162,11 @@ func expandAlertRuleGrouping(input []interface{}, withGroupPrefix bool) *securit return output } -func flattenAlertRuleGrouping(input *securityinsight.GroupingConfiguration, withGroupPrefix bool) []interface{} { +func flattenAlertRuleGrouping(input *alertrules.GroupingConfiguration, withGroupPrefix bool) []interface{} { if input == nil { return []interface{}{} } - enabled := false - if input.Enabled != nil { - enabled = *input.Enabled - } - - lookbackDuration := "" - if input.LookbackDuration != nil { - lookbackDuration = *input.LookbackDuration - } - - reopenClosedIncidents := false - if input.ReopenClosedIncident != nil { - reopenClosedIncidents = *input.ReopenClosedIncident - } - var groupByEntities []interface{} if input.GroupByEntities != nil { for _, entity := range *input.GroupByEntities { @@ -237,9 +201,9 @@ func flattenAlertRuleGrouping(input *securityinsight.GroupingConfiguration, with } return []interface{}{ map[string]interface{}{ - "enabled": enabled, - "lookback_duration": lookbackDuration, - "reopen_closed_incidents": reopenClosedIncidents, + "enabled": input.Enabled, + "lookback_duration": input.LookbackDuration, + "reopen_closed_incidents": input.ReopenClosedIncident, "entity_matching_method": string(input.MatchingMethod), k1: groupByEntities, k2: groupByAlertDetails, @@ -248,13 +212,13 @@ func flattenAlertRuleGrouping(input *securityinsight.GroupingConfiguration, with } } -func expandAlertRuleAlertDetailsOverride(input []interface{}) *securityinsight.AlertDetailsOverride { +func expandAlertRuleAlertDetailsOverride(input []interface{}) *alertrules.AlertDetailsOverride { if len(input) == 0 || input[0] == nil { return nil } b := input[0].(map[string]interface{}) - output := &securityinsight.AlertDetailsOverride{} + output := &alertrules.AlertDetailsOverride{} if v := b["description_format"]; v != "" { output.AlertDescriptionFormat = utils.String(v.(string)) @@ -275,7 +239,7 @@ func expandAlertRuleAlertDetailsOverride(input []interface{}) *securityinsight.A return output } -func flattenAlertRuleAlertDetailsOverride(input *securityinsight.AlertDetailsOverride) []interface{} { +func flattenAlertRuleAlertDetailsOverride(input *alertrules.AlertDetailsOverride) []interface{} { if input == nil { return []interface{}{} } @@ -316,17 +280,18 @@ func flattenAlertRuleAlertDetailsOverride(input *securityinsight.AlertDetailsOve } } -func expandAlertRuleAlertDynamicProperties(input []interface{}) *[]securityinsight.AlertPropertyMapping { +func expandAlertRuleAlertDynamicProperties(input []interface{}) *[]alertrules.AlertPropertyMapping { if len(input) == 0 || input[0] == nil { return nil } - var output []securityinsight.AlertPropertyMapping + var output []alertrules.AlertPropertyMapping for _, v := range input { b := v.(map[string]interface{}) - output = append(output, securityinsight.AlertPropertyMapping{ - AlertProperty: securityinsight.AlertProperty(b["name"].(string)), + property := alertrules.AlertProperty(b["name"].(string)) + output = append(output, alertrules.AlertPropertyMapping{ + AlertProperty: &property, Value: utils.String(b["value"].(string)), }) } @@ -334,15 +299,19 @@ func expandAlertRuleAlertDynamicProperties(input []interface{}) *[]securityinsig return &output } -func flattenAlertRuleAlertDynamicProperties(input *[]securityinsight.AlertPropertyMapping) []interface{} { +func flattenAlertRuleAlertDynamicProperties(input *[]alertrules.AlertPropertyMapping) []interface{} { output := make([]interface{}, 0) if input == nil || len(*input) == 0 { return output } for _, i := range *input { + name := "" + if i.AlertProperty != nil { + name = string(*i.AlertProperty) + } output = append(output, map[string]interface{}{ - "name": string(i.AlertProperty), + "name": name, "value": i.Value, }) } @@ -350,17 +319,18 @@ func flattenAlertRuleAlertDynamicProperties(input *[]securityinsight.AlertProper return output } -func expandAlertRuleEntityMapping(input []interface{}) *[]securityinsight.EntityMapping { +func expandAlertRuleEntityMapping(input []interface{}) *[]alertrules.EntityMapping { if len(input) == 0 { return nil } - result := make([]securityinsight.EntityMapping, 0) + result := make([]alertrules.EntityMapping, 0) for _, e := range input { b := e.(map[string]interface{}) - result = append(result, securityinsight.EntityMapping{ - EntityType: securityinsight.EntityMappingType(b["entity_type"].(string)), + mappingType := alertrules.EntityMappingType(b["entity_type"].(string)) + result = append(result, alertrules.EntityMapping{ + EntityType: &mappingType, FieldMappings: expandAlertRuleFieldMapping(b["field_mapping"].([]interface{})), }) } @@ -368,7 +338,7 @@ func expandAlertRuleEntityMapping(input []interface{}) *[]securityinsight.Entity return &result } -func flattenAlertRuleEntityMapping(input *[]securityinsight.EntityMapping) []interface{} { +func flattenAlertRuleEntityMapping(input *[]alertrules.EntityMapping) []interface{} { if input == nil { return []interface{}{} } @@ -376,8 +346,12 @@ func flattenAlertRuleEntityMapping(input *[]securityinsight.EntityMapping) []int output := make([]interface{}, 0) for _, e := range *input { + entityType := "" + if e.EntityType != nil { + entityType = string(*e.EntityType) + } output = append(output, map[string]interface{}{ - "entity_type": string(e.EntityType), + "entity_type": entityType, "field_mapping": flattenAlertRuleFieldMapping(e.FieldMappings), }) } @@ -385,16 +359,16 @@ func flattenAlertRuleEntityMapping(input *[]securityinsight.EntityMapping) []int return output } -func expandAlertRuleFieldMapping(input []interface{}) *[]securityinsight.FieldMapping { +func expandAlertRuleFieldMapping(input []interface{}) *[]alertrules.FieldMapping { if len(input) == 0 { return nil } - result := make([]securityinsight.FieldMapping, 0) + result := make([]alertrules.FieldMapping, 0) for _, e := range input { b := e.(map[string]interface{}) - result = append(result, securityinsight.FieldMapping{ + result = append(result, alertrules.FieldMapping{ Identifier: utils.String(b["identifier"].(string)), ColumnName: utils.String(b["column_name"].(string)), }) @@ -403,7 +377,7 @@ func expandAlertRuleFieldMapping(input []interface{}) *[]securityinsight.FieldMa return &result } -func flattenAlertRuleFieldMapping(input *[]securityinsight.FieldMapping) []interface{} { +func flattenAlertRuleFieldMapping(input *[]alertrules.FieldMapping) []interface{} { if input == nil { return []interface{}{} } @@ -430,16 +404,16 @@ func flattenAlertRuleFieldMapping(input *[]securityinsight.FieldMapping) []inter return output } -func expandAlertRuleSentinelEntityMapping(input []interface{}) *[]securityinsight.SentinelEntityMapping { +func expandAlertRuleSentinelEntityMapping(input []interface{}) *[]alertrules.SentinelEntityMapping { if len(input) == 0 { return nil } - result := make([]securityinsight.SentinelEntityMapping, 0) + result := make([]alertrules.SentinelEntityMapping, 0) for _, e := range input { b := e.(map[string]interface{}) - result = append(result, securityinsight.SentinelEntityMapping{ + result = append(result, alertrules.SentinelEntityMapping{ ColumnName: utils.String(b["column_name"].(string)), }) } @@ -447,7 +421,7 @@ func expandAlertRuleSentinelEntityMapping(input []interface{}) *[]securityinsigh return &result } -func flattenAlertRuleSentinelEntityMapping(input *[]securityinsight.SentinelEntityMapping) []interface{} { +func flattenAlertRuleSentinelEntityMapping(input *[]alertrules.SentinelEntityMapping) []interface{} { if input == nil { return []interface{}{} } diff --git a/internal/services/sentinel/sentinel_alert_rule_data_source.go b/internal/services/sentinel/sentinel_alert_rule_data_source.go index 11f43bca51b4..d484bf8b7437 100644 --- a/internal/services/sentinel/sentinel_alert_rule_data_source.go +++ b/internal/services/sentinel/sentinel_alert_rule_data_source.go @@ -4,13 +4,12 @@ import ( "fmt" "time" - "github.com/hashicorp/go-azure-sdk/resource-manager/operationalinsights/2020-08-01/workspaces" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/sentinel/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceSentinelAlertRule() *pluginsdk.Resource { @@ -31,7 +30,7 @@ func dataSourceSentinelAlertRule() *pluginsdk.Resource { "log_analytics_workspace_id": { Type: pluginsdk.TypeString, Required: true, - ValidateFunc: workspaces.ValidateWorkspaceID, + ValidateFunc: alertrules.ValidateWorkspaceID, }, }, } @@ -43,19 +42,19 @@ func dataSourceSentinelAlertRuleRead(d *pluginsdk.ResourceData, meta interface{} defer cancel() name := d.Get("name").(string) - workspaceID, err := workspaces.ParseWorkspaceID(d.Get("log_analytics_workspace_id").(string)) + workspaceID, err := alertrules.ParseWorkspaceID(d.Get("log_analytics_workspace_id").(string)) if err != nil { return err } - id := parse.NewAlertRuleID(workspaceID.SubscriptionId, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) + id := alertrules.NewAlertRuleID(workspaceID.SubscriptionId, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) - resp, err := client.Get(ctx, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) + resp, err := client.AlertRulesGet(ctx, id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("Sentinel Alert Rule %q was not found", id) + if response.WasNotFound(resp.HttpResponse) { + return fmt.Errorf("%q was not found", id) } - return fmt.Errorf("retrieving Sentinel Alert Rule %q: %+v", id, err) + return fmt.Errorf("retrieving %q: %+v", id, err) } d.SetId(id.ID()) diff --git a/internal/services/sentinel/sentinel_alert_rule_fusion_resource.go b/internal/services/sentinel/sentinel_alert_rule_fusion_resource.go index 580484b12490..6265d407240d 100644 --- a/internal/services/sentinel/sentinel_alert_rule_fusion_resource.go +++ b/internal/services/sentinel/sentinel_alert_rule_fusion_resource.go @@ -5,15 +5,13 @@ import ( "log" "time" - "github.com/hashicorp/go-azure-sdk/resource-manager/operationalinsights/2020-08-01/workspaces" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/sentinel/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" - securityinsight "github.com/tombuildsstuff/kermit/sdk/securityinsights/2022-10-01-preview/securityinsights" ) func resourceSentinelAlertRuleFusion() *pluginsdk.Resource { @@ -24,9 +22,9 @@ func resourceSentinelAlertRuleFusion() *pluginsdk.Resource { Delete: resourceSentinelAlertRuleFusionDelete, Importer: pluginsdk.ImporterValidatingResourceIdThen(func(id string) error { - _, err := parse.AlertRuleID(id) + _, err := alertrules.ParseAlertRuleID(id) return err - }, importSentinelAlertRule(securityinsight.AlertRuleKindFusion)), + }, importSentinelAlertRule(alertrules.AlertRuleKindFusion)), Timeouts: &pluginsdk.ResourceTimeout{ Create: pluginsdk.DefaultTimeout(30 * time.Minute), @@ -47,7 +45,7 @@ func resourceSentinelAlertRuleFusion() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ForceNew: true, - ValidateFunc: workspaces.ValidateWorkspaceID, + ValidateFunc: alertrules.ValidateWorkspaceID, }, "alert_rule_template_guid": { @@ -103,10 +101,10 @@ func resourceSentinelAlertRuleFusion() *pluginsdk.Resource { Type: pluginsdk.TypeString, ValidateFunc: validation.StringInSlice( []string{ - string(securityinsight.AlertSeverityHigh), - string(securityinsight.AlertSeverityMedium), - string(securityinsight.AlertSeverityLow), - string(securityinsight.AlertSeverityInformational), + string(alertrules.AlertSeverityHigh), + string(alertrules.AlertSeverityMedium), + string(alertrules.AlertSeverityLow), + string(alertrules.AlertSeverityInformational), }, false, ), @@ -129,47 +127,48 @@ func resourceSentinelAlertRuleFusionCreateUpdate(d *pluginsdk.ResourceData, meta name := d.Get("name").(string) - workspaceID, err := workspaces.ParseWorkspaceID(d.Get("log_analytics_workspace_id").(string)) + workspaceID, err := alertrules.ParseWorkspaceID(d.Get("log_analytics_workspace_id").(string)) if err != nil { return err } - id := parse.NewAlertRuleID(workspaceID.SubscriptionId, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) + id := alertrules.NewAlertRuleID(workspaceID.SubscriptionId, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) if d.IsNewResource() { - resp, err := client.Get(ctx, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) + resp, err := client.AlertRulesGet(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("checking for existing Sentinel Alert Rule Fusion %q: %+v", id, err) + if !response.WasNotFound(resp.HttpResponse) { + return fmt.Errorf("checking for existing %q: %+v", id, err) } } - id := alertRuleID(resp.Value) - if id != nil && *id != "" { - return tf.ImportAsExistsError("azurerm_sentinel_alert_rule_fusion", *id) + if !response.WasNotFound(resp.HttpResponse) { + return tf.ImportAsExistsError("azurerm_sentinel_alert_rule_fusion", id.ID()) } } - params := securityinsight.FusionAlertRule{ - Kind: securityinsight.KindBasicAlertRuleKindFusion, - FusionAlertRuleProperties: &securityinsight.FusionAlertRuleProperties{ - AlertRuleTemplateName: utils.String(d.Get("alert_rule_template_guid").(string)), - Enabled: utils.Bool(d.Get("enabled").(bool)), + params := alertrules.FusionAlertRule{ + Properties: &alertrules.FusionAlertRuleProperties{ + AlertRuleTemplateName: d.Get("alert_rule_template_guid").(string), + Enabled: d.Get("enabled").(bool), SourceSettings: expandFusionSourceSettings(d.Get("source").([]interface{})), }, } if !d.IsNewResource() { - resp, err := client.Get(ctx, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) + resp, err := client.AlertRulesGet(ctx, id) if err != nil { - return fmt.Errorf("retrieving Sentinel Alert Rule Fusion %q: %+v", id, err) + return fmt.Errorf("retrieving %q: %+v", id, err) } - if err := assertAlertRuleKind(resp.Value, securityinsight.AlertRuleKindFusion); err != nil { + if resp.Model == nil { + return fmt.Errorf("retrieving %q: model was nil", id) + } + if err = assertAlertRuleKind(resp.Model, alertrules.AlertRuleKindFusion); err != nil { return fmt.Errorf("asserting alert rule of %q: %+v", id, err) } } - if _, err := client.CreateOrUpdate(ctx, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name, params); err != nil { + if _, err := client.AlertRulesCreateOrUpdate(ctx, id, params); err != nil { return fmt.Errorf("creating Sentinel Alert Rule Fusion %q: %+v", id, err) } @@ -183,15 +182,15 @@ func resourceSentinelAlertRuleFusionRead(d *pluginsdk.ResourceData, meta interfa ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.AlertRuleID(d.Id()) + id, err := alertrules.ParseAlertRuleID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.WorkspaceName, id.Name) + resp, err := client.AlertRulesGet(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[DEBUG] Sentinel Alert Rule Fusion %q was not found - removing from state!", id) + if response.WasNotFound(resp.HttpResponse) { + log.Printf("[DEBUG] %q was not found - removing from state!", id) d.SetId("") return nil } @@ -199,21 +198,24 @@ func resourceSentinelAlertRuleFusionRead(d *pluginsdk.ResourceData, meta interfa return fmt.Errorf("retrieving Sentinel Alert Rule Fusion %q: %+v", id, err) } - if err := assertAlertRuleKind(resp.Value, securityinsight.AlertRuleKindFusion); err != nil { - return fmt.Errorf("asserting alert rule of %q: %+v", id, err) - } - rule := resp.Value.(securityinsight.FusionAlertRule) + if model := resp.Model; model != nil { + if err := assertAlertRuleKind(resp.Model, alertrules.AlertRuleKindFusion); err != nil { + return fmt.Errorf("asserting alert rule of %q: %+v", id, err) + } + modelPtr := *model + rule := modelPtr.(alertrules.FusionAlertRule) - d.Set("name", id.Name) + d.Set("name", id.RuleId) - workspaceId := workspaces.NewWorkspaceID(id.SubscriptionId, id.ResourceGroup, id.WorkspaceName) - d.Set("log_analytics_workspace_id", workspaceId.ID()) + workspaceId := alertrules.NewWorkspaceID(id.SubscriptionId, id.ResourceGroupName, id.WorkspaceName) + d.Set("log_analytics_workspace_id", workspaceId.ID()) - if prop := rule.FusionAlertRuleProperties; prop != nil { - d.Set("enabled", prop.Enabled) - d.Set("alert_rule_template_guid", prop.AlertRuleTemplateName) - if err := d.Set("source", flattenFusionSourceSettings(prop.SourceSettings)); err != nil { - return fmt.Errorf("setting `source`: %v", err) + if prop := rule.Properties; prop != nil { + d.Set("enabled", prop.Enabled) + d.Set("alert_rule_template_guid", prop.AlertRuleTemplateName) + if err := d.Set("source", flattenFusionSourceSettings(prop.SourceSettings)); err != nil { + return fmt.Errorf("setting `source`: %v", err) + } } } @@ -225,30 +227,30 @@ func resourceSentinelAlertRuleFusionDelete(d *pluginsdk.ResourceData, meta inter ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.AlertRuleID(d.Id()) + id, err := alertrules.ParseAlertRuleID(d.Id()) if err != nil { return err } - if _, err := client.Delete(ctx, id.ResourceGroup, id.WorkspaceName, id.Name); err != nil { + if _, err := client.AlertRulesDelete(ctx, *id); err != nil { return fmt.Errorf("deleting Sentinel Alert Rule Fusion %q: %+v", id, err) } return nil } -func expandFusionSourceSettings(input []interface{}) *[]securityinsight.FusionSourceSettings { +func expandFusionSourceSettings(input []interface{}) *[]alertrules.FusionSourceSettings { if len(input) == 0 { return nil } - result := make([]securityinsight.FusionSourceSettings, 0) + result := make([]alertrules.FusionSourceSettings, 0) for _, e := range input { e := e.(map[string]interface{}) - setting := securityinsight.FusionSourceSettings{ - Enabled: utils.Bool(e["enabled"].(bool)), - SourceName: utils.String(e["name"].(string)), + setting := alertrules.FusionSourceSettings{ + Enabled: e["enabled"].(bool), + SourceName: e["name"].(string), SourceSubTypes: expandFusionSourceSubTypes(e["sub_type"].([]interface{})), } result = append(result, setting) @@ -257,19 +259,19 @@ func expandFusionSourceSettings(input []interface{}) *[]securityinsight.FusionSo return &result } -func expandFusionSourceSubTypes(input []interface{}) *[]securityinsight.FusionSourceSubTypeSetting { +func expandFusionSourceSubTypes(input []interface{}) *[]alertrules.FusionSourceSubTypeSetting { if len(input) == 0 { return nil } - result := make([]securityinsight.FusionSourceSubTypeSetting, 0) + result := make([]alertrules.FusionSourceSubTypeSetting, 0) for _, e := range input { e := e.(map[string]interface{}) - setting := securityinsight.FusionSourceSubTypeSetting{ - Enabled: utils.Bool(e["enabled"].(bool)), - SourceSubTypeName: utils.String(e["name"].(string)), - SeverityFilters: &securityinsight.FusionSubTypeSeverityFilter{ + setting := alertrules.FusionSourceSubTypeSetting{ + Enabled: e["enabled"].(bool), + SourceSubTypeName: e["name"].(string), + SeverityFilters: alertrules.FusionSubTypeSeverityFilter{ Filters: expandFusionSubTypeSeverityFiltersItems(e["severities_allowed"].(*pluginsdk.Set).List()), }, } @@ -279,18 +281,18 @@ func expandFusionSourceSubTypes(input []interface{}) *[]securityinsight.FusionSo return &result } -func expandFusionSubTypeSeverityFiltersItems(input []interface{}) *[]securityinsight.FusionSubTypeSeverityFiltersItem { +func expandFusionSubTypeSeverityFiltersItems(input []interface{}) *[]alertrules.FusionSubTypeSeverityFiltersItem { if len(input) == 0 { return nil } - result := make([]securityinsight.FusionSubTypeSeverityFiltersItem, 0) + result := make([]alertrules.FusionSubTypeSeverityFiltersItem, 0) // We can't simply remove the disabled properties in the request, as that will be reflected to the backend model (i.e. those unspecified severity will be absent also). // As any absent severity then will not be shown in the Portal when users try to edit the alert rule. The drop down menu won't show these absent severities... filters := map[string]bool{} - for _, e := range securityinsight.PossibleAlertSeverityValues() { - filters[string(e)] = false + for _, e := range alertrules.PossibleValuesForAlertSeverity() { + filters[e] = false } for _, e := range input { @@ -298,9 +300,9 @@ func expandFusionSubTypeSeverityFiltersItems(input []interface{}) *[]securityins } for severity, enabled := range filters { - item := securityinsight.FusionSubTypeSeverityFiltersItem{ - Enabled: utils.Bool(enabled), - Severity: securityinsight.AlertSeverity(severity), + item := alertrules.FusionSubTypeSeverityFiltersItem{ + Enabled: enabled, + Severity: alertrules.AlertSeverity(severity), } result = append(result, item) } @@ -308,7 +310,7 @@ func expandFusionSubTypeSeverityFiltersItems(input []interface{}) *[]securityins return &result } -func flattenFusionSourceSettings(input *[]securityinsight.FusionSourceSettings) []interface{} { +func flattenFusionSourceSettings(input *[]alertrules.FusionSourceSettings) []interface{} { if input == nil { return []interface{}{} } @@ -316,19 +318,9 @@ func flattenFusionSourceSettings(input *[]securityinsight.FusionSourceSettings) output := make([]interface{}, 0) for _, e := range *input { - var name string - if e.SourceName != nil { - name = *e.SourceName - } - - var enabled bool - if e.Enabled != nil { - enabled = *e.Enabled - } - output = append(output, map[string]interface{}{ - "name": name, - "enabled": enabled, + "name": e.SourceName, + "enabled": e.Enabled, "sub_type": flattenFusionSourceSubTypes(e.SourceSubTypes), }) } @@ -336,7 +328,7 @@ func flattenFusionSourceSettings(input *[]securityinsight.FusionSourceSettings) return output } -func flattenFusionSourceSubTypes(input *[]securityinsight.FusionSourceSubTypeSetting) []interface{} { +func flattenFusionSourceSubTypes(input *[]alertrules.FusionSourceSubTypeSetting) []interface{} { if input == nil { return []interface{}{} } @@ -344,32 +336,17 @@ func flattenFusionSourceSubTypes(input *[]securityinsight.FusionSourceSubTypeSet output := make([]interface{}, 0) for _, e := range *input { - var name string - if e.SourceSubTypeName != nil { - name = *e.SourceSubTypeName - } - - var enabledSeverities []interface{} - if e.SeverityFilters != nil { - enabledSeverities = flattenFusionSubTypeSeverityFiltersItems(e.SeverityFilters.Filters) - } - - var enabled bool - if e.Enabled != nil { - enabled = *e.Enabled - } - output = append(output, map[string]interface{}{ - "name": name, - "enabled": enabled, - "severities_allowed": enabledSeverities, + "name": e.SourceSubTypeName, + "enabled": e.Enabled, + "severities_allowed": flattenFusionSubTypeSeverityFiltersItems(e.SeverityFilters.Filters), }) } return output } -func flattenFusionSubTypeSeverityFiltersItems(input *[]securityinsight.FusionSubTypeSeverityFiltersItem) []interface{} { +func flattenFusionSubTypeSeverityFiltersItems(input *[]alertrules.FusionSubTypeSeverityFiltersItem) []interface{} { if input == nil { return []interface{}{} } @@ -377,7 +354,7 @@ func flattenFusionSubTypeSeverityFiltersItems(input *[]securityinsight.FusionSub output := make([]interface{}, 0) for _, e := range *input { - if e.Enabled != nil && *e.Enabled { + if e.Enabled { output = append(output, string(e.Severity)) } } diff --git a/internal/services/sentinel/sentinel_alert_rule_fusion_resource_test.go b/internal/services/sentinel/sentinel_alert_rule_fusion_resource_test.go index 8288c397e484..deafb5f6ef55 100644 --- a/internal/services/sentinel/sentinel_alert_rule_fusion_resource_test.go +++ b/internal/services/sentinel/sentinel_alert_rule_fusion_resource_test.go @@ -5,13 +5,13 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/sentinel/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" - securityinsight "github.com/tombuildsstuff/kermit/sdk/securityinsights/2022-10-01-preview/securityinsights" ) type SentinelAlertRuleFusionResource struct{} @@ -98,26 +98,30 @@ func TestAccSentinelAlertRuleFusion_requiresImport(t *testing.T) { func (r SentinelAlertRuleFusionResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { alertRuleClient := client.Sentinel.AlertRulesClient - id, err := parse.AlertRuleID(state.ID) + id, err := alertrules.ParseAlertRuleID(state.ID) if err != nil { return nil, err } - resp, err := alertRuleClient.Get(ctx, id.ResourceGroup, id.WorkspaceName, id.Name) + resp, err := alertRuleClient.AlertRulesGet(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return utils.Bool(false), nil } return nil, fmt.Errorf("retrieving Sentinel Alert Rule Fusion (%q): %+v", state.String(), err) } - rule, ok := resp.Value.(securityinsight.FusionAlertRule) - if !ok { - return nil, fmt.Errorf("the Alert Rule %q is not a Fusion Alert Rule", id) + if model := resp.Model; model != nil { + modelPtr := *model + rule, ok := modelPtr.(alertrules.FusionAlertRule) + if !ok { + return nil, fmt.Errorf("the Alert Rule %q is not a Fusion Alert Rule", id) + } + return utils.Bool(rule.Id != nil), nil } - return utils.Bool(rule.ID != nil), nil + return utils.Bool(false), nil } func (r SentinelAlertRuleFusionResource) basic(data acceptance.TestData) string { diff --git a/internal/services/sentinel/sentinel_alert_rule_machine_learning_behavior_analytics.go b/internal/services/sentinel/sentinel_alert_rule_machine_learning_behavior_analytics.go index 3a9692c4e1d8..4cfe60c32b44 100644 --- a/internal/services/sentinel/sentinel_alert_rule_machine_learning_behavior_analytics.go +++ b/internal/services/sentinel/sentinel_alert_rule_machine_learning_behavior_analytics.go @@ -5,15 +5,13 @@ import ( "log" "time" - "github.com/hashicorp/go-azure-sdk/resource-manager/operationalinsights/2020-08-01/workspaces" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/sentinel/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" - securityinsight "github.com/tombuildsstuff/kermit/sdk/securityinsights/2022-10-01-preview/securityinsights" ) func resourceSentinelAlertRuleMLBehaviorAnalytics() *pluginsdk.Resource { @@ -24,9 +22,9 @@ func resourceSentinelAlertRuleMLBehaviorAnalytics() *pluginsdk.Resource { Delete: resourceSentinelAlertRuleMLBehaviorAnalyticsDelete, Importer: pluginsdk.ImporterValidatingResourceIdThen(func(id string) error { - _, err := parse.AlertRuleID(id) + _, err := alertrules.ParseAlertRuleID(id) return err - }, importSentinelAlertRule(securityinsight.AlertRuleKindMLBehaviorAnalytics)), + }, importSentinelAlertRule(alertrules.AlertRuleKindMLBehaviorAnalytics)), Timeouts: &pluginsdk.ResourceTimeout{ Create: pluginsdk.DefaultTimeout(30 * time.Minute), @@ -47,7 +45,7 @@ func resourceSentinelAlertRuleMLBehaviorAnalytics() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ForceNew: true, - ValidateFunc: workspaces.ValidateWorkspaceID, + ValidateFunc: alertrules.ValidateWorkspaceID, }, "alert_rule_template_guid": { @@ -73,46 +71,44 @@ func resourceSentinelAlertRuleMLBehaviorAnalyticsCreateUpdate(d *pluginsdk.Resou name := d.Get("name").(string) - workspaceID, err := workspaces.ParseWorkspaceID(d.Get("log_analytics_workspace_id").(string)) + workspaceID, err := alertrules.ParseWorkspaceID(d.Get("log_analytics_workspace_id").(string)) if err != nil { return err } - id := parse.NewAlertRuleID(workspaceID.SubscriptionId, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) + id := alertrules.NewAlertRuleID(workspaceID.SubscriptionId, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) if d.IsNewResource() { - resp, err := client.Get(ctx, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) + resp, err := client.AlertRulesGet(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(resp.Response) { + if !response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("checking for existing Sentinel Alert Rule MLBehaviorAnalytics %q: %+v", id, err) } } - id := alertRuleID(resp.Value) - if id != nil && *id != "" { - return tf.ImportAsExistsError("azurerm_sentinel_alert_rule_machine_learning_behavior_analytics", *id) + if !response.WasNotFound(resp.HttpResponse) { + return tf.ImportAsExistsError("azurerm_sentinel_alert_rule_machine_learning_behavior_analytics", id.ID()) } } - params := securityinsight.MLBehaviorAnalyticsAlertRule{ - Kind: securityinsight.KindBasicAlertRuleKindMLBehaviorAnalytics, - MLBehaviorAnalyticsAlertRuleProperties: &securityinsight.MLBehaviorAnalyticsAlertRuleProperties{ - AlertRuleTemplateName: utils.String(d.Get("alert_rule_template_guid").(string)), - Enabled: utils.Bool(d.Get("enabled").(bool)), + params := alertrules.MLBehaviorAnalyticsAlertRule{ + Properties: &alertrules.MLBehaviorAnalyticsAlertRuleProperties{ + AlertRuleTemplateName: d.Get("alert_rule_template_guid").(string), + Enabled: d.Get("enabled").(bool), }, } if !d.IsNewResource() { - resp, err := client.Get(ctx, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) + resp, err := client.AlertRulesGet(ctx, id) if err != nil { return fmt.Errorf("retrieving Sentinel Alert Rule MLBehaviorAnalytics %q: %+v", id, err) } - if err := assertAlertRuleKind(resp.Value, securityinsight.AlertRuleKindMLBehaviorAnalytics); err != nil { + if err := assertAlertRuleKind(resp.Model, alertrules.AlertRuleKindMLBehaviorAnalytics); err != nil { return fmt.Errorf("asserting alert rule of %q: %+v", id, err) } } - if _, err := client.CreateOrUpdate(ctx, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name, params); err != nil { + if _, err := client.AlertRulesCreateOrUpdate(ctx, id, params); err != nil { return fmt.Errorf("creating Sentinel Alert Rule MLBehaviorAnalytics %q: %+v", id, err) } @@ -126,14 +122,14 @@ func resourceSentinelAlertRuleMLBehaviorAnalyticsRead(d *pluginsdk.ResourceData, ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.AlertRuleID(d.Id()) + id, err := alertrules.ParseAlertRuleID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.WorkspaceName, id.Name) + resp, err := client.AlertRulesGet(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { log.Printf("[DEBUG] Sentinel Alert Rule MLBehaviorAnalytics %q was not found - removing from state!", id) d.SetId("") return nil @@ -142,19 +138,22 @@ func resourceSentinelAlertRuleMLBehaviorAnalyticsRead(d *pluginsdk.ResourceData, return fmt.Errorf("retrieving Sentinel Alert Rule MLBehaviorAnalytics %q: %+v", id, err) } - if err := assertAlertRuleKind(resp.Value, securityinsight.AlertRuleKindMLBehaviorAnalytics); err != nil { + if err := assertAlertRuleKind(resp.Model, alertrules.AlertRuleKindMLBehaviorAnalytics); err != nil { return fmt.Errorf("asserting alert rule of %q: %+v", id, err) } - rule := resp.Value.(securityinsight.MLBehaviorAnalyticsAlertRule) + if model := resp.Model; model != nil { + modelPtr := *model + rule := modelPtr.(alertrules.MLBehaviorAnalyticsAlertRule) - d.Set("name", id.Name) + d.Set("name", id.RuleId) - workspaceId := workspaces.NewWorkspaceID(id.SubscriptionId, id.ResourceGroup, id.WorkspaceName) - d.Set("log_analytics_workspace_id", workspaceId.ID()) + workspaceId := alertrules.NewWorkspaceID(id.SubscriptionId, id.ResourceGroupName, id.WorkspaceName) + d.Set("log_analytics_workspace_id", workspaceId.ID()) - if prop := rule.MLBehaviorAnalyticsAlertRuleProperties; prop != nil { - d.Set("enabled", prop.Enabled) - d.Set("alert_rule_template_guid", prop.AlertRuleTemplateName) + if prop := rule.Properties; prop != nil { + d.Set("enabled", prop.Enabled) + d.Set("alert_rule_template_guid", prop.AlertRuleTemplateName) + } } return nil @@ -165,12 +164,12 @@ func resourceSentinelAlertRuleMLBehaviorAnalyticsDelete(d *pluginsdk.ResourceDat ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.AlertRuleID(d.Id()) + id, err := alertrules.ParseAlertRuleID(d.Id()) if err != nil { return err } - if _, err := client.Delete(ctx, id.ResourceGroup, id.WorkspaceName, id.Name); err != nil { + if _, err := client.AlertRulesDelete(ctx, *id); err != nil { return fmt.Errorf("deleting Sentinel Alert Rule MLBehaviorAnalytics %q: %+v", id, err) } diff --git a/internal/services/sentinel/sentinel_alert_rule_machine_learning_behavior_analytics_test.go b/internal/services/sentinel/sentinel_alert_rule_machine_learning_behavior_analytics_test.go index d1a8e2002065..a4f233466d3a 100644 --- a/internal/services/sentinel/sentinel_alert_rule_machine_learning_behavior_analytics_test.go +++ b/internal/services/sentinel/sentinel_alert_rule_machine_learning_behavior_analytics_test.go @@ -5,13 +5,13 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/sentinel/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" - securityinsight "github.com/tombuildsstuff/kermit/sdk/securityinsights/2022-10-01-preview/securityinsights" ) type SentinelAlertRuleMLBehaviorAnalyticsResource struct{} @@ -92,26 +92,30 @@ func TestAccSentinelAlertRuleMLBehaviorAnalytics_requiresImport(t *testing.T) { func (r SentinelAlertRuleMLBehaviorAnalyticsResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { alertRuleClient := client.Sentinel.AlertRulesClient - id, err := parse.AlertRuleID(state.ID) + id, err := alertrules.ParseAlertRuleID(state.ID) if err != nil { return nil, err } - resp, err := alertRuleClient.Get(ctx, id.ResourceGroup, id.WorkspaceName, id.Name) + resp, err := alertRuleClient.AlertRulesGet(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return utils.Bool(false), nil } return nil, fmt.Errorf("retrieving Sentinel Alert Rule MLBehaviorAnalytics (%q): %+v", state.String(), err) } - rule, ok := resp.Value.(securityinsight.MLBehaviorAnalyticsAlertRule) - if !ok { - return nil, fmt.Errorf("the Alert Rule %q is not a MLBehaviorAnalytics Alert Rule", id) + if model := resp.Model; model != nil { + modelPtr := *model + rule, ok := modelPtr.(alertrules.MLBehaviorAnalyticsAlertRule) + if !ok { + return nil, fmt.Errorf("the Alert Rule %q is not a Fusion Alert Rule", id) + } + return utils.Bool(rule.Id != nil), nil } - return utils.Bool(rule.ID != nil), nil + return utils.Bool(false), nil } func (r SentinelAlertRuleMLBehaviorAnalyticsResource) basic(data acceptance.TestData) string { diff --git a/internal/services/sentinel/sentinel_alert_rule_ms_security_incident_resource.go b/internal/services/sentinel/sentinel_alert_rule_ms_security_incident_resource.go index 82f04d2e1744..cbc2df37dc16 100644 --- a/internal/services/sentinel/sentinel_alert_rule_ms_security_incident_resource.go +++ b/internal/services/sentinel/sentinel_alert_rule_ms_security_incident_resource.go @@ -5,15 +5,14 @@ import ( "log" "time" - "github.com/hashicorp/go-azure-sdk/resource-manager/operationalinsights/2020-08-01/workspaces" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/sentinel/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" - securityinsight "github.com/tombuildsstuff/kermit/sdk/securityinsights/2022-10-01-preview/securityinsights" ) func resourceSentinelAlertRuleMsSecurityIncident() *pluginsdk.Resource { @@ -24,9 +23,9 @@ func resourceSentinelAlertRuleMsSecurityIncident() *pluginsdk.Resource { Delete: resourceSentinelAlertRuleMsSecurityIncidentDelete, Importer: pluginsdk.ImporterValidatingResourceIdThen(func(id string) error { - _, err := parse.AlertRuleID(id) + _, err := alertrules.ParseAlertRuleID(id) return err - }, importSentinelAlertRule(securityinsight.AlertRuleKindMicrosoftSecurityIncidentCreation)), + }, importSentinelAlertRule(alertrules.AlertRuleKindMicrosoftSecurityIncidentCreation)), Timeouts: &pluginsdk.ResourceTimeout{ Create: pluginsdk.DefaultTimeout(30 * time.Minute), @@ -47,7 +46,7 @@ func resourceSentinelAlertRuleMsSecurityIncident() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ForceNew: true, - ValidateFunc: workspaces.ValidateWorkspaceID, + ValidateFunc: alertrules.ValidateWorkspaceID, }, "display_name": { @@ -60,13 +59,13 @@ func resourceSentinelAlertRuleMsSecurityIncident() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(securityinsight.MicrosoftSecurityProductNameMicrosoftCloudAppSecurity), - string(securityinsight.MicrosoftSecurityProductNameAzureSecurityCenter), - string(securityinsight.MicrosoftSecurityProductNameAzureActiveDirectoryIdentityProtection), - string(securityinsight.MicrosoftSecurityProductNameAzureSecurityCenterforIoT), - string(securityinsight.MicrosoftSecurityProductNameAzureAdvancedThreatProtection), - string(securityinsight.MicrosoftSecurityProductNameMicrosoftDefenderAdvancedThreatProtection), - string(securityinsight.MicrosoftSecurityProductNameOffice365AdvancedThreatProtection), + string(alertrules.MicrosoftSecurityProductNameMicrosoftCloudAppSecurity), + string(alertrules.MicrosoftSecurityProductNameAzureSecurityCenter), + string(alertrules.MicrosoftSecurityProductNameAzureActiveDirectoryIdentityProtection), + string(alertrules.MicrosoftSecurityProductNameAzureSecurityCenterForIoT), + string(alertrules.MicrosoftSecurityProductNameAzureAdvancedThreatProtection), + string(alertrules.MicrosoftSecurityProductNameMicrosoftDefenderAdvancedThreatProtection), + string(alertrules.MicrosoftSecurityProductNameOfficeThreeSixFiveAdvancedThreatProtection), }, false), }, @@ -77,10 +76,10 @@ func resourceSentinelAlertRuleMsSecurityIncident() *pluginsdk.Resource { Elem: &pluginsdk.Schema{ Type: pluginsdk.TypeString, ValidateFunc: validation.StringInSlice([]string{ - string(securityinsight.AlertSeverityHigh), - string(securityinsight.AlertSeverityMedium), - string(securityinsight.AlertSeverityLow), - string(securityinsight.AlertSeverityInformational), + string(alertrules.AlertSeverityHigh), + string(alertrules.AlertSeverityMedium), + string(alertrules.AlertSeverityLow), + string(alertrules.AlertSeverityInformational), }, false), }, }, @@ -134,61 +133,59 @@ func resourceSentinelAlertRuleMsSecurityIncidentCreateUpdate(d *pluginsdk.Resour defer cancel() name := d.Get("name").(string) - workspaceID, err := workspaces.ParseWorkspaceID(d.Get("log_analytics_workspace_id").(string)) + workspaceID, err := alertrules.ParseWorkspaceID(d.Get("log_analytics_workspace_id").(string)) if err != nil { return err } - id := parse.NewAlertRuleID(workspaceID.SubscriptionId, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) + id := alertrules.NewAlertRuleID(workspaceID.SubscriptionId, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) if d.IsNewResource() { - resp, err := client.Get(ctx, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) + resp, err := client.AlertRulesGet(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(resp.Response) { + if !response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("checking for existing Sentinel Alert Rule Ms Security Incident %q: %+v", id, err) } } - id := alertRuleID(resp.Value) - if id != nil && *id != "" { - return tf.ImportAsExistsError("azurerm_sentinel_alert_rule_ms_security_incident", *id) + if !response.WasNotFound(resp.HttpResponse) { + return tf.ImportAsExistsError("azurerm_sentinel_alert_rule_ms_security_incident", id.ID()) } } - param := securityinsight.MicrosoftSecurityIncidentCreationAlertRule{ - Kind: securityinsight.KindBasicAlertRuleKindMicrosoftSecurityIncidentCreation, - MicrosoftSecurityIncidentCreationAlertRuleProperties: &securityinsight.MicrosoftSecurityIncidentCreationAlertRuleProperties{ - ProductFilter: securityinsight.MicrosoftSecurityProductName(d.Get("product_filter").(string)), - DisplayName: utils.String(d.Get("display_name").(string)), + param := alertrules.MicrosoftSecurityIncidentCreationAlertRule{ + Properties: &alertrules.MicrosoftSecurityIncidentCreationAlertRuleProperties{ + ProductFilter: alertrules.MicrosoftSecurityProductName(d.Get("product_filter").(string)), + DisplayName: d.Get("display_name").(string), Description: utils.String(d.Get("description").(string)), - Enabled: utils.Bool(d.Get("enabled").(bool)), + Enabled: d.Get("enabled").(bool), SeveritiesFilter: expandAlertRuleMsSecurityIncidentSeverityFilter(d.Get("severity_filter").(*pluginsdk.Set).List()), }, } if v, ok := d.GetOk("alert_rule_template_guid"); ok { - param.MicrosoftSecurityIncidentCreationAlertRuleProperties.AlertRuleTemplateName = utils.String(v.(string)) + param.Properties.AlertRuleTemplateName = utils.String(v.(string)) } if dnf, ok := d.GetOk("display_name_filter"); ok { - param.DisplayNamesFilter = utils.ExpandStringSlice(dnf.(*pluginsdk.Set).List()) + param.Properties.DisplayNamesFilter = utils.ExpandStringSlice(dnf.(*pluginsdk.Set).List()) } if v, ok := d.GetOk("display_name_exclude_filter"); ok { - param.DisplayNamesExcludeFilter = utils.ExpandStringSlice(v.(*pluginsdk.Set).List()) + param.Properties.DisplayNamesExcludeFilter = utils.ExpandStringSlice(v.(*pluginsdk.Set).List()) } if !d.IsNewResource() { - resp, err := client.Get(ctx, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) + resp, err := client.AlertRulesGet(ctx, id) if err != nil { return fmt.Errorf("retrieving Sentinel Alert Rule Ms Security Incident %q: %+v", id, err) } - if err := assertAlertRuleKind(resp.Value, securityinsight.AlertRuleKindMicrosoftSecurityIncidentCreation); err != nil { + if err := assertAlertRuleKind(resp.Model, alertrules.AlertRuleKindMicrosoftSecurityIncidentCreation); err != nil { return fmt.Errorf("asserting alert rule of %q: %+v", id, err) } } - if _, err := client.CreateOrUpdate(ctx, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name, param); err != nil { + if _, err := client.AlertRulesCreateOrUpdate(ctx, id, param); err != nil { return fmt.Errorf("creating Sentinel Alert Rule Ms Security Incident %q: %+v", id, err) } @@ -202,14 +199,14 @@ func resourceSentinelAlertRuleMsSecurityIncidentRead(d *pluginsdk.ResourceData, ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.AlertRuleID(d.Id()) + id, err := alertrules.ParseAlertRuleID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.WorkspaceName, id.Name) + resp, err := client.AlertRulesGet(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { log.Printf("[DEBUG] Sentinel Alert Rule Ms Security Incident %q was not found - removing from state!", id) d.SetId("") return nil @@ -218,30 +215,34 @@ func resourceSentinelAlertRuleMsSecurityIncidentRead(d *pluginsdk.ResourceData, return fmt.Errorf("retrieving Sentinel Alert Rule Ms Security Incident %q: %+v", id, err) } - if err := assertAlertRuleKind(resp.Value, securityinsight.AlertRuleKindMicrosoftSecurityIncidentCreation); err != nil { - return fmt.Errorf("asserting alert rule of %q: %+v", id, err) - } - rule := resp.Value.(securityinsight.MicrosoftSecurityIncidentCreationAlertRule) + if model := resp.Model; model != nil { + if err = assertAlertRuleKind(resp.Model, alertrules.AlertRuleKindMicrosoftSecurityIncidentCreation); err != nil { + return fmt.Errorf("asserting alert rule of %q: %+v", id, err) + } - d.Set("name", id.Name) + modelPtr := *model + rule := modelPtr.(alertrules.MicrosoftSecurityIncidentCreationAlertRule) - workspaceId := workspaces.NewWorkspaceID(id.SubscriptionId, id.ResourceGroup, id.WorkspaceName) - d.Set("log_analytics_workspace_id", workspaceId.ID()) - if prop := rule.MicrosoftSecurityIncidentCreationAlertRuleProperties; prop != nil { - d.Set("product_filter", string(prop.ProductFilter)) - d.Set("display_name", prop.DisplayName) - d.Set("description", prop.Description) - d.Set("enabled", prop.Enabled) - d.Set("alert_rule_template_guid", prop.AlertRuleTemplateName) + d.Set("name", id.RuleId) - if err := d.Set("display_name_filter", utils.FlattenStringSlice(prop.DisplayNamesFilter)); err != nil { - return fmt.Errorf(`setting "display_name_filter": %+v`, err) - } - if err := d.Set("display_name_exclude_filter", utils.FlattenStringSlice(prop.DisplayNamesExcludeFilter)); err != nil { - return fmt.Errorf(`setting "display_name_exclude_filter": %+v`, err) - } - if err := d.Set("severity_filter", flattenAlertRuleMsSecurityIncidentSeverityFilter(prop.SeveritiesFilter)); err != nil { - return fmt.Errorf(`setting "severity_filter": %+v`, err) + workspaceId := alertrules.NewWorkspaceID(id.SubscriptionId, id.ResourceGroupName, id.WorkspaceName) + d.Set("log_analytics_workspace_id", workspaceId.ID()) + if prop := rule.Properties; prop != nil { + d.Set("product_filter", string(prop.ProductFilter)) + d.Set("display_name", prop.DisplayName) + d.Set("description", prop.Description) + d.Set("enabled", prop.Enabled) + d.Set("alert_rule_template_guid", prop.AlertRuleTemplateName) + + if err := d.Set("display_name_filter", utils.FlattenStringSlice(prop.DisplayNamesFilter)); err != nil { + return fmt.Errorf(`setting "display_name_filter": %+v`, err) + } + if err := d.Set("display_name_exclude_filter", utils.FlattenStringSlice(prop.DisplayNamesExcludeFilter)); err != nil { + return fmt.Errorf(`setting "display_name_exclude_filter": %+v`, err) + } + if err := d.Set("severity_filter", flattenAlertRuleMsSecurityIncidentSeverityFilter(prop.SeveritiesFilter)); err != nil { + return fmt.Errorf(`setting "severity_filter": %+v`, err) + } } } @@ -253,29 +254,29 @@ func resourceSentinelAlertRuleMsSecurityIncidentDelete(d *pluginsdk.ResourceData ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.AlertRuleID(d.Id()) + id, err := alertrules.ParseAlertRuleID(d.Id()) if err != nil { return err } - if _, err := client.Delete(ctx, id.ResourceGroup, id.WorkspaceName, id.Name); err != nil { + if _, err := client.AlertRulesDelete(ctx, *id); err != nil { return fmt.Errorf("deleting Sentinel Alert Rule Ms Security Incident %q: %+v", id, err) } return nil } -func expandAlertRuleMsSecurityIncidentSeverityFilter(input []interface{}) *[]securityinsight.AlertSeverity { - result := make([]securityinsight.AlertSeverity, 0) +func expandAlertRuleMsSecurityIncidentSeverityFilter(input []interface{}) *[]alertrules.AlertSeverity { + result := make([]alertrules.AlertSeverity, 0) for _, e := range input { - result = append(result, securityinsight.AlertSeverity(e.(string))) + result = append(result, alertrules.AlertSeverity(e.(string))) } return &result } -func flattenAlertRuleMsSecurityIncidentSeverityFilter(input *[]securityinsight.AlertSeverity) []interface{} { +func flattenAlertRuleMsSecurityIncidentSeverityFilter(input *[]alertrules.AlertSeverity) []interface{} { if input == nil { return []interface{}{} } diff --git a/internal/services/sentinel/sentinel_alert_rule_ms_security_incident_resource_test.go b/internal/services/sentinel/sentinel_alert_rule_ms_security_incident_resource_test.go index 1bc79855d2aa..0c2c1ddb7827 100644 --- a/internal/services/sentinel/sentinel_alert_rule_ms_security_incident_resource_test.go +++ b/internal/services/sentinel/sentinel_alert_rule_ms_security_incident_resource_test.go @@ -5,13 +5,12 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/sentinel/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" - securityinsight "github.com/tombuildsstuff/kermit/sdk/securityinsights/2022-10-01-preview/securityinsights" ) type SentinelAlertRuleMsSecurityIncidentResource struct{} @@ -135,22 +134,26 @@ func TestAccSentinelAlertRuleMsSecurityIncident_withDisplayNameExcludeFilter(t * } func (t SentinelAlertRuleMsSecurityIncidentResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.AlertRuleID(state.ID) + id, err := alertrules.ParseAlertRuleID(state.ID) if err != nil { return nil, err } - resp, err := clients.Sentinel.AlertRulesClient.Get(ctx, id.ResourceGroup, id.WorkspaceName, id.Name) + resp, err := clients.Sentinel.AlertRulesClient.AlertRulesGet(ctx, *id) if err != nil { return nil, fmt.Errorf("reading Sentinel Alert Rule Ms Security Incident %q: %v", id, err) } - rule, ok := resp.Value.(securityinsight.MicrosoftSecurityIncidentCreationAlertRule) - if !ok { - return nil, fmt.Errorf("the Alert Rule %q is not a MS Security Incident Alert Rule", id) + if model := resp.Model; model != nil { + modelPtr := *model + rule, ok := modelPtr.(alertrules.MicrosoftSecurityIncidentCreationAlertRule) + if !ok { + return nil, fmt.Errorf("the Alert Rule %q is not a Fusion Alert Rule", id) + } + return utils.Bool(rule.Id != nil), nil } - return utils.Bool(rule.ID != nil), nil + return utils.Bool(false), nil } func (r SentinelAlertRuleMsSecurityIncidentResource) basic(data acceptance.TestData) string { diff --git a/internal/services/sentinel/sentinel_alert_rule_nrt_resource.go b/internal/services/sentinel/sentinel_alert_rule_nrt_resource.go index 08c967ebdb05..79ff0d98680f 100644 --- a/internal/services/sentinel/sentinel_alert_rule_nrt_resource.go +++ b/internal/services/sentinel/sentinel_alert_rule_nrt_resource.go @@ -5,41 +5,20 @@ import ( "log" "time" - "github.com/hashicorp/go-azure-sdk/resource-manager/operationalinsights/2020-08-01/workspaces" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/helpers/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/features" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/sentinel/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" - securityinsight "github.com/tombuildsstuff/kermit/sdk/securityinsights/2022-10-01-preview/securityinsights" ) func resourceSentinelAlertRuleNrt() *pluginsdk.Resource { - var entityMappingTypes = []string{ - string(securityinsight.EntityMappingTypeAccount), - string(securityinsight.EntityMappingTypeAzureResource), - string(securityinsight.EntityMappingTypeCloudApplication), - string(securityinsight.EntityMappingTypeDNS), - string(securityinsight.EntityMappingTypeFile), - string(securityinsight.EntityMappingTypeFileHash), - string(securityinsight.EntityMappingTypeHost), - string(securityinsight.EntityMappingTypeIP), - string(securityinsight.EntityMappingTypeMailbox), - string(securityinsight.EntityMappingTypeMailCluster), - string(securityinsight.EntityMappingTypeMailMessage), - string(securityinsight.EntityMappingTypeMalware), - string(securityinsight.EntityMappingTypeProcess), - string(securityinsight.EntityMappingTypeRegistryKey), - string(securityinsight.EntityMappingTypeRegistryValue), - string(securityinsight.EntityMappingTypeSecurityGroup), - string(securityinsight.EntityMappingTypeSubmissionMail), - string(securityinsight.EntityMappingTypeURL), - } return &pluginsdk.Resource{ Create: resourceSentinelAlertRuleNrtCreateUpdate, Read: resourceSentinelAlertRuleNrtRead, @@ -47,9 +26,9 @@ func resourceSentinelAlertRuleNrt() *pluginsdk.Resource { Delete: resourceSentinelAlertRuleNrtDelete, Importer: pluginsdk.ImporterValidatingResourceIdThen(func(id string) error { - _, err := parse.AlertRuleID(id) + _, err := alertrules.ParseAlertRuleID(id) return err - }, importSentinelAlertRule(securityinsight.AlertRuleKindNRT)), + }, importSentinelAlertRule(alertrules.AlertRuleKindNRT)), Timeouts: &pluginsdk.ResourceTimeout{ Create: pluginsdk.DefaultTimeout(30 * time.Minute), @@ -70,7 +49,7 @@ func resourceSentinelAlertRuleNrt() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ForceNew: true, - ValidateFunc: workspaces.ValidateWorkspaceID, + ValidateFunc: alertrules.ValidateWorkspaceID, }, "display_name": { @@ -107,12 +86,9 @@ func resourceSentinelAlertRuleNrt() *pluginsdk.Resource { Elem: &pluginsdk.Resource{ Schema: map[string]*pluginsdk.Schema{ "aggregation_method": { - Type: pluginsdk.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice([]string{ - string(securityinsight.EventGroupingAggregationKindAlertPerResult), - string(securityinsight.EventGroupingAggregationKindSingleAlert), - }, false), + Type: pluginsdk.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(alertrules.PossibleValuesForEventGroupingAggregationKind(), false), }, }, }, @@ -122,22 +98,8 @@ func resourceSentinelAlertRuleNrt() *pluginsdk.Resource { Type: pluginsdk.TypeSet, Optional: true, Elem: &pluginsdk.Schema{ - Type: pluginsdk.TypeString, - ValidateFunc: validation.StringInSlice([]string{ - string(securityinsight.AttackTacticCollection), - string(securityinsight.AttackTacticCommandAndControl), - string(securityinsight.AttackTacticCredentialAccess), - string(securityinsight.AttackTacticDefenseEvasion), - string(securityinsight.AttackTacticDiscovery), - string(securityinsight.AttackTacticExecution), - string(securityinsight.AttackTacticExfiltration), - string(securityinsight.AttackTacticImpact), - string(securityinsight.AttackTacticInitialAccess), - string(securityinsight.AttackTacticLateralMovement), - string(securityinsight.AttackTacticPersistence), - string(securityinsight.AttackTacticPrivilegeEscalation), - string(securityinsight.AttackTacticPreAttack), - }, false), + Type: pluginsdk.TypeString, + ValidateFunc: validation.StringInSlice(alertrules.PossibleValuesForAttackTactic(), false), }, }, @@ -186,33 +148,25 @@ func resourceSentinelAlertRuleNrt() *pluginsdk.Resource { Default: false, }, "entity_matching_method": { - Type: pluginsdk.TypeString, - Optional: true, - Default: securityinsight.MatchingMethodAnyAlert, - ValidateFunc: validation.StringInSlice([]string{ - string(securityinsight.MatchingMethodAnyAlert), - string(securityinsight.MatchingMethodSelected), - string(securityinsight.MatchingMethodAllEntities), - }, false), + Type: pluginsdk.TypeString, + Optional: true, + Default: alertrules.MatchingMethodAnyAlert, + ValidateFunc: validation.StringInSlice(alertrules.PossibleValuesForMatchingMethod(), false), }, "by_entities": { Type: pluginsdk.TypeList, Optional: true, Elem: &pluginsdk.Schema{ Type: pluginsdk.TypeString, - ValidateFunc: validation.StringInSlice(entityMappingTypes, false), + ValidateFunc: validation.StringInSlice(alertrules.PossibleValuesForEntityMappingType(), false), }, }, "by_alert_details": { Type: pluginsdk.TypeList, Optional: true, Elem: &pluginsdk.Schema{ - Type: pluginsdk.TypeString, - ValidateFunc: validation.StringInSlice([]string{ - string(securityinsight.AlertDetailDisplayName), - string(securityinsight.AlertDetailSeverity), - }, - false), + Type: pluginsdk.TypeString, + ValidateFunc: validation.StringInSlice(alertrules.PossibleValuesForAlertDetail(), false), }, }, "by_custom_details": { @@ -231,14 +185,9 @@ func resourceSentinelAlertRuleNrt() *pluginsdk.Resource { }, "severity": { - Type: pluginsdk.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice([]string{ - string(securityinsight.AlertSeverityHigh), - string(securityinsight.AlertSeverityMedium), - string(securityinsight.AlertSeverityLow), - string(securityinsight.AlertSeverityInformational), - }, false), + Type: pluginsdk.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(alertrules.PossibleValuesForAlertSeverity(), false), }, "enabled": { @@ -295,20 +244,9 @@ func resourceSentinelAlertRuleNrt() *pluginsdk.Resource { Elem: &pluginsdk.Resource{ Schema: map[string]*schema.Schema{ "name": { - Type: pluginsdk.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice( - []string{ - string(securityinsight.AlertPropertyAlertLink), - string(securityinsight.AlertPropertyConfidenceLevel), - string(securityinsight.AlertPropertyConfidenceScore), - string(securityinsight.AlertPropertyExtendedLinks), - string(securityinsight.AlertPropertyProductComponentName), - string(securityinsight.AlertPropertyProductName), - string(securityinsight.AlertPropertyProviderName), - string(securityinsight.AlertPropertyRemediationSteps), - string(securityinsight.AlertPropertyTechniques), - }, false), + Type: pluginsdk.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(alertrules.PossibleValuesForAlertProperty(), false), }, "value": { Type: pluginsdk.TypeString, @@ -338,7 +276,7 @@ func resourceSentinelAlertRuleNrt() *pluginsdk.Resource { "entity_type": { Type: pluginsdk.TypeString, Required: true, - ValidateFunc: validation.StringInSlice(entityMappingTypes, false), + ValidateFunc: validation.StringInSlice(alertrules.PossibleValuesForEntityMappingType(), false), }, "field_mapping": { Type: pluginsdk.TypeList, @@ -386,71 +324,65 @@ func resourceSentinelAlertRuleNrtCreateUpdate(d *pluginsdk.ResourceData, meta in defer cancel() name := d.Get("name").(string) - workspaceID, err := workspaces.ParseWorkspaceID(d.Get("log_analytics_workspace_id").(string)) + workspaceID, err := alertrules.ParseWorkspaceID(d.Get("log_analytics_workspace_id").(string)) if err != nil { return err } - id := parse.NewAlertRuleID(workspaceID.SubscriptionId, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) + id := alertrules.NewAlertRuleID(workspaceID.SubscriptionId, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) if d.IsNewResource() { - resp, err := client.Get(ctx, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) + resp, err := client.AlertRulesGet(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(resp.Response) { + if !response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("checking for existing %q: %+v", id, err) } } - id := alertRuleID(resp.Value) - if id != nil && *id != "" { - return tf.ImportAsExistsError("azurerm_sentinel_alert_rule_nrt", *id) + if !response.WasNotFound(resp.HttpResponse) { + return tf.ImportAsExistsError("azurerm_sentinel_alert_rule_nrt", id.ID()) } } - // query frequency must <= suppression duration: otherwise suppression has no effect. - suppressionDuration := d.Get("suppression_duration").(string) - suppressionEnabled := d.Get("suppression_enabled").(bool) - - param := securityinsight.NrtAlertRule{ - Kind: securityinsight.KindBasicAlertRuleKindNRT, - NrtAlertRuleProperties: &securityinsight.NrtAlertRuleProperties{ + param := alertrules.NrtAlertRule{ + Properties: &alertrules.NrtAlertRuleProperties{ Description: utils.String(d.Get("description").(string)), - DisplayName: utils.String(d.Get("display_name").(string)), + DisplayName: d.Get("display_name").(string), Techniques: expandAlertRuleTechnicals(d.Get("techniques").(*pluginsdk.Set).List()), Tactics: expandAlertRuleTactics(d.Get("tactics").(*pluginsdk.Set).List()), IncidentConfiguration: expandAlertRuleIncidentConfiguration(d.Get("incident").([]interface{}), "create_incident_enabled", false), - Severity: securityinsight.AlertSeverity(d.Get("severity").(string)), - Enabled: utils.Bool(d.Get("enabled").(bool)), - Query: utils.String(d.Get("query").(string)), - SuppressionEnabled: &suppressionEnabled, - SuppressionDuration: &suppressionDuration, + Severity: alertrules.AlertSeverity(d.Get("severity").(string)), + Enabled: d.Get("enabled").(bool), + Query: d.Get("query").(string), + SuppressionEnabled: d.Get("suppression_enabled").(bool), + SuppressionDuration: d.Get("suppression_duration").(string), }, } if v, ok := d.GetOk("alert_rule_template_guid"); ok { - param.NrtAlertRuleProperties.AlertRuleTemplateName = utils.String(v.(string)) + param.Properties.AlertRuleTemplateName = utils.String(v.(string)) } if v, ok := d.GetOk("alert_rule_template_version"); ok { - param.NrtAlertRuleProperties.TemplateVersion = utils.String(v.(string)) + param.Properties.TemplateVersion = utils.String(v.(string)) } if v, ok := d.GetOk("event_grouping"); ok { - param.NrtAlertRuleProperties.EventGroupingSettings = expandAlertRuleScheduledEventGroupingSetting(v.([]interface{})) + param.Properties.EventGroupingSettings = expandAlertRuleScheduledEventGroupingSetting(v.([]interface{})) } if v, ok := d.GetOk("alert_details_override"); ok { - param.NrtAlertRuleProperties.AlertDetailsOverride = expandAlertRuleAlertDetailsOverride(v.([]interface{})) + param.Properties.AlertDetailsOverride = expandAlertRuleAlertDetailsOverride(v.([]interface{})) } if v, ok := d.GetOk("custom_details"); ok { - param.NrtAlertRuleProperties.CustomDetails = utils.ExpandMapStringPtrString(v.(map[string]interface{})) + param.Properties.CustomDetails = utils.ExpandPtrMapStringString(v.(map[string]interface{})) } entityMappingCount := 0 sentinelEntityMappingCount := 0 if v, ok := d.GetOk("entity_mapping"); ok { - param.NrtAlertRuleProperties.EntityMappings = expandAlertRuleEntityMapping(v.([]interface{})) - entityMappingCount = len(*param.NrtAlertRuleProperties.EntityMappings) + param.Properties.EntityMappings = expandAlertRuleEntityMapping(v.([]interface{})) + entityMappingCount = len(*param.Properties.EntityMappings) } if v, ok := d.GetOk("sentinel_entity_mapping"); ok { - param.NrtAlertRuleProperties.SentinelEntitiesMappings = expandAlertRuleSentinelEntityMapping(v.([]interface{})) - sentinelEntityMappingCount = len(*param.NrtAlertRuleProperties.SentinelEntitiesMappings) + param.Properties.SentinelEntitiesMappings = expandAlertRuleSentinelEntityMapping(v.([]interface{})) + sentinelEntityMappingCount = len(*param.Properties.SentinelEntitiesMappings) } // the max number of `sentinel_entity_mapping` and `entity_mapping` together is 5 @@ -460,18 +392,21 @@ func resourceSentinelAlertRuleNrtCreateUpdate(d *pluginsdk.ResourceData, meta in // Service avoid concurrent update of this resource via checking the "etag" to guarantee it is the same value as last Read. if !d.IsNewResource() { - resp, err := client.Get(ctx, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) + resp, err := client.AlertRulesGet(ctx, id) if err != nil { return fmt.Errorf("retrieving %q: %+v", id, err) } - if err := assertAlertRuleKind(resp.Value, securityinsight.AlertRuleKindNRT); err != nil { + if err := assertAlertRuleKind(resp.Model, alertrules.AlertRuleKindNRT); err != nil { return fmt.Errorf("asserting %q: %+v", id, err) } - param.Etag = resp.Value.(securityinsight.NrtAlertRule).Etag + if model := resp.Model; model != nil { + modelPtr := *model + param.Etag = modelPtr.(alertrules.NrtAlertRule).Etag + } } - if _, err := client.CreateOrUpdate(ctx, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name, param); err != nil { + if _, err := client.AlertRulesCreateOrUpdate(ctx, id, param); err != nil { return fmt.Errorf("creating %q: %+v", id, err) } @@ -485,14 +420,14 @@ func resourceSentinelAlertRuleNrtRead(d *pluginsdk.ResourceData, meta interface{ ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.AlertRuleID(d.Id()) + id, err := alertrules.ParseAlertRuleID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.WorkspaceName, id.Name) + resp, err := client.AlertRulesGet(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { log.Printf("[DEBUG] %q was not found - removing from state!", id) d.SetId("") return nil @@ -501,51 +436,55 @@ func resourceSentinelAlertRuleNrtRead(d *pluginsdk.ResourceData, meta interface{ return fmt.Errorf("retrieving %q: %+v", id, err) } - if err := assertAlertRuleKind(resp.Value, securityinsight.AlertRuleKindNRT); err != nil { + if err := assertAlertRuleKind(resp.Model, alertrules.AlertRuleKindNRT); err != nil { return fmt.Errorf("asserting %q: %+v", id, err) } - rule := resp.Value.(securityinsight.NrtAlertRule) - d.Set("name", id.Name) + if model := resp.Model; model != nil { + modelPtr := *model + rule := modelPtr.(alertrules.NrtAlertRule) - workspaceId := workspaces.NewWorkspaceID(id.SubscriptionId, id.ResourceGroup, id.WorkspaceName) - d.Set("log_analytics_workspace_id", workspaceId.ID()) + d.Set("name", id.RuleId) - if prop := rule.NrtAlertRuleProperties; prop != nil { - d.Set("description", prop.Description) - d.Set("display_name", prop.DisplayName) - if err := d.Set("tactics", flattenAlertRuleTactics(prop.Tactics)); err != nil { - return fmt.Errorf("setting `tactics`: %+v", err) - } - if err := d.Set("techniques", prop.Techniques); err != nil { - return fmt.Errorf("setting `techniques`: %+v", err) - } - if err := d.Set("incident", flattenAlertRuleIncidentConfiguration(prop.IncidentConfiguration, "create_incident_enabled", false)); err != nil { - return fmt.Errorf("setting `incident`: %+v", err) - } - d.Set("severity", string(prop.Severity)) - d.Set("enabled", prop.Enabled) - d.Set("query", prop.Query) + workspaceId := alertrules.NewWorkspaceID(id.SubscriptionId, id.ResourceGroupName, id.WorkspaceName) + d.Set("log_analytics_workspace_id", workspaceId.ID()) - d.Set("suppression_enabled", prop.SuppressionEnabled) - d.Set("suppression_duration", prop.SuppressionDuration) - d.Set("alert_rule_template_guid", prop.AlertRuleTemplateName) - d.Set("alert_rule_template_version", prop.TemplateVersion) + if prop := rule.Properties; prop != nil { + d.Set("description", prop.Description) + d.Set("display_name", prop.DisplayName) + if err := d.Set("tactics", flattenAlertRuleTactics(prop.Tactics)); err != nil { + return fmt.Errorf("setting `tactics`: %+v", err) + } + if err := d.Set("techniques", prop.Techniques); err != nil { + return fmt.Errorf("setting `techniques`: %+v", err) + } + if err := d.Set("incident", flattenAlertRuleIncidentConfiguration(prop.IncidentConfiguration, "create_incident_enabled", false)); err != nil { + return fmt.Errorf("setting `incident`: %+v", err) + } + d.Set("severity", string(prop.Severity)) + d.Set("enabled", prop.Enabled) + d.Set("query", prop.Query) - if err := d.Set("event_grouping", flattenAlertRuleScheduledEventGroupingSetting(prop.EventGroupingSettings)); err != nil { - return fmt.Errorf("setting `event_grouping`: %+v", err) - } - if err := d.Set("alert_details_override", flattenAlertRuleAlertDetailsOverride(prop.AlertDetailsOverride)); err != nil { - return fmt.Errorf("setting `alert_details_override`: %+v", err) - } - if err := d.Set("custom_details", utils.FlattenMapStringPtrString(prop.CustomDetails)); err != nil { - return fmt.Errorf("setting `custom_details`: %+v", err) - } - if err := d.Set("entity_mapping", flattenAlertRuleEntityMapping(prop.EntityMappings)); err != nil { - return fmt.Errorf("setting `entity_mapping`: %+v", err) - } - if err := d.Set("sentinel_entity_mapping", flattenAlertRuleSentinelEntityMapping(prop.SentinelEntitiesMappings)); err != nil { - return fmt.Errorf("setting `sentinel_entity_mapping`: %+v", err) + d.Set("suppression_enabled", prop.SuppressionEnabled) + d.Set("suppression_duration", prop.SuppressionDuration) + d.Set("alert_rule_template_guid", prop.AlertRuleTemplateName) + d.Set("alert_rule_template_version", prop.TemplateVersion) + + if err := d.Set("event_grouping", flattenAlertRuleScheduledEventGroupingSetting(prop.EventGroupingSettings)); err != nil { + return fmt.Errorf("setting `event_grouping`: %+v", err) + } + if err := d.Set("alert_details_override", flattenAlertRuleAlertDetailsOverride(prop.AlertDetailsOverride)); err != nil { + return fmt.Errorf("setting `alert_details_override`: %+v", err) + } + if err := d.Set("custom_details", utils.FlattenPtrMapStringString(prop.CustomDetails)); err != nil { + return fmt.Errorf("setting `custom_details`: %+v", err) + } + if err := d.Set("entity_mapping", flattenAlertRuleEntityMapping(prop.EntityMappings)); err != nil { + return fmt.Errorf("setting `entity_mapping`: %+v", err) + } + if err := d.Set("sentinel_entity_mapping", flattenAlertRuleSentinelEntityMapping(prop.SentinelEntitiesMappings)); err != nil { + return fmt.Errorf("setting `sentinel_entity_mapping`: %+v", err) + } } } @@ -557,12 +496,12 @@ func resourceSentinelAlertRuleNrtDelete(d *pluginsdk.ResourceData, meta interfac ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.AlertRuleID(d.Id()) + id, err := alertrules.ParseAlertRuleID(d.Id()) if err != nil { return err } - if _, err := client.Delete(ctx, id.ResourceGroup, id.WorkspaceName, id.Name); err != nil { + if _, err := client.AlertRulesDelete(ctx, *id); err != nil { return fmt.Errorf("deleting Sentinel Alert Rule Nrt %q: %+v", id, err) } diff --git a/internal/services/sentinel/sentinel_alert_rule_nrt_resource_test.go b/internal/services/sentinel/sentinel_alert_rule_nrt_resource_test.go index 69da6252acae..abf72e132961 100644 --- a/internal/services/sentinel/sentinel_alert_rule_nrt_resource_test.go +++ b/internal/services/sentinel/sentinel_alert_rule_nrt_resource_test.go @@ -5,13 +5,12 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/sentinel/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" - securityinsight "github.com/tombuildsstuff/kermit/sdk/securityinsights/2022-10-01-preview/securityinsights" ) type SentinelAlertRuleNrtResource struct{} @@ -128,22 +127,26 @@ func TestAccSentinelAlertRuleNrt_updateEventGroupingSetting(t *testing.T) { } func (t SentinelAlertRuleNrtResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.AlertRuleID(state.ID) + id, err := alertrules.ParseAlertRuleID(state.ID) if err != nil { return nil, err } - resp, err := clients.Sentinel.AlertRulesClient.Get(ctx, id.ResourceGroup, id.WorkspaceName, id.Name) + resp, err := clients.Sentinel.AlertRulesClient.AlertRulesGet(ctx, *id) if err != nil { return nil, fmt.Errorf("reading %q: %v", id, err) } - rule, ok := resp.Value.(securityinsight.NrtAlertRule) - if !ok { - return nil, fmt.Errorf("the Alert Rule %q is not a NRT Alert Rule", id) + if model := resp.Model; model != nil { + modelPtr := *model + rule, ok := modelPtr.(alertrules.NrtAlertRule) + if !ok { + return nil, fmt.Errorf("the Alert Rule %q is not a Fusion Alert Rule", id) + } + return utils.Bool(rule.Id != nil), nil } - return utils.Bool(rule.ID != nil), nil + return utils.Bool(false), nil } func (r SentinelAlertRuleNrtResource) basic(data acceptance.TestData) string { diff --git a/internal/services/sentinel/sentinel_alert_rule_scheduled_resource.go b/internal/services/sentinel/sentinel_alert_rule_scheduled_resource.go index b7630fcd8890..0449ac939ee8 100644 --- a/internal/services/sentinel/sentinel_alert_rule_scheduled_resource.go +++ b/internal/services/sentinel/sentinel_alert_rule_scheduled_resource.go @@ -5,41 +5,21 @@ import ( "log" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-sdk/resource-manager/operationalinsights/2020-08-01/workspaces" + "github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/helpers/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/sentinel/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" "github.com/rickb777/date/period" - securityinsight "github.com/tombuildsstuff/kermit/sdk/securityinsights/2022-10-01-preview/securityinsights" ) func resourceSentinelAlertRuleScheduled() *pluginsdk.Resource { - var entityMappingTypes = []string{ - string(securityinsight.EntityMappingTypeAccount), - string(securityinsight.EntityMappingTypeAzureResource), - string(securityinsight.EntityMappingTypeCloudApplication), - string(securityinsight.EntityMappingTypeDNS), - string(securityinsight.EntityMappingTypeFile), - string(securityinsight.EntityMappingTypeFileHash), - string(securityinsight.EntityMappingTypeHost), - string(securityinsight.EntityMappingTypeIP), - string(securityinsight.EntityMappingTypeMailbox), - string(securityinsight.EntityMappingTypeMailCluster), - string(securityinsight.EntityMappingTypeMailMessage), - string(securityinsight.EntityMappingTypeMalware), - string(securityinsight.EntityMappingTypeProcess), - string(securityinsight.EntityMappingTypeRegistryKey), - string(securityinsight.EntityMappingTypeRegistryValue), - string(securityinsight.EntityMappingTypeSecurityGroup), - string(securityinsight.EntityMappingTypeSubmissionMail), - string(securityinsight.EntityMappingTypeURL), - } return &pluginsdk.Resource{ Create: resourceSentinelAlertRuleScheduledCreateUpdate, Read: resourceSentinelAlertRuleScheduledRead, @@ -47,9 +27,9 @@ func resourceSentinelAlertRuleScheduled() *pluginsdk.Resource { Delete: resourceSentinelAlertRuleScheduledDelete, Importer: pluginsdk.ImporterValidatingResourceIdThen(func(id string) error { - _, err := parse.AlertRuleID(id) + _, err := alertrules.ParseAlertRuleID(id) return err - }, importSentinelAlertRule(securityinsight.AlertRuleKindScheduled)), + }, importSentinelAlertRule(alertrules.AlertRuleKindScheduled)), Timeouts: &pluginsdk.ResourceTimeout{ Create: pluginsdk.DefaultTimeout(30 * time.Minute), @@ -105,12 +85,9 @@ func resourceSentinelAlertRuleScheduled() *pluginsdk.Resource { Elem: &pluginsdk.Resource{ Schema: map[string]*pluginsdk.Schema{ "aggregation_method": { - Type: pluginsdk.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice([]string{ - string(securityinsight.EventGroupingAggregationKindAlertPerResult), - string(securityinsight.EventGroupingAggregationKindSingleAlert), - }, false), + Type: pluginsdk.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(alertrules.PossibleValuesForEventGroupingAggregationKind(), false), }, }, }, @@ -120,26 +97,8 @@ func resourceSentinelAlertRuleScheduled() *pluginsdk.Resource { Type: pluginsdk.TypeSet, Optional: true, Elem: &pluginsdk.Schema{ - Type: pluginsdk.TypeString, - ValidateFunc: validation.StringInSlice([]string{ - string(securityinsight.AttackTacticCollection), - string(securityinsight.AttackTacticCommandAndControl), - string(securityinsight.AttackTacticCredentialAccess), - string(securityinsight.AttackTacticDefenseEvasion), - string(securityinsight.AttackTacticDiscovery), - string(securityinsight.AttackTacticExecution), - string(securityinsight.AttackTacticExfiltration), - string(securityinsight.AttackTacticImpairProcessControl), - string(securityinsight.AttackTacticInhibitResponseFunction), - string(securityinsight.AttackTacticImpact), - string(securityinsight.AttackTacticInitialAccess), - string(securityinsight.AttackTacticLateralMovement), - string(securityinsight.AttackTacticPersistence), - string(securityinsight.AttackTacticPrivilegeEscalation), - string(securityinsight.AttackTacticPreAttack), - string(securityinsight.AttackTacticReconnaissance), - string(securityinsight.AttackTacticResourceDevelopment), - }, false), + Type: pluginsdk.TypeString, + ValidateFunc: validation.StringInSlice(alertrules.PossibleValuesForAttackTactic(), false), }, }, @@ -190,14 +149,10 @@ func resourceSentinelAlertRuleScheduled() *pluginsdk.Resource { Default: false, }, "entity_matching_method": { - Type: pluginsdk.TypeString, - Optional: true, - Default: securityinsight.MatchingMethodAnyAlert, - ValidateFunc: validation.StringInSlice([]string{ - string(securityinsight.MatchingMethodAnyAlert), - string(securityinsight.MatchingMethodSelected), - string(securityinsight.MatchingMethodAllEntities), - }, false), + Type: pluginsdk.TypeString, + Optional: true, + Default: alertrules.MatchingMethodAnyAlert, + ValidateFunc: validation.StringInSlice(alertrules.PossibleValuesForMatchingMethod(), false), }, // TODO 4.0 - rename this to "by_entities" "group_by_entities": { @@ -205,7 +160,7 @@ func resourceSentinelAlertRuleScheduled() *pluginsdk.Resource { Optional: true, Elem: &pluginsdk.Schema{ Type: pluginsdk.TypeString, - ValidateFunc: validation.StringInSlice(entityMappingTypes, false), + ValidateFunc: validation.StringInSlice(alertrules.PossibleValuesForEntityMappingType(), false), }, }, // TODO 4.0 - rename this to "by_alert_details" @@ -213,12 +168,8 @@ func resourceSentinelAlertRuleScheduled() *pluginsdk.Resource { Type: pluginsdk.TypeList, Optional: true, Elem: &pluginsdk.Schema{ - Type: pluginsdk.TypeString, - ValidateFunc: validation.StringInSlice([]string{ - string(securityinsight.AlertDetailDisplayName), - string(securityinsight.AlertDetailSeverity), - }, - false), + Type: pluginsdk.TypeString, + ValidateFunc: validation.StringInSlice(alertrules.PossibleValuesForAlertDetail(), false), }, }, // TODO 4.0 - rename this to "by_custom_details" @@ -238,14 +189,9 @@ func resourceSentinelAlertRuleScheduled() *pluginsdk.Resource { }, "severity": { - Type: pluginsdk.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice([]string{ - string(securityinsight.AlertSeverityHigh), - string(securityinsight.AlertSeverityMedium), - string(securityinsight.AlertSeverityLow), - string(securityinsight.AlertSeverityInformational), - }, false), + Type: pluginsdk.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(alertrules.PossibleValuesForAlertSeverity(), false), }, "enabled": { @@ -275,15 +221,10 @@ func resourceSentinelAlertRuleScheduled() *pluginsdk.Resource { }, "trigger_operator": { - Type: pluginsdk.TypeString, - Optional: true, - Default: string(securityinsight.TriggerOperatorGreaterThan), - ValidateFunc: validation.StringInSlice([]string{ - string(securityinsight.TriggerOperatorGreaterThan), - string(securityinsight.TriggerOperatorLessThan), - string(securityinsight.TriggerOperatorEqual), - string(securityinsight.TriggerOperatorNotEqual), - }, false), + Type: pluginsdk.TypeString, + Optional: true, + Default: string(alertrules.TriggerOperatorGreaterThan), + ValidateFunc: validation.StringInSlice(alertrules.PossibleValuesForTriggerOperator(), false), }, "trigger_threshold": { @@ -335,20 +276,9 @@ func resourceSentinelAlertRuleScheduled() *pluginsdk.Resource { Elem: &pluginsdk.Resource{ Schema: map[string]*schema.Schema{ "name": { - Type: pluginsdk.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice( - []string{ - string(securityinsight.AlertPropertyAlertLink), - string(securityinsight.AlertPropertyConfidenceLevel), - string(securityinsight.AlertPropertyConfidenceScore), - string(securityinsight.AlertPropertyExtendedLinks), - string(securityinsight.AlertPropertyProductComponentName), - string(securityinsight.AlertPropertyProductName), - string(securityinsight.AlertPropertyProviderName), - string(securityinsight.AlertPropertyRemediationSteps), - string(securityinsight.AlertPropertyTechniques), - }, false), + Type: pluginsdk.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(alertrules.PossibleValuesForAlertProperty(), false), }, "value": { Type: pluginsdk.TypeString, @@ -378,7 +308,7 @@ func resourceSentinelAlertRuleScheduled() *pluginsdk.Resource { "entity_type": { Type: pluginsdk.TypeString, Required: true, - ValidateFunc: validation.StringInSlice(entityMappingTypes, false), + ValidateFunc: validation.StringInSlice(alertrules.PossibleValuesForEntityMappingType(), false), }, "field_mapping": { Type: pluginsdk.TypeList, @@ -426,23 +356,22 @@ func resourceSentinelAlertRuleScheduledCreateUpdate(d *pluginsdk.ResourceData, m defer cancel() name := d.Get("name").(string) - workspaceID, err := workspaces.ParseWorkspaceID(d.Get("log_analytics_workspace_id").(string)) + workspaceID, err := alertrules.ParseWorkspaceID(d.Get("log_analytics_workspace_id").(string)) if err != nil { return err } - id := parse.NewAlertRuleID(workspaceID.SubscriptionId, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) + id := alertrules.NewAlertRuleID(workspaceID.SubscriptionId, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) if d.IsNewResource() { - resp, err := client.Get(ctx, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) + resp, err := client.AlertRulesGet(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(resp.Response) { + if !response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("checking for existing Sentinel Alert Rule Scheduled %q: %+v", id, err) } } - id := alertRuleID(resp.Value) - if id != nil && *id != "" { - return tf.ImportAsExistsError("azurerm_sentinel_alert_rule_scheduled", *id) + if !response.WasNotFound(resp.HttpResponse) { + return tf.ImportAsExistsError("azurerm_sentinel_alert_rule_scheduled", id.ID()) } } @@ -468,51 +397,50 @@ func resourceSentinelAlertRuleScheduledCreateUpdate(d *pluginsdk.ResourceData, m } } - param := securityinsight.ScheduledAlertRule{ - Kind: securityinsight.KindBasicAlertRuleKindScheduled, - ScheduledAlertRuleProperties: &securityinsight.ScheduledAlertRuleProperties{ + param := alertrules.ScheduledAlertRule{ + Properties: &alertrules.ScheduledAlertRuleProperties{ Description: utils.String(d.Get("description").(string)), - DisplayName: utils.String(d.Get("display_name").(string)), + DisplayName: d.Get("display_name").(string), Tactics: expandAlertRuleTactics(d.Get("tactics").(*pluginsdk.Set).List()), Techniques: expandAlertRuleTechnicals(d.Get("techniques").(*pluginsdk.Set).List()), IncidentConfiguration: expandAlertRuleIncidentConfiguration(d.Get("incident_configuration").([]interface{}), "create_incident", true), - Severity: securityinsight.AlertSeverity(d.Get("severity").(string)), - Enabled: utils.Bool(d.Get("enabled").(bool)), - Query: utils.String(d.Get("query").(string)), - QueryFrequency: &queryFreq, - QueryPeriod: &queryPeriod, - SuppressionEnabled: &suppressionEnabled, - SuppressionDuration: &suppressionDuration, - TriggerOperator: securityinsight.TriggerOperator(d.Get("trigger_operator").(string)), - TriggerThreshold: utils.Int32(int32(d.Get("trigger_threshold").(int))), + Severity: alertrules.AlertSeverity(d.Get("severity").(string)), + Enabled: d.Get("enabled").(bool), + Query: d.Get("query").(string), + QueryFrequency: queryFreq, + QueryPeriod: queryPeriod, + SuppressionEnabled: suppressionEnabled, + SuppressionDuration: suppressionDuration, + TriggerOperator: alertrules.TriggerOperator(d.Get("trigger_operator").(string)), + TriggerThreshold: int64(d.Get("trigger_threshold").(int)), }, } if v, ok := d.GetOk("alert_rule_template_guid"); ok { - param.ScheduledAlertRuleProperties.AlertRuleTemplateName = utils.String(v.(string)) + param.Properties.AlertRuleTemplateName = utils.String(v.(string)) } if v, ok := d.GetOk("alert_rule_template_version"); ok { - param.ScheduledAlertRuleProperties.TemplateVersion = utils.String(v.(string)) + param.Properties.TemplateVersion = utils.String(v.(string)) } if v, ok := d.GetOk("event_grouping"); ok { - param.ScheduledAlertRuleProperties.EventGroupingSettings = expandAlertRuleScheduledEventGroupingSetting(v.([]interface{})) + param.Properties.EventGroupingSettings = expandAlertRuleScheduledEventGroupingSetting(v.([]interface{})) } if v, ok := d.GetOk("alert_details_override"); ok { - param.ScheduledAlertRuleProperties.AlertDetailsOverride = expandAlertRuleAlertDetailsOverride(v.([]interface{})) + param.Properties.AlertDetailsOverride = expandAlertRuleAlertDetailsOverride(v.([]interface{})) } if v, ok := d.GetOk("custom_details"); ok { - param.ScheduledAlertRuleProperties.CustomDetails = utils.ExpandMapStringPtrString(v.(map[string]interface{})) + param.Properties.CustomDetails = utils.ExpandPtrMapStringString(v.(map[string]interface{})) } entityMappingCount := 0 sentinelEntityMappingCount := 0 if v, ok := d.GetOk("entity_mapping"); ok { - param.ScheduledAlertRuleProperties.EntityMappings = expandAlertRuleEntityMapping(v.([]interface{})) - entityMappingCount = len(*param.ScheduledAlertRuleProperties.EntityMappings) + param.Properties.EntityMappings = expandAlertRuleEntityMapping(v.([]interface{})) + entityMappingCount = len(*param.Properties.EntityMappings) } if v, ok := d.GetOk("sentinel_entity_mapping"); ok { - param.ScheduledAlertRuleProperties.SentinelEntitiesMappings = expandAlertRuleSentinelEntityMapping(v.([]interface{})) - sentinelEntityMappingCount = len(*param.ScheduledAlertRuleProperties.SentinelEntitiesMappings) + param.Properties.SentinelEntitiesMappings = expandAlertRuleSentinelEntityMapping(v.([]interface{})) + sentinelEntityMappingCount = len(*param.Properties.SentinelEntitiesMappings) } // the max number of `sentinel_entity_mapping` and `entity_mapping` together is 5 @@ -521,17 +449,17 @@ func resourceSentinelAlertRuleScheduledCreateUpdate(d *pluginsdk.ResourceData, m } if !d.IsNewResource() { - resp, err := client.Get(ctx, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name) + resp, err := client.AlertRulesGet(ctx, id) if err != nil { return fmt.Errorf("retrieving Sentinel Alert Rule Scheduled %q: %+v", id, err) } - if err := assertAlertRuleKind(resp.Value, securityinsight.AlertRuleKindScheduled); err != nil { + if err := assertAlertRuleKind(resp.Model, alertrules.AlertRuleKindScheduled); err != nil { return fmt.Errorf("asserting alert rule of %q: %+v", id, err) } } - if _, err := client.CreateOrUpdate(ctx, workspaceID.ResourceGroupName, workspaceID.WorkspaceName, name, param); err != nil { + if _, err := client.AlertRulesCreateOrUpdate(ctx, id, param); err != nil { return fmt.Errorf("creating Sentinel Alert Rule Scheduled %q: %+v", id, err) } @@ -545,14 +473,14 @@ func resourceSentinelAlertRuleScheduledRead(d *pluginsdk.ResourceData, meta inte ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.AlertRuleID(d.Id()) + id, err := alertrules.ParseAlertRuleID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.WorkspaceName, id.Name) + resp, err := client.AlertRulesGet(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { log.Printf("[DEBUG] Sentinel Alert Rule Scheduled %q was not found - removing from state!", id) d.SetId("") return nil @@ -561,60 +489,58 @@ func resourceSentinelAlertRuleScheduledRead(d *pluginsdk.ResourceData, meta inte return fmt.Errorf("retrieving Sentinel Alert Rule Scheduled %q: %+v", id, err) } - if err := assertAlertRuleKind(resp.Value, securityinsight.AlertRuleKindScheduled); err != nil { + if err := assertAlertRuleKind(resp.Model, alertrules.AlertRuleKindScheduled); err != nil { return fmt.Errorf("asserting alert rule of %q: %+v", id, err) } - rule := resp.Value.(securityinsight.ScheduledAlertRule) - d.Set("name", id.Name) + if model := resp.Model; model != nil { + modelPtr := *model + rule := modelPtr.(alertrules.ScheduledAlertRule) - workspaceId := workspaces.NewWorkspaceID(id.SubscriptionId, id.ResourceGroup, id.WorkspaceName) - d.Set("log_analytics_workspace_id", workspaceId.ID()) + d.Set("name", id.RuleId) - if prop := rule.ScheduledAlertRuleProperties; prop != nil { - d.Set("description", prop.Description) - d.Set("display_name", prop.DisplayName) - if err := d.Set("tactics", flattenAlertRuleTactics(prop.Tactics)); err != nil { - return fmt.Errorf("setting `tactics`: %+v", err) - } - if err := d.Set("techniques", prop.Techniques); err != nil { - return fmt.Errorf("setting `techniques`: %+v", err) - } - if err := d.Set("incident_configuration", flattenAlertRuleIncidentConfiguration(prop.IncidentConfiguration, "create_incident", true)); err != nil { - return fmt.Errorf("setting `incident_configuration`: %+v", err) - } - d.Set("severity", string(prop.Severity)) - d.Set("enabled", prop.Enabled) - d.Set("query", prop.Query) - d.Set("query_frequency", prop.QueryFrequency) - d.Set("query_period", prop.QueryPeriod) - d.Set("trigger_operator", string(prop.TriggerOperator)) - - var threshold int32 - if prop.TriggerThreshold != nil { - threshold = *prop.TriggerThreshold - } - - d.Set("trigger_threshold", int(threshold)) - d.Set("suppression_enabled", prop.SuppressionEnabled) - d.Set("suppression_duration", prop.SuppressionDuration) - d.Set("alert_rule_template_guid", prop.AlertRuleTemplateName) - d.Set("alert_rule_template_version", prop.TemplateVersion) + workspaceId := workspaces.NewWorkspaceID(id.SubscriptionId, id.ResourceGroupName, id.WorkspaceName) + d.Set("log_analytics_workspace_id", workspaceId.ID()) - if err := d.Set("event_grouping", flattenAlertRuleScheduledEventGroupingSetting(prop.EventGroupingSettings)); err != nil { - return fmt.Errorf("setting `event_grouping`: %+v", err) - } - if err := d.Set("alert_details_override", flattenAlertRuleAlertDetailsOverride(prop.AlertDetailsOverride)); err != nil { - return fmt.Errorf("setting `alert_details_override`: %+v", err) - } - if err := d.Set("custom_details", utils.FlattenMapStringPtrString(prop.CustomDetails)); err != nil { - return fmt.Errorf("setting `custom_details`: %+v", err) - } - if err := d.Set("entity_mapping", flattenAlertRuleEntityMapping(prop.EntityMappings)); err != nil { - return fmt.Errorf("setting `entity_mapping`: %+v", err) - } - if err := d.Set("sentinel_entity_mapping", flattenAlertRuleSentinelEntityMapping(prop.SentinelEntitiesMappings)); err != nil { - return fmt.Errorf("setting `sentinel_entity_mapping`: %+v", err) + if prop := rule.Properties; prop != nil { + d.Set("description", prop.Description) + d.Set("display_name", prop.DisplayName) + if err := d.Set("tactics", flattenAlertRuleTactics(prop.Tactics)); err != nil { + return fmt.Errorf("setting `tactics`: %+v", err) + } + if err := d.Set("techniques", prop.Techniques); err != nil { + return fmt.Errorf("setting `techniques`: %+v", err) + } + if err := d.Set("incident_configuration", flattenAlertRuleIncidentConfiguration(prop.IncidentConfiguration, "create_incident", true)); err != nil { + return fmt.Errorf("setting `incident_configuration`: %+v", err) + } + d.Set("severity", string(prop.Severity)) + d.Set("enabled", prop.Enabled) + d.Set("query", prop.Query) + d.Set("query_frequency", prop.QueryFrequency) + d.Set("query_period", prop.QueryPeriod) + d.Set("trigger_operator", string(prop.TriggerOperator)) + d.Set("trigger_threshold", int(prop.TriggerThreshold)) + d.Set("suppression_enabled", prop.SuppressionEnabled) + d.Set("suppression_duration", prop.SuppressionDuration) + d.Set("alert_rule_template_guid", prop.AlertRuleTemplateName) + d.Set("alert_rule_template_version", prop.TemplateVersion) + + if err := d.Set("event_grouping", flattenAlertRuleScheduledEventGroupingSetting(prop.EventGroupingSettings)); err != nil { + return fmt.Errorf("setting `event_grouping`: %+v", err) + } + if err := d.Set("alert_details_override", flattenAlertRuleAlertDetailsOverride(prop.AlertDetailsOverride)); err != nil { + return fmt.Errorf("setting `alert_details_override`: %+v", err) + } + if err := d.Set("custom_details", utils.FlattenPtrMapStringString(prop.CustomDetails)); err != nil { + return fmt.Errorf("setting `custom_details`: %+v", err) + } + if err := d.Set("entity_mapping", flattenAlertRuleEntityMapping(prop.EntityMappings)); err != nil { + return fmt.Errorf("setting `entity_mapping`: %+v", err) + } + if err := d.Set("sentinel_entity_mapping", flattenAlertRuleSentinelEntityMapping(prop.SentinelEntitiesMappings)); err != nil { + return fmt.Errorf("setting `sentinel_entity_mapping`: %+v", err) + } } } @@ -626,41 +552,42 @@ func resourceSentinelAlertRuleScheduledDelete(d *pluginsdk.ResourceData, meta in ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.AlertRuleID(d.Id()) + id, err := alertrules.ParseAlertRuleID(d.Id()) if err != nil { return err } - if _, err := client.Delete(ctx, id.ResourceGroup, id.WorkspaceName, id.Name); err != nil { + if _, err := client.AlertRulesDelete(ctx, *id); err != nil { return fmt.Errorf("deleting Sentinel Alert Rule Scheduled %q: %+v", id, err) } return nil } -func expandAlertRuleScheduledEventGroupingSetting(input []interface{}) *securityinsight.EventGroupingSettings { +func expandAlertRuleScheduledEventGroupingSetting(input []interface{}) *alertrules.EventGroupingSettings { if len(input) == 0 || input[0] == nil { return nil } v := input[0].(map[string]interface{}) - result := securityinsight.EventGroupingSettings{} + result := alertrules.EventGroupingSettings{} if aggregationKind := v["aggregation_method"].(string); aggregationKind != "" { - result.AggregationKind = securityinsight.EventGroupingAggregationKind(aggregationKind) + kind := alertrules.EventGroupingAggregationKind(aggregationKind) + result.AggregationKind = &kind } return &result } -func flattenAlertRuleScheduledEventGroupingSetting(input *securityinsight.EventGroupingSettings) []interface{} { +func flattenAlertRuleScheduledEventGroupingSetting(input *alertrules.EventGroupingSettings) []interface{} { if input == nil { return []interface{}{} } var aggregationKind string - if input.AggregationKind != "" { - aggregationKind = string(input.AggregationKind) + if input.AggregationKind != nil { + aggregationKind = string(*input.AggregationKind) } return []interface{}{ diff --git a/internal/services/sentinel/sentinel_alert_rule_scheduled_resource_test.go b/internal/services/sentinel/sentinel_alert_rule_scheduled_resource_test.go index 897fca4fb7b4..9f3c28c8029e 100644 --- a/internal/services/sentinel/sentinel_alert_rule_scheduled_resource_test.go +++ b/internal/services/sentinel/sentinel_alert_rule_scheduled_resource_test.go @@ -5,13 +5,12 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/sentinel/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" - securityinsight "github.com/tombuildsstuff/kermit/sdk/securityinsights/2022-10-01-preview/securityinsights" ) type SentinelAlertRuleScheduledResource struct{} @@ -128,22 +127,26 @@ func TestAccSentinelAlertRuleScheduled_updateEventGroupingSetting(t *testing.T) } func (t SentinelAlertRuleScheduledResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.AlertRuleID(state.ID) + id, err := alertrules.ParseAlertRuleID(state.ID) if err != nil { return nil, err } - resp, err := clients.Sentinel.AlertRulesClient.Get(ctx, id.ResourceGroup, id.WorkspaceName, id.Name) + resp, err := clients.Sentinel.AlertRulesClient.AlertRulesGet(ctx, *id) if err != nil { return nil, fmt.Errorf("reading Sentinel Alert Rule Scheduled %q: %v", id, err) } - rule, ok := resp.Value.(securityinsight.ScheduledAlertRule) - if !ok { - return nil, fmt.Errorf("the Alert Rule %q is not a Scheduled Alert Rule", id) + if model := resp.Model; model != nil { + modelPtr := *model + rule, ok := modelPtr.(alertrules.ScheduledAlertRule) + if !ok { + return nil, fmt.Errorf("the Alert Rule %q is not a Fusion Alert Rule", id) + } + return utils.Bool(rule.Id != nil), nil } - return utils.Bool(rule.ID != nil), nil + return utils.Bool(false), nil } func (r SentinelAlertRuleScheduledResource) basic(data acceptance.TestData) string { diff --git a/internal/services/sentinel/validate/alert_rule_id.go b/internal/services/sentinel/validate/alert_rule_id.go deleted file mode 100644 index 9e3f7d5ae5a5..000000000000 --- a/internal/services/sentinel/validate/alert_rule_id.go +++ /dev/null @@ -1,23 +0,0 @@ -package validate - -// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten - -import ( - "fmt" - - "github.com/hashicorp/terraform-provider-azurerm/internal/services/sentinel/parse" -) - -func AlertRuleID(input interface{}, key string) (warnings []string, errors []error) { - v, ok := input.(string) - if !ok { - errors = append(errors, fmt.Errorf("expected %q to be a string", key)) - return - } - - if _, err := parse.AlertRuleID(v); err != nil { - errors = append(errors, err) - } - - return -} diff --git a/internal/services/sentinel/validate/alert_rule_id_test.go b/internal/services/sentinel/validate/alert_rule_id_test.go deleted file mode 100644 index 834a4766f4bf..000000000000 --- a/internal/services/sentinel/validate/alert_rule_id_test.go +++ /dev/null @@ -1,88 +0,0 @@ -package validate - -// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten - -import "testing" - -func TestAlertRuleID(t *testing.T) { - cases := []struct { - Input string - Valid bool - }{ - - { - // empty - Input: "", - Valid: false, - }, - - { - // missing SubscriptionId - Input: "/", - Valid: false, - }, - - { - // missing value for SubscriptionId - Input: "/subscriptions/", - Valid: false, - }, - - { - // missing ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", - Valid: false, - }, - - { - // missing value for ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", - Valid: false, - }, - - { - // missing WorkspaceName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.OperationalInsights/", - Valid: false, - }, - - { - // missing value for WorkspaceName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.OperationalInsights/workspaces/", - Valid: false, - }, - - { - // missing Name - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.OperationalInsights/workspaces/workspace1/providers/Microsoft.SecurityInsights/", - Valid: false, - }, - - { - // missing value for Name - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.OperationalInsights/workspaces/workspace1/providers/Microsoft.SecurityInsights/alertRules/", - Valid: false, - }, - - { - // valid - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.OperationalInsights/workspaces/workspace1/providers/Microsoft.SecurityInsights/alertRules/rule1", - Valid: true, - }, - - { - // upper-cased - Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/RESGROUP1/PROVIDERS/MICROSOFT.OPERATIONALINSIGHTS/WORKSPACES/WORKSPACE1/PROVIDERS/MICROSOFT.SECURITYINSIGHTS/ALERTRULES/RULE1", - Valid: false, - }, - } - for _, tc := range cases { - t.Logf("[DEBUG] Testing Value %s", tc.Input) - _, errors := AlertRuleID(tc.Input, "test") - valid := len(errors) == 0 - - if tc.Valid != valid { - t.Fatalf("Expected %t but got %t", tc.Valid, valid) - } - } -} diff --git a/utils/common_marshal.go b/utils/common_marshal.go index facb21ae61b4..9139f46b0172 100644 --- a/utils/common_marshal.go +++ b/utils/common_marshal.go @@ -37,6 +37,14 @@ func ExpandFloatRangeSlice(input []interface{}) *[][]float64 { return &result } +func ExpandPtrMapStringString(input map[string]interface{}) *map[string]string { + result := make(map[string]string) + for k, v := range input { + result[k] = v.(string) + } + return &result +} + func ExpandMapStringPtrString(input map[string]interface{}) map[string]*string { result := make(map[string]*string) for k, v := range input { diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/README.md new file mode 100644 index 000000000000..b4700b41a87f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/README.md @@ -0,0 +1,90 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules` Documentation + +The `alertrules` SDK allows for interaction with the Azure Resource Manager Service `securityinsights` (API Version `2022-10-01-preview`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules" +``` + + +### Client Initialization + +```go +client := alertrules.NewAlertRulesClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `AlertRulesClient.AlertRulesCreateOrUpdate` + +```go +ctx := context.TODO() +id := alertrules.NewAlertRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "workspaceValue", "ruleIdValue") + +payload := alertrules.AlertRule{ + // ... +} + + +read, err := client.AlertRulesCreateOrUpdate(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `AlertRulesClient.AlertRulesDelete` + +```go +ctx := context.TODO() +id := alertrules.NewAlertRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "workspaceValue", "ruleIdValue") + +read, err := client.AlertRulesDelete(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `AlertRulesClient.AlertRulesGet` + +```go +ctx := context.TODO() +id := alertrules.NewAlertRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "workspaceValue", "ruleIdValue") + +read, err := client.AlertRulesGet(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `AlertRulesClient.AlertRulesList` + +```go +ctx := context.TODO() +id := alertrules.NewWorkspaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "workspaceValue") + +// alternatively `client.AlertRulesList(ctx, id)` can be used to do batched pagination +items, err := client.AlertRulesListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/client.go new file mode 100644 index 000000000000..6e34bca2ce36 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/client.go @@ -0,0 +1,18 @@ +package alertrules + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AlertRulesClient struct { + Client autorest.Client + baseUri string +} + +func NewAlertRulesClientWithBaseURI(endpoint string) AlertRulesClient { + return AlertRulesClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/constants.go new file mode 100644 index 000000000000..793d176c710f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/constants.go @@ -0,0 +1,442 @@ +package alertrules + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AlertDetail string + +const ( + AlertDetailDisplayName AlertDetail = "DisplayName" + AlertDetailSeverity AlertDetail = "Severity" +) + +func PossibleValuesForAlertDetail() []string { + return []string{ + string(AlertDetailDisplayName), + string(AlertDetailSeverity), + } +} + +func parseAlertDetail(input string) (*AlertDetail, error) { + vals := map[string]AlertDetail{ + "displayname": AlertDetailDisplayName, + "severity": AlertDetailSeverity, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := AlertDetail(input) + return &out, nil +} + +type AlertProperty string + +const ( + AlertPropertyAlertLink AlertProperty = "AlertLink" + AlertPropertyConfidenceLevel AlertProperty = "ConfidenceLevel" + AlertPropertyConfidenceScore AlertProperty = "ConfidenceScore" + AlertPropertyExtendedLinks AlertProperty = "ExtendedLinks" + AlertPropertyProductComponentName AlertProperty = "ProductComponentName" + AlertPropertyProductName AlertProperty = "ProductName" + AlertPropertyProviderName AlertProperty = "ProviderName" + AlertPropertyRemediationSteps AlertProperty = "RemediationSteps" + AlertPropertyTechniques AlertProperty = "Techniques" +) + +func PossibleValuesForAlertProperty() []string { + return []string{ + string(AlertPropertyAlertLink), + string(AlertPropertyConfidenceLevel), + string(AlertPropertyConfidenceScore), + string(AlertPropertyExtendedLinks), + string(AlertPropertyProductComponentName), + string(AlertPropertyProductName), + string(AlertPropertyProviderName), + string(AlertPropertyRemediationSteps), + string(AlertPropertyTechniques), + } +} + +func parseAlertProperty(input string) (*AlertProperty, error) { + vals := map[string]AlertProperty{ + "alertlink": AlertPropertyAlertLink, + "confidencelevel": AlertPropertyConfidenceLevel, + "confidencescore": AlertPropertyConfidenceScore, + "extendedlinks": AlertPropertyExtendedLinks, + "productcomponentname": AlertPropertyProductComponentName, + "productname": AlertPropertyProductName, + "providername": AlertPropertyProviderName, + "remediationsteps": AlertPropertyRemediationSteps, + "techniques": AlertPropertyTechniques, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := AlertProperty(input) + return &out, nil +} + +type AlertRuleKind string + +const ( + AlertRuleKindFusion AlertRuleKind = "Fusion" + AlertRuleKindMLBehaviorAnalytics AlertRuleKind = "MLBehaviorAnalytics" + AlertRuleKindMicrosoftSecurityIncidentCreation AlertRuleKind = "MicrosoftSecurityIncidentCreation" + AlertRuleKindNRT AlertRuleKind = "NRT" + AlertRuleKindScheduled AlertRuleKind = "Scheduled" + AlertRuleKindThreatIntelligence AlertRuleKind = "ThreatIntelligence" +) + +func PossibleValuesForAlertRuleKind() []string { + return []string{ + string(AlertRuleKindFusion), + string(AlertRuleKindMLBehaviorAnalytics), + string(AlertRuleKindMicrosoftSecurityIncidentCreation), + string(AlertRuleKindNRT), + string(AlertRuleKindScheduled), + string(AlertRuleKindThreatIntelligence), + } +} + +func parseAlertRuleKind(input string) (*AlertRuleKind, error) { + vals := map[string]AlertRuleKind{ + "fusion": AlertRuleKindFusion, + "mlbehavioranalytics": AlertRuleKindMLBehaviorAnalytics, + "microsoftsecurityincidentcreation": AlertRuleKindMicrosoftSecurityIncidentCreation, + "nrt": AlertRuleKindNRT, + "scheduled": AlertRuleKindScheduled, + "threatintelligence": AlertRuleKindThreatIntelligence, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := AlertRuleKind(input) + return &out, nil +} + +type AlertSeverity string + +const ( + AlertSeverityHigh AlertSeverity = "High" + AlertSeverityInformational AlertSeverity = "Informational" + AlertSeverityLow AlertSeverity = "Low" + AlertSeverityMedium AlertSeverity = "Medium" +) + +func PossibleValuesForAlertSeverity() []string { + return []string{ + string(AlertSeverityHigh), + string(AlertSeverityInformational), + string(AlertSeverityLow), + string(AlertSeverityMedium), + } +} + +func parseAlertSeverity(input string) (*AlertSeverity, error) { + vals := map[string]AlertSeverity{ + "high": AlertSeverityHigh, + "informational": AlertSeverityInformational, + "low": AlertSeverityLow, + "medium": AlertSeverityMedium, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := AlertSeverity(input) + return &out, nil +} + +type AttackTactic string + +const ( + AttackTacticCollection AttackTactic = "Collection" + AttackTacticCommandAndControl AttackTactic = "CommandAndControl" + AttackTacticCredentialAccess AttackTactic = "CredentialAccess" + AttackTacticDefenseEvasion AttackTactic = "DefenseEvasion" + AttackTacticDiscovery AttackTactic = "Discovery" + AttackTacticExecution AttackTactic = "Execution" + AttackTacticExfiltration AttackTactic = "Exfiltration" + AttackTacticImpact AttackTactic = "Impact" + AttackTacticImpairProcessControl AttackTactic = "ImpairProcessControl" + AttackTacticInhibitResponseFunction AttackTactic = "InhibitResponseFunction" + AttackTacticInitialAccess AttackTactic = "InitialAccess" + AttackTacticLateralMovement AttackTactic = "LateralMovement" + AttackTacticPersistence AttackTactic = "Persistence" + AttackTacticPreAttack AttackTactic = "PreAttack" + AttackTacticPrivilegeEscalation AttackTactic = "PrivilegeEscalation" + AttackTacticReconnaissance AttackTactic = "Reconnaissance" + AttackTacticResourceDevelopment AttackTactic = "ResourceDevelopment" +) + +func PossibleValuesForAttackTactic() []string { + return []string{ + string(AttackTacticCollection), + string(AttackTacticCommandAndControl), + string(AttackTacticCredentialAccess), + string(AttackTacticDefenseEvasion), + string(AttackTacticDiscovery), + string(AttackTacticExecution), + string(AttackTacticExfiltration), + string(AttackTacticImpact), + string(AttackTacticImpairProcessControl), + string(AttackTacticInhibitResponseFunction), + string(AttackTacticInitialAccess), + string(AttackTacticLateralMovement), + string(AttackTacticPersistence), + string(AttackTacticPreAttack), + string(AttackTacticPrivilegeEscalation), + string(AttackTacticReconnaissance), + string(AttackTacticResourceDevelopment), + } +} + +func parseAttackTactic(input string) (*AttackTactic, error) { + vals := map[string]AttackTactic{ + "collection": AttackTacticCollection, + "commandandcontrol": AttackTacticCommandAndControl, + "credentialaccess": AttackTacticCredentialAccess, + "defenseevasion": AttackTacticDefenseEvasion, + "discovery": AttackTacticDiscovery, + "execution": AttackTacticExecution, + "exfiltration": AttackTacticExfiltration, + "impact": AttackTacticImpact, + "impairprocesscontrol": AttackTacticImpairProcessControl, + "inhibitresponsefunction": AttackTacticInhibitResponseFunction, + "initialaccess": AttackTacticInitialAccess, + "lateralmovement": AttackTacticLateralMovement, + "persistence": AttackTacticPersistence, + "preattack": AttackTacticPreAttack, + "privilegeescalation": AttackTacticPrivilegeEscalation, + "reconnaissance": AttackTacticReconnaissance, + "resourcedevelopment": AttackTacticResourceDevelopment, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := AttackTactic(input) + return &out, nil +} + +type EntityMappingType string + +const ( + EntityMappingTypeAccount EntityMappingType = "Account" + EntityMappingTypeAzureResource EntityMappingType = "AzureResource" + EntityMappingTypeCloudApplication EntityMappingType = "CloudApplication" + EntityMappingTypeDNS EntityMappingType = "DNS" + EntityMappingTypeFile EntityMappingType = "File" + EntityMappingTypeFileHash EntityMappingType = "FileHash" + EntityMappingTypeHost EntityMappingType = "Host" + EntityMappingTypeIP EntityMappingType = "IP" + EntityMappingTypeMailCluster EntityMappingType = "MailCluster" + EntityMappingTypeMailMessage EntityMappingType = "MailMessage" + EntityMappingTypeMailbox EntityMappingType = "Mailbox" + EntityMappingTypeMalware EntityMappingType = "Malware" + EntityMappingTypeProcess EntityMappingType = "Process" + EntityMappingTypeRegistryKey EntityMappingType = "RegistryKey" + EntityMappingTypeRegistryValue EntityMappingType = "RegistryValue" + EntityMappingTypeSecurityGroup EntityMappingType = "SecurityGroup" + EntityMappingTypeSubmissionMail EntityMappingType = "SubmissionMail" + EntityMappingTypeURL EntityMappingType = "URL" +) + +func PossibleValuesForEntityMappingType() []string { + return []string{ + string(EntityMappingTypeAccount), + string(EntityMappingTypeAzureResource), + string(EntityMappingTypeCloudApplication), + string(EntityMappingTypeDNS), + string(EntityMappingTypeFile), + string(EntityMappingTypeFileHash), + string(EntityMappingTypeHost), + string(EntityMappingTypeIP), + string(EntityMappingTypeMailCluster), + string(EntityMappingTypeMailMessage), + string(EntityMappingTypeMailbox), + string(EntityMappingTypeMalware), + string(EntityMappingTypeProcess), + string(EntityMappingTypeRegistryKey), + string(EntityMappingTypeRegistryValue), + string(EntityMappingTypeSecurityGroup), + string(EntityMappingTypeSubmissionMail), + string(EntityMappingTypeURL), + } +} + +func parseEntityMappingType(input string) (*EntityMappingType, error) { + vals := map[string]EntityMappingType{ + "account": EntityMappingTypeAccount, + "azureresource": EntityMappingTypeAzureResource, + "cloudapplication": EntityMappingTypeCloudApplication, + "dns": EntityMappingTypeDNS, + "file": EntityMappingTypeFile, + "filehash": EntityMappingTypeFileHash, + "host": EntityMappingTypeHost, + "ip": EntityMappingTypeIP, + "mailcluster": EntityMappingTypeMailCluster, + "mailmessage": EntityMappingTypeMailMessage, + "mailbox": EntityMappingTypeMailbox, + "malware": EntityMappingTypeMalware, + "process": EntityMappingTypeProcess, + "registrykey": EntityMappingTypeRegistryKey, + "registryvalue": EntityMappingTypeRegistryValue, + "securitygroup": EntityMappingTypeSecurityGroup, + "submissionmail": EntityMappingTypeSubmissionMail, + "url": EntityMappingTypeURL, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := EntityMappingType(input) + return &out, nil +} + +type EventGroupingAggregationKind string + +const ( + EventGroupingAggregationKindAlertPerResult EventGroupingAggregationKind = "AlertPerResult" + EventGroupingAggregationKindSingleAlert EventGroupingAggregationKind = "SingleAlert" +) + +func PossibleValuesForEventGroupingAggregationKind() []string { + return []string{ + string(EventGroupingAggregationKindAlertPerResult), + string(EventGroupingAggregationKindSingleAlert), + } +} + +func parseEventGroupingAggregationKind(input string) (*EventGroupingAggregationKind, error) { + vals := map[string]EventGroupingAggregationKind{ + "alertperresult": EventGroupingAggregationKindAlertPerResult, + "singlealert": EventGroupingAggregationKindSingleAlert, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := EventGroupingAggregationKind(input) + return &out, nil +} + +type MatchingMethod string + +const ( + MatchingMethodAllEntities MatchingMethod = "AllEntities" + MatchingMethodAnyAlert MatchingMethod = "AnyAlert" + MatchingMethodSelected MatchingMethod = "Selected" +) + +func PossibleValuesForMatchingMethod() []string { + return []string{ + string(MatchingMethodAllEntities), + string(MatchingMethodAnyAlert), + string(MatchingMethodSelected), + } +} + +func parseMatchingMethod(input string) (*MatchingMethod, error) { + vals := map[string]MatchingMethod{ + "allentities": MatchingMethodAllEntities, + "anyalert": MatchingMethodAnyAlert, + "selected": MatchingMethodSelected, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := MatchingMethod(input) + return &out, nil +} + +type MicrosoftSecurityProductName string + +const ( + MicrosoftSecurityProductNameAzureActiveDirectoryIdentityProtection MicrosoftSecurityProductName = "Azure Active Directory Identity Protection" + MicrosoftSecurityProductNameAzureAdvancedThreatProtection MicrosoftSecurityProductName = "Azure Advanced Threat Protection" + MicrosoftSecurityProductNameAzureSecurityCenter MicrosoftSecurityProductName = "Azure Security Center" + MicrosoftSecurityProductNameAzureSecurityCenterForIoT MicrosoftSecurityProductName = "Azure Security Center for IoT" + MicrosoftSecurityProductNameMicrosoftCloudAppSecurity MicrosoftSecurityProductName = "Microsoft Cloud App Security" + MicrosoftSecurityProductNameMicrosoftDefenderAdvancedThreatProtection MicrosoftSecurityProductName = "Microsoft Defender Advanced Threat Protection" + MicrosoftSecurityProductNameOfficeThreeSixFiveAdvancedThreatProtection MicrosoftSecurityProductName = "Office 365 Advanced Threat Protection" +) + +func PossibleValuesForMicrosoftSecurityProductName() []string { + return []string{ + string(MicrosoftSecurityProductNameAzureActiveDirectoryIdentityProtection), + string(MicrosoftSecurityProductNameAzureAdvancedThreatProtection), + string(MicrosoftSecurityProductNameAzureSecurityCenter), + string(MicrosoftSecurityProductNameAzureSecurityCenterForIoT), + string(MicrosoftSecurityProductNameMicrosoftCloudAppSecurity), + string(MicrosoftSecurityProductNameMicrosoftDefenderAdvancedThreatProtection), + string(MicrosoftSecurityProductNameOfficeThreeSixFiveAdvancedThreatProtection), + } +} + +func parseMicrosoftSecurityProductName(input string) (*MicrosoftSecurityProductName, error) { + vals := map[string]MicrosoftSecurityProductName{ + "azure active directory identity protection": MicrosoftSecurityProductNameAzureActiveDirectoryIdentityProtection, + "azure advanced threat protection": MicrosoftSecurityProductNameAzureAdvancedThreatProtection, + "azure security center": MicrosoftSecurityProductNameAzureSecurityCenter, + "azure security center for iot": MicrosoftSecurityProductNameAzureSecurityCenterForIoT, + "microsoft cloud app security": MicrosoftSecurityProductNameMicrosoftCloudAppSecurity, + "microsoft defender advanced threat protection": MicrosoftSecurityProductNameMicrosoftDefenderAdvancedThreatProtection, + "office 365 advanced threat protection": MicrosoftSecurityProductNameOfficeThreeSixFiveAdvancedThreatProtection, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := MicrosoftSecurityProductName(input) + return &out, nil +} + +type TriggerOperator string + +const ( + TriggerOperatorEqual TriggerOperator = "Equal" + TriggerOperatorGreaterThan TriggerOperator = "GreaterThan" + TriggerOperatorLessThan TriggerOperator = "LessThan" + TriggerOperatorNotEqual TriggerOperator = "NotEqual" +) + +func PossibleValuesForTriggerOperator() []string { + return []string{ + string(TriggerOperatorEqual), + string(TriggerOperatorGreaterThan), + string(TriggerOperatorLessThan), + string(TriggerOperatorNotEqual), + } +} + +func parseTriggerOperator(input string) (*TriggerOperator, error) { + vals := map[string]TriggerOperator{ + "equal": TriggerOperatorEqual, + "greaterthan": TriggerOperatorGreaterThan, + "lessthan": TriggerOperatorLessThan, + "notequal": TriggerOperatorNotEqual, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := TriggerOperator(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/id_alertrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/id_alertrule.go new file mode 100644 index 000000000000..f95578dfde6b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/id_alertrule.go @@ -0,0 +1,142 @@ +package alertrules + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +var _ resourceids.ResourceId = AlertRuleId{} + +// AlertRuleId is a struct representing the Resource ID for a Alert Rule +type AlertRuleId struct { + SubscriptionId string + ResourceGroupName string + WorkspaceName string + RuleId string +} + +// NewAlertRuleID returns a new AlertRuleId struct +func NewAlertRuleID(subscriptionId string, resourceGroupName string, workspaceName string, ruleId string) AlertRuleId { + return AlertRuleId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + WorkspaceName: workspaceName, + RuleId: ruleId, + } +} + +// ParseAlertRuleID parses 'input' into a AlertRuleId +func ParseAlertRuleID(input string) (*AlertRuleId, error) { + parser := resourceids.NewParserFromResourceIdType(AlertRuleId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := AlertRuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.WorkspaceName, ok = parsed.Parsed["workspaceName"]; !ok { + return nil, fmt.Errorf("the segment 'workspaceName' was not found in the resource id %q", input) + } + + if id.RuleId, ok = parsed.Parsed["ruleId"]; !ok { + return nil, fmt.Errorf("the segment 'ruleId' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseAlertRuleIDInsensitively parses 'input' case-insensitively into a AlertRuleId +// note: this method should only be used for API response data and not user input +func ParseAlertRuleIDInsensitively(input string) (*AlertRuleId, error) { + parser := resourceids.NewParserFromResourceIdType(AlertRuleId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := AlertRuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.WorkspaceName, ok = parsed.Parsed["workspaceName"]; !ok { + return nil, fmt.Errorf("the segment 'workspaceName' was not found in the resource id %q", input) + } + + if id.RuleId, ok = parsed.Parsed["ruleId"]; !ok { + return nil, fmt.Errorf("the segment 'ruleId' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateAlertRuleID checks that 'input' can be parsed as a Alert Rule ID +func ValidateAlertRuleID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseAlertRuleID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Alert Rule ID +func (id AlertRuleId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.OperationalInsights/workspaces/%s/providers/Microsoft.SecurityInsights/alertRules/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.WorkspaceName, id.RuleId) +} + +// Segments returns a slice of Resource ID Segments which comprise this Alert Rule ID +func (id AlertRuleId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftOperationalInsights", "Microsoft.OperationalInsights", "Microsoft.OperationalInsights"), + resourceids.StaticSegment("staticWorkspaces", "workspaces", "workspaces"), + resourceids.UserSpecifiedSegment("workspaceName", "workspaceValue"), + resourceids.StaticSegment("staticProviders2", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftSecurityInsights", "Microsoft.SecurityInsights", "Microsoft.SecurityInsights"), + resourceids.StaticSegment("staticAlertRules", "alertRules", "alertRules"), + resourceids.UserSpecifiedSegment("ruleId", "ruleIdValue"), + } +} + +// String returns a human-readable description of this Alert Rule ID +func (id AlertRuleId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Workspace Name: %q", id.WorkspaceName), + fmt.Sprintf("Rule: %q", id.RuleId), + } + return fmt.Sprintf("Alert Rule (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/id_workspace.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/id_workspace.go new file mode 100644 index 000000000000..8c3c0b8673f4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/id_workspace.go @@ -0,0 +1,127 @@ +package alertrules + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +var _ resourceids.ResourceId = WorkspaceId{} + +// WorkspaceId is a struct representing the Resource ID for a Workspace +type WorkspaceId struct { + SubscriptionId string + ResourceGroupName string + WorkspaceName string +} + +// NewWorkspaceID returns a new WorkspaceId struct +func NewWorkspaceID(subscriptionId string, resourceGroupName string, workspaceName string) WorkspaceId { + return WorkspaceId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + WorkspaceName: workspaceName, + } +} + +// ParseWorkspaceID parses 'input' into a WorkspaceId +func ParseWorkspaceID(input string) (*WorkspaceId, error) { + parser := resourceids.NewParserFromResourceIdType(WorkspaceId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := WorkspaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.WorkspaceName, ok = parsed.Parsed["workspaceName"]; !ok { + return nil, fmt.Errorf("the segment 'workspaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseWorkspaceIDInsensitively parses 'input' case-insensitively into a WorkspaceId +// note: this method should only be used for API response data and not user input +func ParseWorkspaceIDInsensitively(input string) (*WorkspaceId, error) { + parser := resourceids.NewParserFromResourceIdType(WorkspaceId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := WorkspaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.WorkspaceName, ok = parsed.Parsed["workspaceName"]; !ok { + return nil, fmt.Errorf("the segment 'workspaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateWorkspaceID checks that 'input' can be parsed as a Workspace ID +func ValidateWorkspaceID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseWorkspaceID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Workspace ID +func (id WorkspaceId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.OperationalInsights/workspaces/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.WorkspaceName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Workspace ID +func (id WorkspaceId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftOperationalInsights", "Microsoft.OperationalInsights", "Microsoft.OperationalInsights"), + resourceids.StaticSegment("staticWorkspaces", "workspaces", "workspaces"), + resourceids.UserSpecifiedSegment("workspaceName", "workspaceValue"), + } +} + +// String returns a human-readable description of this Workspace ID +func (id WorkspaceId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Workspace Name: %q", id.WorkspaceName), + } + return fmt.Sprintf("Workspace (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/method_alertrulescreateorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/method_alertrulescreateorupdate_autorest.go new file mode 100644 index 000000000000..7918c11805a3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/method_alertrulescreateorupdate_autorest.go @@ -0,0 +1,75 @@ +package alertrules + +import ( + "context" + "encoding/json" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AlertRulesCreateOrUpdateOperationResponse struct { + HttpResponse *http.Response + Model *AlertRule +} + +// AlertRulesCreateOrUpdate ... +func (c AlertRulesClient) AlertRulesCreateOrUpdate(ctx context.Context, id AlertRuleId, input AlertRule) (result AlertRulesCreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForAlertRulesCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "alertrules.AlertRulesClient", "AlertRulesCreateOrUpdate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "alertrules.AlertRulesClient", "AlertRulesCreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForAlertRulesCreateOrUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "alertrules.AlertRulesClient", "AlertRulesCreateOrUpdate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForAlertRulesCreateOrUpdate prepares the AlertRulesCreateOrUpdate request. +func (c AlertRulesClient) preparerForAlertRulesCreateOrUpdate(ctx context.Context, id AlertRuleId, input AlertRule) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForAlertRulesCreateOrUpdate handles the response to the AlertRulesCreateOrUpdate request. The method always +// closes the http.Response Body. +func (c AlertRulesClient) responderForAlertRulesCreateOrUpdate(resp *http.Response) (result AlertRulesCreateOrUpdateOperationResponse, err error) { + var respObj json.RawMessage + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + model, err := unmarshalAlertRuleImplementation(respObj) + if err != nil { + return + } + result.Model = &model + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/method_alertrulesdelete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/method_alertrulesdelete_autorest.go new file mode 100644 index 000000000000..635d0607bc38 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/method_alertrulesdelete_autorest.go @@ -0,0 +1,66 @@ +package alertrules + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AlertRulesDeleteOperationResponse struct { + HttpResponse *http.Response +} + +// AlertRulesDelete ... +func (c AlertRulesClient) AlertRulesDelete(ctx context.Context, id AlertRuleId) (result AlertRulesDeleteOperationResponse, err error) { + req, err := c.preparerForAlertRulesDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "alertrules.AlertRulesClient", "AlertRulesDelete", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "alertrules.AlertRulesClient", "AlertRulesDelete", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForAlertRulesDelete(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "alertrules.AlertRulesClient", "AlertRulesDelete", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForAlertRulesDelete prepares the AlertRulesDelete request. +func (c AlertRulesClient) preparerForAlertRulesDelete(ctx context.Context, id AlertRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForAlertRulesDelete handles the response to the AlertRulesDelete request. The method always +// closes the http.Response Body. +func (c AlertRulesClient) responderForAlertRulesDelete(resp *http.Response) (result AlertRulesDeleteOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/method_alertrulesget_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/method_alertrulesget_autorest.go new file mode 100644 index 000000000000..bf4bd79cd1b7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/method_alertrulesget_autorest.go @@ -0,0 +1,74 @@ +package alertrules + +import ( + "context" + "encoding/json" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AlertRulesGetOperationResponse struct { + HttpResponse *http.Response + Model *AlertRule +} + +// AlertRulesGet ... +func (c AlertRulesClient) AlertRulesGet(ctx context.Context, id AlertRuleId) (result AlertRulesGetOperationResponse, err error) { + req, err := c.preparerForAlertRulesGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "alertrules.AlertRulesClient", "AlertRulesGet", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "alertrules.AlertRulesClient", "AlertRulesGet", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForAlertRulesGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "alertrules.AlertRulesClient", "AlertRulesGet", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForAlertRulesGet prepares the AlertRulesGet request. +func (c AlertRulesClient) preparerForAlertRulesGet(ctx context.Context, id AlertRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForAlertRulesGet handles the response to the AlertRulesGet request. The method always +// closes the http.Response Body. +func (c AlertRulesClient) responderForAlertRulesGet(resp *http.Response) (result AlertRulesGetOperationResponse, err error) { + var respObj json.RawMessage + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + model, err := unmarshalAlertRuleImplementation(respObj) + if err != nil { + return + } + result.Model = &model + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/method_alertruleslist_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/method_alertruleslist_autorest.go new file mode 100644 index 000000000000..f65b7ed44eb4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/method_alertruleslist_autorest.go @@ -0,0 +1,196 @@ +package alertrules + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AlertRulesListOperationResponse struct { + HttpResponse *http.Response + Model *[]AlertRule + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (AlertRulesListOperationResponse, error) +} + +type AlertRulesListCompleteResult struct { + Items []AlertRule +} + +func (r AlertRulesListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r AlertRulesListOperationResponse) LoadMore(ctx context.Context) (resp AlertRulesListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// AlertRulesList ... +func (c AlertRulesClient) AlertRulesList(ctx context.Context, id WorkspaceId) (resp AlertRulesListOperationResponse, err error) { + req, err := c.preparerForAlertRulesList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "alertrules.AlertRulesClient", "AlertRulesList", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "alertrules.AlertRulesClient", "AlertRulesList", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForAlertRulesList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "alertrules.AlertRulesClient", "AlertRulesList", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// preparerForAlertRulesList prepares the AlertRulesList request. +func (c AlertRulesClient) preparerForAlertRulesList(ctx context.Context, id WorkspaceId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.SecurityInsights/alertRules", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForAlertRulesListWithNextLink prepares the AlertRulesList request with the given nextLink token. +func (c AlertRulesClient) preparerForAlertRulesListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForAlertRulesList handles the response to the AlertRulesList request. The method always +// closes the http.Response Body. +func (c AlertRulesClient) responderForAlertRulesList(resp *http.Response) (result AlertRulesListOperationResponse, err error) { + type page struct { + Values []json.RawMessage `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + temp := make([]AlertRule, 0) + for i, v := range respObj.Values { + val, err := unmarshalAlertRuleImplementation(v) + if err != nil { + err = fmt.Errorf("unmarshalling item %d for AlertRule (%q): %+v", i, v, err) + return result, err + } + temp = append(temp, val) + } + result.Model = &temp + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result AlertRulesListOperationResponse, err error) { + req, err := c.preparerForAlertRulesListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "alertrules.AlertRulesClient", "AlertRulesList", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "alertrules.AlertRulesClient", "AlertRulesList", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForAlertRulesList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "alertrules.AlertRulesClient", "AlertRulesList", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} + +// AlertRulesListComplete retrieves all of the results into a single object +func (c AlertRulesClient) AlertRulesListComplete(ctx context.Context, id WorkspaceId) (AlertRulesListCompleteResult, error) { + return c.AlertRulesListCompleteMatchingPredicate(ctx, id, AlertRuleOperationPredicate{}) +} + +// AlertRulesListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c AlertRulesClient) AlertRulesListCompleteMatchingPredicate(ctx context.Context, id WorkspaceId, predicate AlertRuleOperationPredicate) (resp AlertRulesListCompleteResult, err error) { + items := make([]AlertRule, 0) + + page, err := c.AlertRulesList(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := AlertRulesListCompleteResult{ + Items: items, + } + return out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_alertdetailsoverride.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_alertdetailsoverride.go new file mode 100644 index 000000000000..15010b19db06 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_alertdetailsoverride.go @@ -0,0 +1,12 @@ +package alertrules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AlertDetailsOverride struct { + AlertDescriptionFormat *string `json:"alertDescriptionFormat,omitempty"` + AlertDisplayNameFormat *string `json:"alertDisplayNameFormat,omitempty"` + AlertDynamicProperties *[]AlertPropertyMapping `json:"alertDynamicProperties,omitempty"` + AlertSeverityColumnName *string `json:"alertSeverityColumnName,omitempty"` + AlertTacticsColumnName *string `json:"alertTacticsColumnName,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_alertpropertymapping.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_alertpropertymapping.go new file mode 100644 index 000000000000..f98f2362b60d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_alertpropertymapping.go @@ -0,0 +1,9 @@ +package alertrules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AlertPropertyMapping struct { + AlertProperty *AlertProperty `json:"alertProperty,omitempty"` + Value *string `json:"value,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_alertrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_alertrule.go new file mode 100644 index 000000000000..ba13c7d9e25d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_alertrule.go @@ -0,0 +1,88 @@ +package alertrules + +import ( + "encoding/json" + "fmt" + "strings" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AlertRule interface { +} + +func unmarshalAlertRuleImplementation(input []byte) (AlertRule, error) { + if input == nil { + return nil, nil + } + + var temp map[string]interface{} + if err := json.Unmarshal(input, &temp); err != nil { + return nil, fmt.Errorf("unmarshaling AlertRule into map[string]interface: %+v", err) + } + + value, ok := temp["kind"].(string) + if !ok { + return nil, nil + } + + if strings.EqualFold(value, "Fusion") { + var out FusionAlertRule + if err := json.Unmarshal(input, &out); err != nil { + return nil, fmt.Errorf("unmarshaling into FusionAlertRule: %+v", err) + } + return out, nil + } + + if strings.EqualFold(value, "MLBehaviorAnalytics") { + var out MLBehaviorAnalyticsAlertRule + if err := json.Unmarshal(input, &out); err != nil { + return nil, fmt.Errorf("unmarshaling into MLBehaviorAnalyticsAlertRule: %+v", err) + } + return out, nil + } + + if strings.EqualFold(value, "MicrosoftSecurityIncidentCreation") { + var out MicrosoftSecurityIncidentCreationAlertRule + if err := json.Unmarshal(input, &out); err != nil { + return nil, fmt.Errorf("unmarshaling into MicrosoftSecurityIncidentCreationAlertRule: %+v", err) + } + return out, nil + } + + if strings.EqualFold(value, "NRT") { + var out NrtAlertRule + if err := json.Unmarshal(input, &out); err != nil { + return nil, fmt.Errorf("unmarshaling into NrtAlertRule: %+v", err) + } + return out, nil + } + + if strings.EqualFold(value, "Scheduled") { + var out ScheduledAlertRule + if err := json.Unmarshal(input, &out); err != nil { + return nil, fmt.Errorf("unmarshaling into ScheduledAlertRule: %+v", err) + } + return out, nil + } + + if strings.EqualFold(value, "ThreatIntelligence") { + var out ThreatIntelligenceAlertRule + if err := json.Unmarshal(input, &out); err != nil { + return nil, fmt.Errorf("unmarshaling into ThreatIntelligenceAlertRule: %+v", err) + } + return out, nil + } + + type RawAlertRuleImpl struct { + Type string `json:"-"` + Values map[string]interface{} `json:"-"` + } + out := RawAlertRuleImpl{ + Type: value, + Values: temp, + } + return out, nil + +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_entitymapping.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_entitymapping.go new file mode 100644 index 000000000000..b1fc81c3323a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_entitymapping.go @@ -0,0 +1,9 @@ +package alertrules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EntityMapping struct { + EntityType *EntityMappingType `json:"entityType,omitempty"` + FieldMappings *[]FieldMapping `json:"fieldMappings,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_eventgroupingsettings.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_eventgroupingsettings.go new file mode 100644 index 000000000000..ae513b5b198c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_eventgroupingsettings.go @@ -0,0 +1,8 @@ +package alertrules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EventGroupingSettings struct { + AggregationKind *EventGroupingAggregationKind `json:"aggregationKind,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fieldmapping.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fieldmapping.go new file mode 100644 index 000000000000..9e73ac232185 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fieldmapping.go @@ -0,0 +1,9 @@ +package alertrules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FieldMapping struct { + ColumnName *string `json:"columnName,omitempty"` + Identifier *string `json:"identifier,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionalertrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionalertrule.go new file mode 100644 index 000000000000..c4ed17f4319a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionalertrule.go @@ -0,0 +1,48 @@ +package alertrules + +import ( + "encoding/json" + "fmt" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +var _ AlertRule = FusionAlertRule{} + +type FusionAlertRule struct { + Properties *FusionAlertRuleProperties `json:"properties,omitempty"` + + // Fields inherited from AlertRule + Etag *string `json:"etag,omitempty"` + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} + +var _ json.Marshaler = FusionAlertRule{} + +func (s FusionAlertRule) MarshalJSON() ([]byte, error) { + type wrapper FusionAlertRule + wrapped := wrapper(s) + encoded, err := json.Marshal(wrapped) + if err != nil { + return nil, fmt.Errorf("marshaling FusionAlertRule: %+v", err) + } + + var decoded map[string]interface{} + if err := json.Unmarshal(encoded, &decoded); err != nil { + return nil, fmt.Errorf("unmarshaling FusionAlertRule: %+v", err) + } + decoded["kind"] = "Fusion" + + encoded, err = json.Marshal(decoded) + if err != nil { + return nil, fmt.Errorf("re-marshaling FusionAlertRule: %+v", err) + } + + return encoded, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionalertruleproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionalertruleproperties.go new file mode 100644 index 000000000000..89e3751fcc87 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionalertruleproperties.go @@ -0,0 +1,35 @@ +package alertrules + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FusionAlertRuleProperties struct { + AlertRuleTemplateName string `json:"alertRuleTemplateName"` + Description *string `json:"description,omitempty"` + DisplayName *string `json:"displayName,omitempty"` + Enabled bool `json:"enabled"` + LastModifiedUtc *string `json:"lastModifiedUtc,omitempty"` + ScenarioExclusionPatterns *[]FusionScenarioExclusionPattern `json:"scenarioExclusionPatterns,omitempty"` + Severity *AlertSeverity `json:"severity,omitempty"` + SourceSettings *[]FusionSourceSettings `json:"sourceSettings,omitempty"` + Tactics *[]AttackTactic `json:"tactics,omitempty"` + Techniques *[]string `json:"techniques,omitempty"` +} + +func (o *FusionAlertRuleProperties) GetLastModifiedUtcAsTime() (*time.Time, error) { + if o.LastModifiedUtc == nil { + return nil, nil + } + return dates.ParseAsFormat(o.LastModifiedUtc, "2006-01-02T15:04:05Z07:00") +} + +func (o *FusionAlertRuleProperties) SetLastModifiedUtcAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.LastModifiedUtc = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionscenarioexclusionpattern.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionscenarioexclusionpattern.go new file mode 100644 index 000000000000..98b11076d11a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionscenarioexclusionpattern.go @@ -0,0 +1,9 @@ +package alertrules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FusionScenarioExclusionPattern struct { + DateAddedInUTC string `json:"dateAddedInUTC"` + ExclusionPattern string `json:"exclusionPattern"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionsourcesettings.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionsourcesettings.go new file mode 100644 index 000000000000..dd206d437b58 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionsourcesettings.go @@ -0,0 +1,10 @@ +package alertrules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FusionSourceSettings struct { + Enabled bool `json:"enabled"` + SourceName string `json:"sourceName"` + SourceSubTypes *[]FusionSourceSubTypeSetting `json:"sourceSubTypes,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionsourcesubtypesetting.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionsourcesubtypesetting.go new file mode 100644 index 000000000000..b2561512e5f8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionsourcesubtypesetting.go @@ -0,0 +1,11 @@ +package alertrules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FusionSourceSubTypeSetting struct { + Enabled bool `json:"enabled"` + SeverityFilters FusionSubTypeSeverityFilter `json:"severityFilters"` + SourceSubTypeDisplayName *string `json:"sourceSubTypeDisplayName,omitempty"` + SourceSubTypeName string `json:"sourceSubTypeName"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionsubtypeseverityfilter.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionsubtypeseverityfilter.go new file mode 100644 index 000000000000..149cc8f8372c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionsubtypeseverityfilter.go @@ -0,0 +1,9 @@ +package alertrules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FusionSubTypeSeverityFilter struct { + Filters *[]FusionSubTypeSeverityFiltersItem `json:"filters,omitempty"` + IsSupported *bool `json:"isSupported,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionsubtypeseverityfiltersitem.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionsubtypeseverityfiltersitem.go new file mode 100644 index 000000000000..5e70b222ee7f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_fusionsubtypeseverityfiltersitem.go @@ -0,0 +1,9 @@ +package alertrules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FusionSubTypeSeverityFiltersItem struct { + Enabled bool `json:"enabled"` + Severity AlertSeverity `json:"severity"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_groupingconfiguration.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_groupingconfiguration.go new file mode 100644 index 000000000000..cb8d21f3d601 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_groupingconfiguration.go @@ -0,0 +1,14 @@ +package alertrules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GroupingConfiguration struct { + Enabled bool `json:"enabled"` + GroupByAlertDetails *[]AlertDetail `json:"groupByAlertDetails,omitempty"` + GroupByCustomDetails *[]string `json:"groupByCustomDetails,omitempty"` + GroupByEntities *[]EntityMappingType `json:"groupByEntities,omitempty"` + LookbackDuration string `json:"lookbackDuration"` + MatchingMethod MatchingMethod `json:"matchingMethod"` + ReopenClosedIncident bool `json:"reopenClosedIncident"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_incidentconfiguration.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_incidentconfiguration.go new file mode 100644 index 000000000000..53ab8b667b1c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_incidentconfiguration.go @@ -0,0 +1,9 @@ +package alertrules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type IncidentConfiguration struct { + CreateIncident bool `json:"createIncident"` + GroupingConfiguration *GroupingConfiguration `json:"groupingConfiguration,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_microsoftsecurityincidentcreationalertrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_microsoftsecurityincidentcreationalertrule.go new file mode 100644 index 000000000000..4fa227e3728a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_microsoftsecurityincidentcreationalertrule.go @@ -0,0 +1,48 @@ +package alertrules + +import ( + "encoding/json" + "fmt" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +var _ AlertRule = MicrosoftSecurityIncidentCreationAlertRule{} + +type MicrosoftSecurityIncidentCreationAlertRule struct { + Properties *MicrosoftSecurityIncidentCreationAlertRuleProperties `json:"properties,omitempty"` + + // Fields inherited from AlertRule + Etag *string `json:"etag,omitempty"` + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} + +var _ json.Marshaler = MicrosoftSecurityIncidentCreationAlertRule{} + +func (s MicrosoftSecurityIncidentCreationAlertRule) MarshalJSON() ([]byte, error) { + type wrapper MicrosoftSecurityIncidentCreationAlertRule + wrapped := wrapper(s) + encoded, err := json.Marshal(wrapped) + if err != nil { + return nil, fmt.Errorf("marshaling MicrosoftSecurityIncidentCreationAlertRule: %+v", err) + } + + var decoded map[string]interface{} + if err := json.Unmarshal(encoded, &decoded); err != nil { + return nil, fmt.Errorf("unmarshaling MicrosoftSecurityIncidentCreationAlertRule: %+v", err) + } + decoded["kind"] = "MicrosoftSecurityIncidentCreation" + + encoded, err = json.Marshal(decoded) + if err != nil { + return nil, fmt.Errorf("re-marshaling MicrosoftSecurityIncidentCreationAlertRule: %+v", err) + } + + return encoded, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_microsoftsecurityincidentcreationalertruleproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_microsoftsecurityincidentcreationalertruleproperties.go new file mode 100644 index 000000000000..428ca90f774f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_microsoftsecurityincidentcreationalertruleproperties.go @@ -0,0 +1,34 @@ +package alertrules + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type MicrosoftSecurityIncidentCreationAlertRuleProperties struct { + AlertRuleTemplateName *string `json:"alertRuleTemplateName,omitempty"` + Description *string `json:"description,omitempty"` + DisplayName string `json:"displayName"` + DisplayNamesExcludeFilter *[]string `json:"displayNamesExcludeFilter,omitempty"` + DisplayNamesFilter *[]string `json:"displayNamesFilter,omitempty"` + Enabled bool `json:"enabled"` + LastModifiedUtc *string `json:"lastModifiedUtc,omitempty"` + ProductFilter MicrosoftSecurityProductName `json:"productFilter"` + SeveritiesFilter *[]AlertSeverity `json:"severitiesFilter,omitempty"` +} + +func (o *MicrosoftSecurityIncidentCreationAlertRuleProperties) GetLastModifiedUtcAsTime() (*time.Time, error) { + if o.LastModifiedUtc == nil { + return nil, nil + } + return dates.ParseAsFormat(o.LastModifiedUtc, "2006-01-02T15:04:05Z07:00") +} + +func (o *MicrosoftSecurityIncidentCreationAlertRuleProperties) SetLastModifiedUtcAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.LastModifiedUtc = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_mlbehavioranalyticsalertrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_mlbehavioranalyticsalertrule.go new file mode 100644 index 000000000000..e49aa4ea1f01 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_mlbehavioranalyticsalertrule.go @@ -0,0 +1,48 @@ +package alertrules + +import ( + "encoding/json" + "fmt" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +var _ AlertRule = MLBehaviorAnalyticsAlertRule{} + +type MLBehaviorAnalyticsAlertRule struct { + Properties *MLBehaviorAnalyticsAlertRuleProperties `json:"properties,omitempty"` + + // Fields inherited from AlertRule + Etag *string `json:"etag,omitempty"` + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} + +var _ json.Marshaler = MLBehaviorAnalyticsAlertRule{} + +func (s MLBehaviorAnalyticsAlertRule) MarshalJSON() ([]byte, error) { + type wrapper MLBehaviorAnalyticsAlertRule + wrapped := wrapper(s) + encoded, err := json.Marshal(wrapped) + if err != nil { + return nil, fmt.Errorf("marshaling MLBehaviorAnalyticsAlertRule: %+v", err) + } + + var decoded map[string]interface{} + if err := json.Unmarshal(encoded, &decoded); err != nil { + return nil, fmt.Errorf("unmarshaling MLBehaviorAnalyticsAlertRule: %+v", err) + } + decoded["kind"] = "MLBehaviorAnalytics" + + encoded, err = json.Marshal(decoded) + if err != nil { + return nil, fmt.Errorf("re-marshaling MLBehaviorAnalyticsAlertRule: %+v", err) + } + + return encoded, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_mlbehavioranalyticsalertruleproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_mlbehavioranalyticsalertruleproperties.go new file mode 100644 index 000000000000..87834ad4f66b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_mlbehavioranalyticsalertruleproperties.go @@ -0,0 +1,33 @@ +package alertrules + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type MLBehaviorAnalyticsAlertRuleProperties struct { + AlertRuleTemplateName string `json:"alertRuleTemplateName"` + Description *string `json:"description,omitempty"` + DisplayName *string `json:"displayName,omitempty"` + Enabled bool `json:"enabled"` + LastModifiedUtc *string `json:"lastModifiedUtc,omitempty"` + Severity *AlertSeverity `json:"severity,omitempty"` + Tactics *[]AttackTactic `json:"tactics,omitempty"` + Techniques *[]string `json:"techniques,omitempty"` +} + +func (o *MLBehaviorAnalyticsAlertRuleProperties) GetLastModifiedUtcAsTime() (*time.Time, error) { + if o.LastModifiedUtc == nil { + return nil, nil + } + return dates.ParseAsFormat(o.LastModifiedUtc, "2006-01-02T15:04:05Z07:00") +} + +func (o *MLBehaviorAnalyticsAlertRuleProperties) SetLastModifiedUtcAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.LastModifiedUtc = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_nrtalertrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_nrtalertrule.go new file mode 100644 index 000000000000..d0d096cbfc58 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_nrtalertrule.go @@ -0,0 +1,48 @@ +package alertrules + +import ( + "encoding/json" + "fmt" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +var _ AlertRule = NrtAlertRule{} + +type NrtAlertRule struct { + Properties *NrtAlertRuleProperties `json:"properties,omitempty"` + + // Fields inherited from AlertRule + Etag *string `json:"etag,omitempty"` + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} + +var _ json.Marshaler = NrtAlertRule{} + +func (s NrtAlertRule) MarshalJSON() ([]byte, error) { + type wrapper NrtAlertRule + wrapped := wrapper(s) + encoded, err := json.Marshal(wrapped) + if err != nil { + return nil, fmt.Errorf("marshaling NrtAlertRule: %+v", err) + } + + var decoded map[string]interface{} + if err := json.Unmarshal(encoded, &decoded); err != nil { + return nil, fmt.Errorf("unmarshaling NrtAlertRule: %+v", err) + } + decoded["kind"] = "NRT" + + encoded, err = json.Marshal(decoded) + if err != nil { + return nil, fmt.Errorf("re-marshaling NrtAlertRule: %+v", err) + } + + return encoded, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_nrtalertruleproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_nrtalertruleproperties.go new file mode 100644 index 000000000000..8c8669017c93 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_nrtalertruleproperties.go @@ -0,0 +1,43 @@ +package alertrules + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NrtAlertRuleProperties struct { + AlertDetailsOverride *AlertDetailsOverride `json:"alertDetailsOverride,omitempty"` + AlertRuleTemplateName *string `json:"alertRuleTemplateName,omitempty"` + CustomDetails *map[string]string `json:"customDetails,omitempty"` + Description *string `json:"description,omitempty"` + DisplayName string `json:"displayName"` + Enabled bool `json:"enabled"` + EntityMappings *[]EntityMapping `json:"entityMappings,omitempty"` + EventGroupingSettings *EventGroupingSettings `json:"eventGroupingSettings,omitempty"` + IncidentConfiguration *IncidentConfiguration `json:"incidentConfiguration,omitempty"` + LastModifiedUtc *string `json:"lastModifiedUtc,omitempty"` + Query string `json:"query"` + SentinelEntitiesMappings *[]SentinelEntityMapping `json:"sentinelEntitiesMappings,omitempty"` + Severity AlertSeverity `json:"severity"` + SuppressionDuration string `json:"suppressionDuration"` + SuppressionEnabled bool `json:"suppressionEnabled"` + Tactics *[]AttackTactic `json:"tactics,omitempty"` + Techniques *[]string `json:"techniques,omitempty"` + TemplateVersion *string `json:"templateVersion,omitempty"` +} + +func (o *NrtAlertRuleProperties) GetLastModifiedUtcAsTime() (*time.Time, error) { + if o.LastModifiedUtc == nil { + return nil, nil + } + return dates.ParseAsFormat(o.LastModifiedUtc, "2006-01-02T15:04:05Z07:00") +} + +func (o *NrtAlertRuleProperties) SetLastModifiedUtcAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.LastModifiedUtc = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_scheduledalertrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_scheduledalertrule.go new file mode 100644 index 000000000000..cf91bcec4f27 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_scheduledalertrule.go @@ -0,0 +1,48 @@ +package alertrules + +import ( + "encoding/json" + "fmt" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +var _ AlertRule = ScheduledAlertRule{} + +type ScheduledAlertRule struct { + Properties *ScheduledAlertRuleProperties `json:"properties,omitempty"` + + // Fields inherited from AlertRule + Etag *string `json:"etag,omitempty"` + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} + +var _ json.Marshaler = ScheduledAlertRule{} + +func (s ScheduledAlertRule) MarshalJSON() ([]byte, error) { + type wrapper ScheduledAlertRule + wrapped := wrapper(s) + encoded, err := json.Marshal(wrapped) + if err != nil { + return nil, fmt.Errorf("marshaling ScheduledAlertRule: %+v", err) + } + + var decoded map[string]interface{} + if err := json.Unmarshal(encoded, &decoded); err != nil { + return nil, fmt.Errorf("unmarshaling ScheduledAlertRule: %+v", err) + } + decoded["kind"] = "Scheduled" + + encoded, err = json.Marshal(decoded) + if err != nil { + return nil, fmt.Errorf("re-marshaling ScheduledAlertRule: %+v", err) + } + + return encoded, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_scheduledalertruleproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_scheduledalertruleproperties.go new file mode 100644 index 000000000000..846c2acb14d7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_scheduledalertruleproperties.go @@ -0,0 +1,47 @@ +package alertrules + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ScheduledAlertRuleProperties struct { + AlertDetailsOverride *AlertDetailsOverride `json:"alertDetailsOverride,omitempty"` + AlertRuleTemplateName *string `json:"alertRuleTemplateName,omitempty"` + CustomDetails *map[string]string `json:"customDetails,omitempty"` + Description *string `json:"description,omitempty"` + DisplayName string `json:"displayName"` + Enabled bool `json:"enabled"` + EntityMappings *[]EntityMapping `json:"entityMappings,omitempty"` + EventGroupingSettings *EventGroupingSettings `json:"eventGroupingSettings,omitempty"` + IncidentConfiguration *IncidentConfiguration `json:"incidentConfiguration,omitempty"` + LastModifiedUtc *string `json:"lastModifiedUtc,omitempty"` + Query string `json:"query"` + QueryFrequency string `json:"queryFrequency"` + QueryPeriod string `json:"queryPeriod"` + SentinelEntitiesMappings *[]SentinelEntityMapping `json:"sentinelEntitiesMappings,omitempty"` + Severity AlertSeverity `json:"severity"` + SuppressionDuration string `json:"suppressionDuration"` + SuppressionEnabled bool `json:"suppressionEnabled"` + Tactics *[]AttackTactic `json:"tactics,omitempty"` + Techniques *[]string `json:"techniques,omitempty"` + TemplateVersion *string `json:"templateVersion,omitempty"` + TriggerOperator TriggerOperator `json:"triggerOperator"` + TriggerThreshold int64 `json:"triggerThreshold"` +} + +func (o *ScheduledAlertRuleProperties) GetLastModifiedUtcAsTime() (*time.Time, error) { + if o.LastModifiedUtc == nil { + return nil, nil + } + return dates.ParseAsFormat(o.LastModifiedUtc, "2006-01-02T15:04:05Z07:00") +} + +func (o *ScheduledAlertRuleProperties) SetLastModifiedUtcAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.LastModifiedUtc = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_sentinelentitymapping.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_sentinelentitymapping.go new file mode 100644 index 000000000000..356dda0094fe --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_sentinelentitymapping.go @@ -0,0 +1,8 @@ +package alertrules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SentinelEntityMapping struct { + ColumnName *string `json:"columnName,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_threatintelligencealertrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_threatintelligencealertrule.go new file mode 100644 index 000000000000..fe9fc75c2e6e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_threatintelligencealertrule.go @@ -0,0 +1,48 @@ +package alertrules + +import ( + "encoding/json" + "fmt" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +var _ AlertRule = ThreatIntelligenceAlertRule{} + +type ThreatIntelligenceAlertRule struct { + Properties *ThreatIntelligenceAlertRuleProperties `json:"properties,omitempty"` + + // Fields inherited from AlertRule + Etag *string `json:"etag,omitempty"` + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} + +var _ json.Marshaler = ThreatIntelligenceAlertRule{} + +func (s ThreatIntelligenceAlertRule) MarshalJSON() ([]byte, error) { + type wrapper ThreatIntelligenceAlertRule + wrapped := wrapper(s) + encoded, err := json.Marshal(wrapped) + if err != nil { + return nil, fmt.Errorf("marshaling ThreatIntelligenceAlertRule: %+v", err) + } + + var decoded map[string]interface{} + if err := json.Unmarshal(encoded, &decoded); err != nil { + return nil, fmt.Errorf("unmarshaling ThreatIntelligenceAlertRule: %+v", err) + } + decoded["kind"] = "ThreatIntelligence" + + encoded, err = json.Marshal(decoded) + if err != nil { + return nil, fmt.Errorf("re-marshaling ThreatIntelligenceAlertRule: %+v", err) + } + + return encoded, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_threatintelligencealertruleproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_threatintelligencealertruleproperties.go new file mode 100644 index 000000000000..498f10795251 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/model_threatintelligencealertruleproperties.go @@ -0,0 +1,33 @@ +package alertrules + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ThreatIntelligenceAlertRuleProperties struct { + AlertRuleTemplateName string `json:"alertRuleTemplateName"` + Description *string `json:"description,omitempty"` + DisplayName *string `json:"displayName,omitempty"` + Enabled bool `json:"enabled"` + LastModifiedUtc *string `json:"lastModifiedUtc,omitempty"` + Severity *AlertSeverity `json:"severity,omitempty"` + Tactics *[]AttackTactic `json:"tactics,omitempty"` + Techniques *[]string `json:"techniques,omitempty"` +} + +func (o *ThreatIntelligenceAlertRuleProperties) GetLastModifiedUtcAsTime() (*time.Time, error) { + if o.LastModifiedUtc == nil { + return nil, nil + } + return dates.ParseAsFormat(o.LastModifiedUtc, "2006-01-02T15:04:05Z07:00") +} + +func (o *ThreatIntelligenceAlertRuleProperties) SetLastModifiedUtcAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.LastModifiedUtc = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/predicates.go new file mode 100644 index 000000000000..20dada025237 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/predicates.go @@ -0,0 +1,12 @@ +package alertrules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AlertRuleOperationPredicate struct { +} + +func (p AlertRuleOperationPredicate) Matches(input AlertRule) bool { + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/version.go new file mode 100644 index 000000000000..0eed78e43ceb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules/version.go @@ -0,0 +1,12 @@ +package alertrules + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2022-10-01-preview" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/alertrules/%s", defaultApiVersion) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 64e89d8ffd65..7625db57b11b 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -488,6 +488,7 @@ github.com/hashicorp/go-azure-sdk/resource-manager/search/2020-03-13/querykeys github.com/hashicorp/go-azure-sdk/resource-manager/search/2020-03-13/services github.com/hashicorp/go-azure-sdk/resource-manager/search/2020-08-01/sharedprivatelinkresources github.com/hashicorp/go-azure-sdk/resource-manager/security/2022-03-01/pricings +github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-10-01-preview/alertrules github.com/hashicorp/go-azure-sdk/resource-manager/securityinsights/2022-11-01/sentinelonboardingstates github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule