Skip to content

Commit

Permalink
fix enforce_on_key_configs (GoogleCloudPlatform#8165)
Browse files Browse the repository at this point in the history
* fix enforce_on_key_configs

* add updatemask

---------

Co-authored-by: Edward Sun <sunedward@google.com>
  • Loading branch information
2 people authored and DanielRieske committed Aug 2, 2023
1 parent ccd5ed6 commit 3d8e31d
Show file tree
Hide file tree
Showing 2 changed files with 144 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import (
"context"
"fmt"
"log"
<% if version != 'ga' -%>
"strings"
<% end -%>

"time"

Expand Down Expand Up @@ -280,7 +283,6 @@ func ResourceComputeSecurityPolicy() *schema.Resource {
"enforce_on_key_configs": {
Type: schema.TypeList,
Description: `Enforce On Key Config of this security policy`,
ForceNew: true,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
Expand Down Expand Up @@ -772,7 +774,7 @@ func resourceComputeSecurityPolicyUpdate(d *schema.ResourceData, meta interface{
}
}


<% if version == 'ga' -%>
if d.HasChange("rule") {
o, n := d.GetChange("rule")
oSet := o.(*schema.Set)
Expand All @@ -788,12 +790,7 @@ func resourceComputeSecurityPolicyUpdate(d *schema.ResourceData, meta interface{
priority := int64(rule.(map[string]interface{})["priority"].(int))
nPriorities[priority] = true
if !oPriorities[priority] {
<% if version == 'ga' -%>
client := config.NewComputeClient(userAgent)
<% else -%>
client := config.NewComputeClient(userAgent)
<% end -%>

// If the rule is in new and its priority does not exist in old, then add it.
op, err := client.SecurityPolicies.AddRule(project, sp, expandSecurityPolicyRule(rule)).Do()

Expand All @@ -806,11 +803,7 @@ func resourceComputeSecurityPolicyUpdate(d *schema.ResourceData, meta interface{
return err
}
} else if !oSet.Contains(rule) {
<% if version == 'ga' -%>
client := config.NewComputeClient(userAgent)
<% else -%>
client := config.NewComputeClient(userAgent)
<% end -%>

// If the rule is in new, and its priority is in old, but its hash is different than the one in old, update it.
op, err := client.SecurityPolicies.PatchRule(project, sp, expandSecurityPolicyRule(rule)).Priority(priority).Do()
Expand All @@ -829,11 +822,109 @@ func resourceComputeSecurityPolicyUpdate(d *schema.ResourceData, meta interface{
for _, rule := range oSet.List() {
priority := int64(rule.(map[string]interface{})["priority"].(int))
if !nPriorities[priority] {
<% if version == 'ga' -%>
client := config.NewComputeClient(userAgent)
<% else -%>

// If the rule's priority is in old but not new, remove it.
op, err := client.SecurityPolicies.RemoveRule(project, sp).Priority(priority).Do()

if err != nil {
return errwrap.Wrapf(fmt.Sprintf("Error updating SecurityPolicy %q: {{err}}", sp), err)
}

err = ComputeOperationWaitTime(config, op, project, fmt.Sprintf("Updating SecurityPolicy %q", sp), userAgent, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return err
}
}
}
}

<% else -%>
if d.HasChange("rule") {
o, n := d.GetChange("rule")
oSet := o.(*schema.Set)
nSet := n.(*schema.Set)

oPriorities := map[int64]bool{}
nPriorities := map[int64]bool{}
oRules := make(map[int64]map[string]interface{})
nRules := make(map[int64]map[string]interface{})

for _, rule := range oSet.List() {
oPriorities[int64(rule.(map[string]interface{})["priority"].(int))] = true
oRules[int64(rule.(map[string]interface{})["priority"].(int))] = rule.(map[string]interface{})
}

for _, rule := range nSet.List() {
nRules[int64(rule.(map[string]interface{})["priority"].(int))] = rule.(map[string]interface{})
priority := int64(rule.(map[string]interface{})["priority"].(int))
nPriorities[priority] = true

if !oPriorities[priority] {
client := config.NewComputeClient(userAgent)

// If the rule is in new and its priority does not exist in old, then add it.
op, err := client.SecurityPolicies.AddRule(project, sp, expandSecurityPolicyRule(rule)).Do()

if err != nil {
return errwrap.Wrapf(fmt.Sprintf("Error updating SecurityPolicy %q: {{err}}", sp), err)
}

err = ComputeOperationWaitTime(config, op, project, fmt.Sprintf("Updating SecurityPolicy %q", sp), userAgent, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return err
}
} else if !oSet.Contains(rule) {

oMap := make(map[string]interface{})
nMap := make(map[string]interface{})

updateMask := []string{}

if oRules[priority]["rate_limit_options"] != nil {
for _, oValue := range oRules[priority]["rate_limit_options"].([]interface{}) {
oMap = oValue.(map[string]interface{})
}
}

if nRules[priority]["rate_limit_options"] != nil {
for _, nValue := range nRules[priority]["rate_limit_options"].([]interface{}) {
nMap = nValue.(map[string]interface{})
}
}

if fmt.Sprintf("%v", oMap["enforce_on_key"]) != fmt.Sprintf("%v", nMap["enforce_on_key"]) {
updateMask = append(updateMask, "rate_limit_options.enforce_on_key")
}

if fmt.Sprintf("%v", oMap["enforce_on_key_configs"]) != fmt.Sprintf("%v", nMap["enforce_on_key_configs"]) {
updateMask = append(updateMask, "rate_limit_options.enforce_on_key_configs")
}

if fmt.Sprintf("%v", oMap["enforce_on_key_name"]) != fmt.Sprintf("%v", nMap["enforce_on_key_name"]) {
updateMask = append(updateMask, "rate_limit_options.enforce_on_key_name")
}

client := config.NewComputeClient(userAgent)

// If the rule is in new, and its priority is in old, but its hash is different than the one in old, update it.
op, err := client.SecurityPolicies.PatchRule(project, sp, expandSecurityPolicyRule(rule)).Priority(priority).UpdateMask(strings.Join(updateMask, ",")).Do()

if err != nil {
return errwrap.Wrapf(fmt.Sprintf("Error updating SecurityPolicy %q: {{err}}", sp), err)
}

err = ComputeOperationWaitTime(config, op, project, fmt.Sprintf("Updating SecurityPolicy %q", sp), userAgent, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return err
}
}
}

for _, rule := range oSet.List() {
priority := int64(rule.(map[string]interface{})["priority"].(int))
if !nPriorities[priority] {
client := config.NewComputeClient(userAgent)
<% end -%>

// If the rule's priority is in old but not new, remove it.
op, err := client.SecurityPolicies.RemoveRule(project, sp).Priority(priority).Do()
Expand All @@ -849,6 +940,7 @@ func resourceComputeSecurityPolicyUpdate(d *schema.ResourceData, meta interface{
}
}
}
<% end -%>

return resourceComputeSecurityPolicyRead(d, meta)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,14 @@ func TestAccComputeSecurityPolicy_EnforceOnKeyUpdates(t *testing.T) {
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t),
CheckDestroy: testAccCheckComputeSecurityPolicyDestroyProducer(t),
Steps: []resource.TestStep{
{
Config: testAccComputeSecurityPolicy_withRateLimitOptions_withoutRateLimitOptions(spName),
},
{
ResourceName: "google_compute_security_policy.policy",
ImportState: true,
ImportStateVerify: true,
},
{
Config: testAccComputeSecurityPolicy_withRateLimitOptions_withEnforceOnKeyName(spName),
},
Expand Down Expand Up @@ -396,10 +404,19 @@ func TestAccComputeSecurityPolicy_EnforceOnKeyUpdates(t *testing.T) {
ImportState: true,
ImportStateVerify: true,
},
{
Config: testAccComputeSecurityPolicy_withRateLimitOptions_withEnforceOnKeyName(spName),
},
{
ResourceName: "google_compute_security_policy.policy",
ImportState: true,
ImportStateVerify: true,
},
},
})
}


<% end -%>

func TestAccComputeSecurityPolicy_withRecaptchaOptionsConfig(t *testing.T) {
Expand Down Expand Up @@ -1267,6 +1284,27 @@ resource "google_compute_security_policy" "policy" {
`, spName)
}

func testAccComputeSecurityPolicy_withRateLimitOptions_withoutRateLimitOptions(spName string) string {
return fmt.Sprintf(`
resource "google_compute_security_policy" "policy" {
name = "%s"
description = "throttle rule with enforce_on_key_configs"

rule {
action = "deny(403)"
priority = "2147483647"
match {
versioned_expr = "SRC_IPS_V1"
config {
src_ip_ranges = ["*"]
}
}
description = "default rule"
}
}
`, spName)
}

func testAccComputeSecurityPolicy_withRateLimitOptions_withEnforceOnKeyName(spName string) string {
return fmt.Sprintf(`
resource "google_compute_security_policy" "policy" {
Expand Down

0 comments on commit 3d8e31d

Please sign in to comment.