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

r/wafv2_web_acl_logging_configuration: update redacted_fields schema definition #14319

Merged
merged 7 commits into from
Mar 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changelog/14319.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
```release-note:bug
resource/aws_wafv2_web_acl_logging_configuration: Ensure `redacted_fields` are applied to the resource
```

```release-note:note
resource/aws_wafv2_web_acl_logging_configuration: The `redacted_fields` configuration block `all_query_arguments`, `body`, and `single_query_argument` arguments have been deprecated to match the WAF API documentation
```
198 changes: 185 additions & 13 deletions aws/resource_aws_wafv2_web_acl_logging_configuration.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package aws

import (
"bytes"
"fmt"
"log"
"regexp"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/wafv2"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode"
)

func resourceAwsWafv2WebACLLoggingConfiguration() *schema.Resource {
Expand Down Expand Up @@ -34,11 +38,68 @@ func resourceAwsWafv2WebACLLoggingConfiguration() *schema.Resource {
Description: "AWS Kinesis Firehose Delivery Stream ARNs",
},
"redacted_fields": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 100,
Elem: wafv2FieldToMatchBaseSchema(),
Description: "Parts of the request to exclude from logs",
// To allow this argument and its nested fields with Empty Schemas (e.g. "method")
// to be correctly interpreted, this argument must be of type List,
// otherwise, at apply-time a field configured as an empty block
// (e.g. body {}) will result in a nil redacted_fields attribute
Type: schema.TypeList,
Optional: true,
MaxItems: 100,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// TODO: remove attributes marked as Deprecated
// as they are not supported by the WAFv2 API
// in the context of WebACL Logging Configurations
"all_query_arguments": wafv2EmptySchemaDeprecated(),
Copy link
Contributor Author

Choose a reason for hiding this comment

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

maybe we can skip this deprecation part (since they don't function as is?)

"body": wafv2EmptySchemaDeprecated(),
"method": wafv2EmptySchema(),
"query_string": wafv2EmptySchema(),
"single_header": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.All(
validation.StringLenBetween(1, 40),
// The value is returned in lower case by the API.
// Trying to solve it with StateFunc and/or DiffSuppressFunc resulted in hash problem of the rule field or didn't work.
validation.StringMatch(regexp.MustCompile(`^[a-z0-9-_]+$`), "must contain only lowercase alphanumeric characters, underscores, and hyphens"),
),
Deprecated: "Not supported by WAFv2 API",
},
},
},
},
"single_query_argument": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.All(
validation.StringLenBetween(1, 30),
// The value is returned in lower case by the API.
// Trying to solve it with StateFunc and/or DiffSuppressFunc resulted in hash problem of the rule field or didn't work.
validation.StringMatch(regexp.MustCompile(`^[a-z0-9-_]+$`), "must contain only lowercase alphanumeric characters, underscores, and hyphens"),
),
Deprecated: "Not supported by WAFv2 API",
},
},
},
Deprecated: "Not supported by WAFv2 API",
},
"uri_path": wafv2EmptySchema(),
},
},
Description: "Parts of the request to exclude from logs",
DiffSuppressFunc: suppressRedactedFieldsDiff,
},
"resource_arn": {
Type: schema.TypeString,
Expand All @@ -60,8 +121,8 @@ func resourceAwsWafv2WebACLLoggingConfigurationPut(d *schema.ResourceData, meta
ResourceArn: aws.String(resourceArn),
}

if v, ok := d.GetOk("redacted_fields"); ok && v.(*schema.Set).Len() > 0 {
config.RedactedFields = expandWafv2RedactedFields(v.(*schema.Set).List())
if v, ok := d.GetOk("redacted_fields"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil {
config.RedactedFields = expandWafv2RedactedFields(v.([]interface{}))
} else {
config.RedactedFields = []*wafv2.FieldToMatch{}
}
Expand Down Expand Up @@ -126,18 +187,129 @@ func resourceAwsWafv2WebACLLoggingConfigurationDelete(d *schema.ResourceData, me
return nil
}

func flattenWafv2RedactedFields(fields []*wafv2.FieldToMatch) []map[string]interface{} {
redactedFields := make([]map[string]interface{}, 0, len(fields))
func expandWafv2RedactedFields(fields []interface{}) []*wafv2.FieldToMatch {
redactedFields := make([]*wafv2.FieldToMatch, 0, len(fields))
for _, field := range fields {
redactedFields = append(redactedFields, flattenWafv2FieldToMatch(field).([]interface{})[0].(map[string]interface{}))
redactedFields = append(redactedFields, expandWafv2RedactedField(field))
}
return redactedFields
}

func expandWafv2RedactedFields(fields []interface{}) []*wafv2.FieldToMatch {
redactedFields := make([]*wafv2.FieldToMatch, 0, len(fields))
func expandWafv2RedactedField(field interface{}) *wafv2.FieldToMatch {
m := field.(map[string]interface{})

f := &wafv2.FieldToMatch{}

// While the FieldToMatch struct allows more than 1 of its fields to be set,
// the WAFv2 API does not. In addition, in the context of Logging Configuration requests,
// the WAFv2 API only supports the following redacted fields.
// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/14244
if v, ok := m["method"]; ok && len(v.([]interface{})) > 0 {
f.Method = &wafv2.Method{}
}

if v, ok := m["query_string"]; ok && len(v.([]interface{})) > 0 {
f.QueryString = &wafv2.QueryString{}
}

if v, ok := m["single_header"]; ok && len(v.([]interface{})) > 0 {
f.SingleHeader = expandWafv2SingleHeader(m["single_header"].([]interface{}))
}

if v, ok := m["uri_path"]; ok && len(v.([]interface{})) > 0 {
f.UriPath = &wafv2.UriPath{}
}

return f
}

func flattenWafv2RedactedFields(fields []*wafv2.FieldToMatch) []interface{} {
redactedFields := make([]interface{}, 0, len(fields))
for _, field := range fields {
redactedFields = append(redactedFields, expandWafv2FieldToMatch([]interface{}{field}))
redactedFields = append(redactedFields, flattenWafv2RedactedField(field))
}
return redactedFields
}

func flattenWafv2RedactedField(f *wafv2.FieldToMatch) map[string]interface{} {
m := map[string]interface{}{}

if f == nil {
return m
}

// In the context of Logging Configuration requests,
// the WAFv2 API only supports the following redacted fields.
// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/14244
if f.Method != nil {
m["method"] = make([]map[string]interface{}, 1)
}

if f.QueryString != nil {
m["query_string"] = make([]map[string]interface{}, 1)
}

if f.SingleHeader != nil {
m["single_header"] = flattenWafv2SingleHeader(f.SingleHeader)
}

if f.UriPath != nil {
m["uri_path"] = make([]map[string]interface{}, 1)
}

return m
}

// redactedFieldsHash takes a map[string]interface{} as input and generates a
// unique hashcode, taking into account keys defined in the resource's schema
// are present even if not explicitly configured
func redactedFieldsHash(v interface{}) int {
var buf bytes.Buffer
m, ok := v.(map[string]interface{})
if !ok {
return 0
}
if v, ok := m["method"].([]interface{}); ok && len(v) > 0 {
buf.WriteString("method-")
}
if v, ok := m["query_string"].([]interface{}); ok && len(v) > 0 {
buf.WriteString("query_string-")
}
if v, ok := m["uri_path"].([]interface{}); ok && len(v) > 0 {
buf.WriteString("uri_path-")
}
if v, ok := m["single_header"].([]interface{}); ok && len(v) > 0 {
sh, ok := v[0].(map[string]interface{})
if ok {
if name, ok := sh["name"].(string); ok {
buf.WriteString(fmt.Sprintf("%s-", name))
}
}
}

return hashcode.String(buf.String())
}

func suppressRedactedFieldsDiff(k, old, new string, d *schema.ResourceData) bool {
o, n := d.GetChange("redacted_fields")
oList := o.([]interface{})
nList := n.([]interface{})

if len(oList) == 0 && len(nList) == 0 {
return true
}

if len(oList) == 0 && len(nList) != 0 {
// account for empty block
return nList[0] == nil
}

if len(oList) != 0 && len(nList) == 0 {
// account for empty block
return oList[0] == nil
}

oldSet := schema.NewSet(redactedFieldsHash, oList)
newSet := schema.NewSet(redactedFieldsHash, nList)
return oldSet.Equal(newSet)
}
Loading