Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Fix unexpected crashes when using cloudflare_notification_policy with a filters attribute #1520

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .changelog/1520.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:bug
resource/cloudflare_notification_policy: Fix unexpected crashes when using cloudflare_notification_policy with a filters attribute
```
32 changes: 29 additions & 3 deletions cloudflare/resource_cloudflare_notification_policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,22 @@ func resourceCloudflareNotificationPolicyRead(d *schema.ResourceData, meta inter
d.Set("enabled", policy.Result.Enabled)
d.Set("alert_type", policy.Result.AlertType)
d.Set("description", policy.Result.Description)
d.Set("filters", policy.Result.Filters)
d.Set("conditions", policy.Result.Conditions)
d.Set("created", policy.Result.Created.Format(time.RFC3339))
d.Set("modified", policy.Result.Modified.Format(time.RFC3339))

if err := d.Set("filters", setNotificationFilters(policy.Result.Filters)); err != nil {
return fmt.Errorf("failed to set filters: %s", err)
}

if err := d.Set("email_integration", setNotificationMechanisms(policy.Result.Mechanisms["email"])); err != nil {
return fmt.Errorf("failed to set email integration: %s", err)
}

if err := d.Set("pagerduty_integration", setNotificationMechanisms(policy.Result.Mechanisms["pagerduty"])); err != nil {
return fmt.Errorf("failed to set pagerduty integration: %s", err)
}

if err := d.Set("webhooks_integration", setNotificationMechanisms(policy.Result.Mechanisms["webhooks"])); err != nil {
return fmt.Errorf("failed to set webhooks integration: %s", err)
}
Expand Down Expand Up @@ -124,7 +129,6 @@ func buildNotificationPolicy(d *schema.ResourceData) cloudflare.NotificationPoli
notificationPolicy := cloudflare.NotificationPolicy{}
notificationPolicy.Mechanisms = make(map[string]cloudflare.NotificationMechanismIntegrations)
notificationPolicy.Conditions = make(map[string]interface{})
notificationPolicy.Filters = make(map[string][]string)

if name, ok := d.GetOk("name"); ok {
notificationPolicy.Name = name.(string)
Expand Down Expand Up @@ -155,7 +159,7 @@ func buildNotificationPolicy(d *schema.ResourceData) cloudflare.NotificationPoli
}

if filters, ok := d.GetOk("filters"); ok {
notificationPolicy.Filters = filters.(map[string][]string)
notificationPolicy.Filters = getNotificationFilters(filters.(*schema.Set))
}

if conditions, ok := d.GetOk("conditions"); ok {
Expand Down Expand Up @@ -192,3 +196,25 @@ func setNotificationMechanisms(md []cloudflare.NotificationMechanismData) *schem

return schema.NewSet(schema.HashResource(mechanismData), mechanisms)
}

func getNotificationFilters(s *schema.Set) map[string][]string {
filters := make(map[string][]string)

for _, v := range s.List() {
for key, set := range v.(map[string]interface{}) {
filters[key] = expandInterfaceToStringList(set.(*schema.Set).List())
}
}

return filters
}

func setNotificationFilters(m map[string][]string) []interface{} {
filters := map[string]*schema.Set{}

for k, v := range m {
filters[k] = expandStringListToSet(v)
}

return []interface{}{filters}
}
102 changes: 101 additions & 1 deletion cloudflare/resource_cloudflare_notification_policy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccCloudflareNotificationPolicy(t *testing.T) {
func TestAccCloudflareNotificationPolicy_Basic(t *testing.T) {
// Temporarily unset CLOUDFLARE_API_TOKEN if it is set as the notification
// service does not yet support the API tokens and it results in
// misleading state error messages.
Expand Down Expand Up @@ -84,3 +84,103 @@ func testCheckCloudflareNotificationPolicyUpdated(resName, policyName, policyDes
}
}`, resName, policyName, policyDesc, accountID)
}

func TestAccCloudflareNotificationPolicy_WithFiltersAttribute(t *testing.T) {
// Temporarily unset CLOUDFLARE_API_TOKEN if it is set as the notification
// service does not yet support the API tokens and it results in
// misleading state error messages.
if os.Getenv("CLOUDFLARE_API_TOKEN") != "" {
defer func(apiToken string) {
os.Setenv("CLOUDFLARE_API_TOKEN", apiToken)
}(os.Getenv("CLOUDFLARE_API_TOKEN"))
os.Setenv("CLOUDFLARE_API_TOKEN", "")
}

rnd := generateRandomResourceName()
resourceName := "cloudflare_notification_policy." + rnd
updatedPolicyName := "updated Advanced Security Events Alert from terraform provider"
updatedPolicyDesc := "updated description"
accountID := os.Getenv("CLOUDFLARE_ACCOUNT_ID")
zoneID := os.Getenv("CLOUDFLARE_ZONE_ID")

resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheckAccount(t)
},
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testCheckCloudflareNotificationPolicyWithFiltersAttribute(rnd, accountID, zoneID),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(resourceName, "name", "test Advanced Security Events Alert from terraform provider"),
resource.TestCheckResourceAttr(resourceName, "description", "test description"),
resource.TestCheckResourceAttr(resourceName, "enabled", "true"),
resource.TestCheckResourceAttr(resourceName, "alert_type", "clickhouse_alert_fw_ent_anomaly"),
resource.TestCheckResourceAttr(resourceName, "account_id", accountID),
resource.TestCheckResourceAttr(resourceName, "filters.0.services.#", "1"),
resource.TestCheckResourceAttr(resourceName, "filters.0.services.0", "waf"),
Copy link
Member

Choose a reason for hiding this comment

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

services.0 isn't directly addressable as the index is a hash of the items; you'll need to use TestCheckTypeSetElemAttr instead.

resource.TestCheckResourceAttr(resourceName, "filters.0.zones.#", "1"),
resource.TestCheckResourceAttr(resourceName, "filters.0.zones.0", zoneID),
),
},
{
Config: testCheckCloudflareNotificationPolicyWithFiltersAttributeUpdated(rnd, updatedPolicyName, updatedPolicyDesc, accountID, zoneID),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(resourceName, "name", updatedPolicyName),
resource.TestCheckResourceAttr(resourceName, "description", updatedPolicyDesc),
resource.TestCheckResourceAttr(resourceName, "enabled", "true"),
resource.TestCheckResourceAttr(resourceName, "alert_type", "clickhouse_alert_fw_ent_anomaly"),
resource.TestCheckResourceAttr(resourceName, "account_id", accountID),
resource.TestCheckResourceAttr(resourceName, "filters.0.services.#", "2"),
resource.TestCheckResourceAttr(resourceName, "filters.0.services.0", "waf"),
resource.TestCheckResourceAttr(resourceName, "filters.0.services.1", "firewallrules"),
resource.TestCheckResourceAttr(resourceName, "filters.0.zones.#", "1"),
resource.TestCheckResourceAttr(resourceName, "filters.0.zones.0", zoneID),
),
},
},
})
}

func testCheckCloudflareNotificationPolicyWithFiltersAttribute(name, accountID, zoneID string) string {
return fmt.Sprintf(`
resource "cloudflare_notification_policy" "%[1]s" {
name = "test Advanced Security Events Alert from terraform provider"
account_id = "%[2]s"
description = "test description"
enabled = true
alert_type = "clickhouse_alert_fw_ent_anomaly"
email_integration {
name = ""
id = "[email protected]"
}
filters {
services = [
"waf",
]
zones = ["%[3]s"]
}
}`, name, accountID, zoneID)
}

func testCheckCloudflareNotificationPolicyWithFiltersAttributeUpdated(resName, policyName, policyDesc, accountID, zoneID string) string {
return fmt.Sprintf(`
resource "cloudflare_notification_policy" "%[1]s" {
name = "%[2]s"
account_id = "%[4]s"
description = "%[3]s"
enabled = true
alert_type = "clickhouse_alert_fw_ent_anomaly"
email_integration {
name = ""
id = "[email protected]"
}
filters {
services = [
"waf",
"firewallrules",
]
zones = ["%[5]s"]
}
}`, resName, policyName, policyDesc, accountID, zoneID)
}
23 changes: 19 additions & 4 deletions cloudflare/schema_cloudflare_notification_policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,26 @@ func resourceCloudflareNotificationPolicySchema() map[string]*schema.Schema {
Required: true,
},
"filters": {
Type: schema.TypeMap,
Type: schema.TypeSet,
Copy link
Member

Choose a reason for hiding this comment

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

you still want this as a TypeList otherwise it won't be addressable as filters.0...

Suggested change
Type: schema.TypeSet,
Type: schema.TypeList,

Optional: true,
Elem: &schema.Schema{
Type: schema.TypeList,
Elem: schema.TypeString,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"zones": {
Type: schema.TypeSet,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Optional: true,
},
"services": {
Type: schema.TypeSet,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Optional: true,
},
},
},
},
"created": {
Expand Down