# trussworks/wafv2/aws has a basic WAF with the AWS Managed Ruleset
# See https://registry.terraform.io/modules/trussworks/wafv2/aws/latest
#
# Attempted to add some sane defaults so we can customize as needed
resource "aws_wafv2_ip_set" "ipset" {
  name = "blocked_ips"

  scope              = "REGIONAL"
  ip_address_version = "IPV4"

  addresses = [
  ]
}

module "wafv2" {
  source = "trussworks/wafv2/aws"
  version = "~> 2.0"

  name   = local.alb_name
  scope = "REGIONAL"

  alb_arn       = aws_lb.searchhead-alb.arn
  associate_alb = true

  ip_sets_rule = [
    {
      name       = "blocked_ips"
      action     = "block"
      priority   = 1
      ip_set_arn = aws_wafv2_ip_set.ipset.arn
    }
  ]

  # A rate-based rule tracks the rate of requests for each originating IP address, and triggers the rule action when the rate exceeds a limit that you specify on the number of requests in any 5-minute time span
  ip_rate_based_rule = {
    name     = "Rate_Limit"
    priority = 5
    limit    = 900 # 900 requests per 5 minutes= 3 requests/second (sustained for 5 minutes)
    action   = "block"
  }

  tags = merge(var.standard_tags, var.tags)
}

resource "aws_wafv2_web_acl_logging_configuration" "waf_logs" {
  log_destination_configs = [ "arn:${var.aws_partition}:firehose:${var.aws_region}:${var.aws_account_id}:deliverystream/aws-waf-logs-splunk" ]
  resource_arn            = module.wafv2.web_acl_id

#  logging_filter {
#    default_behavior = "KEEP"
#
#    filter {
#      behavior = "DROP"
#
#      condition {
#        action_condition {
#          action = "COUNT"
#        }
#      }
#
#      condition {
#        label_name_condition {
#          label_name = "awswaf:111122223333:rulegroup:testRules:LabelNameZ"
#        }
#      }
#
#      requirement = "MEETS_ALL"
#    }
#
#    filter {
#      behavior = "KEEP"
#
#      condition {
#        action_condition {
#          action = "ALLOW"
#        }
#      }
#
#      requirement = "MEETS_ANY"
#    }
#  }
}


