Skip to content

Commit

Permalink
New Resource: aws_wafregional_sql_injection_match_set (#1013)
Browse files Browse the repository at this point in the history
* Add support for resource_aws_wafregional_sql_injection_match_set

* Implement feedback and clean up code
  • Loading branch information
DennyLoko authored and radeksimko committed Mar 15, 2018
1 parent cef9081 commit f617d80
Show file tree
Hide file tree
Showing 5 changed files with 600 additions and 0 deletions.
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,7 @@ func Provider() terraform.ResourceProvider {
"aws_waf_geo_match_set": resourceAwsWafGeoMatchSet(),
"aws_wafregional_byte_match_set": resourceAwsWafRegionalByteMatchSet(),
"aws_wafregional_ipset": resourceAwsWafRegionalIPSet(),
"aws_wafregional_sql_injection_match_set": resourceAwsWafRegionalSqlInjectionMatchSet(),
"aws_wafregional_xss_match_set": resourceAwsWafRegionalXssMatchSet(),
"aws_batch_compute_environment": resourceAwsBatchComputeEnvironment(),
"aws_batch_job_definition": resourceAwsBatchJobDefinition(),
Expand Down
233 changes: 233 additions & 0 deletions aws/resource_aws_wafregional_sql_injection_match_set.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
package aws

import (
"bytes"
"fmt"
"log"
"strings"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/waf"
"github.com/aws/aws-sdk-go/service/wafregional"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsWafRegionalSqlInjectionMatchSet() *schema.Resource {
return &schema.Resource{
Create: resourceAwsWafRegionalSqlInjectionMatchSetCreate,
Read: resourceAwsWafRegionalSqlInjectionMatchSetRead,
Update: resourceAwsWafRegionalSqlInjectionMatchSetUpdate,
Delete: resourceAwsWafRegionalSqlInjectionMatchSetDelete,

Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"sql_injection_match_tuple": {
Type: schema.TypeSet,
Optional: true,
Set: resourceAwsWafRegionalSqlInjectionMatchSetTupleHash,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"field_to_match": {
Type: schema.TypeList,
Required: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"data": {
Type: schema.TypeString,
Optional: true,
StateFunc: func(v interface{}) string {
value := v.(string)
return strings.ToLower(value)
},
},
"type": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"text_transformation": {
Type: schema.TypeString,
Required: true,
},
},
},
},
},
}
}

func resourceAwsWafRegionalSqlInjectionMatchSetCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).wafregionalconn
region := meta.(*AWSClient).region

log.Printf("[INFO] Creating Regional WAF SQL Injection Match Set: %s", d.Get("name").(string))

wr := newWafRegionalRetryer(conn, region)
out, err := wr.RetryWithToken(func(token *string) (interface{}, error) {
params := &waf.CreateSqlInjectionMatchSetInput{
ChangeToken: token,
Name: aws.String(d.Get("name").(string)),
}

return conn.CreateSqlInjectionMatchSet(params)
})
if err != nil {
return fmt.Errorf("Failed creating Regional WAF SQL Injection Match Set: %s", err)
}
resp := out.(*waf.CreateSqlInjectionMatchSetOutput)
d.SetId(*resp.SqlInjectionMatchSet.SqlInjectionMatchSetId)

return resourceAwsWafRegionalSqlInjectionMatchSetUpdate(d, meta)
}

func resourceAwsWafRegionalSqlInjectionMatchSetRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).wafregionalconn
log.Printf("[INFO] Reading Regional WAF SQL Injection Match Set: %s", d.Get("name").(string))
params := &waf.GetSqlInjectionMatchSetInput{
SqlInjectionMatchSetId: aws.String(d.Id()),
}

resp, err := conn.GetSqlInjectionMatchSet(params)
if err != nil {
if isAWSErr(err, wafregional.ErrCodeWAFNonexistentItemException, "") {
log.Printf("[WARN] Regional WAF SQL Injection Match Set (%s) not found, error code (404)", d.Id())
d.SetId("")
return nil
}

return err
}

d.Set("name", resp.SqlInjectionMatchSet.Name)
d.Set("sql_injection_match_tuple", flattenWafSqlInjectionMatchTuples(resp.SqlInjectionMatchSet.SqlInjectionMatchTuples))

return nil
}

func resourceAwsWafRegionalSqlInjectionMatchSetUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).wafregionalconn
region := meta.(*AWSClient).region

if d.HasChange("sql_injection_match_tuple") {
o, n := d.GetChange("sql_injection_match_tuple")
oldT, newT := o.(*schema.Set).List(), n.(*schema.Set).List()

err := updateSqlInjectionMatchSetResourceWR(d.Id(), oldT, newT, conn, region)
if err != nil {
return fmt.Errorf("[ERROR] Error updating Regional WAF SQL Injection Match Set: %s", err)
}
}

return resourceAwsWafRegionalSqlInjectionMatchSetRead(d, meta)
}

func resourceAwsWafRegionalSqlInjectionMatchSetDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).wafregionalconn
region := meta.(*AWSClient).region

oldTuples := d.Get("sql_injection_match_tuple").(*schema.Set).List()

if len(oldTuples) > 0 {
noTuples := []interface{}{}
err := updateSqlInjectionMatchSetResourceWR(d.Id(), oldTuples, noTuples, conn, region)
if err != nil {
return fmt.Errorf("[ERROR] Error deleting Regional WAF SQL Injection Match Set: %s", err)
}
}

wr := newWafRegionalRetryer(conn, region)
_, err := wr.RetryWithToken(func(token *string) (interface{}, error) {
req := &waf.DeleteSqlInjectionMatchSetInput{
ChangeToken: token,
SqlInjectionMatchSetId: aws.String(d.Id()),
}

return conn.DeleteSqlInjectionMatchSet(req)
})
if err != nil {
return fmt.Errorf("Failed deleting Regional WAF SQL Injection Match Set: %s", err)
}

return nil
}

func updateSqlInjectionMatchSetResourceWR(id string, oldT, newT []interface{}, conn *wafregional.WAFRegional, region string) error {
wr := newWafRegionalRetryer(conn, region)
_, err := wr.RetryWithToken(func(token *string) (interface{}, error) {
req := &waf.UpdateSqlInjectionMatchSetInput{
ChangeToken: token,
SqlInjectionMatchSetId: aws.String(id),
Updates: diffWafSqlInjectionMatchTuplesWR(oldT, newT),
}

log.Printf("[INFO] Updating Regional WAF SQL Injection Match Set: %s", req)
return conn.UpdateSqlInjectionMatchSet(req)
})
if err != nil {
return fmt.Errorf("Failed updating Regional WAF SQL Injection Match Set: %s", err)
}

return nil
}

func diffWafSqlInjectionMatchTuplesWR(oldT, newT []interface{}) []*waf.SqlInjectionMatchSetUpdate {
updates := make([]*waf.SqlInjectionMatchSetUpdate, 0)

for _, od := range oldT {
tuple := od.(map[string]interface{})

if idx, contains := sliceContainsMap(newT, tuple); contains {
newT = append(newT[:idx], newT[idx+1:]...)
continue
}

ftm := tuple["field_to_match"].([]interface{})

updates = append(updates, &waf.SqlInjectionMatchSetUpdate{
Action: aws.String(waf.ChangeActionDelete),
SqlInjectionMatchTuple: &waf.SqlInjectionMatchTuple{
FieldToMatch: expandFieldToMatch(ftm[0].(map[string]interface{})),
TextTransformation: aws.String(tuple["text_transformation"].(string)),
},
})
}

for _, nd := range newT {
tuple := nd.(map[string]interface{})
ftm := tuple["field_to_match"].([]interface{})

updates = append(updates, &waf.SqlInjectionMatchSetUpdate{
Action: aws.String(waf.ChangeActionInsert),
SqlInjectionMatchTuple: &waf.SqlInjectionMatchTuple{
FieldToMatch: expandFieldToMatch(ftm[0].(map[string]interface{})),
TextTransformation: aws.String(tuple["text_transformation"].(string)),
},
})
}
return updates
}

func resourceAwsWafRegionalSqlInjectionMatchSetTupleHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
if v, ok := m["field_to_match"]; ok {
ftms := v.([]interface{})
ftm := ftms[0].(map[string]interface{})

if v, ok := ftm["data"]; ok {
buf.WriteString(fmt.Sprintf("%s-", strings.ToLower(v.(string))))
}
buf.WriteString(fmt.Sprintf("%s-", ftm["type"].(string)))
}
buf.WriteString(fmt.Sprintf("%s-", m["text_transformation"].(string)))

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

0 comments on commit f617d80

Please sign in to comment.