AWS WAF:如何使用 Terraform 阻止不包含特定 header 的请求

AWS WAF: How to block requests that do not contain a particular header using Terraform

我想阻止不包含授权的请求 header。我想出了以下规则,但我发现不包含此 header 的请求也被允许。指定此条件的正确方法是什么?

rule {
    name = "restrict-requests-without-authorization-header"
    priority = 2

    action {
      block {}
    }

    statement {
      size_constraint_statement {
        field_to_match {
          single_header {
            name = "authorization"
          }
        }

        comparison_operator = "LE"
        size = 0
        text_transformation {
          priority = 0
          type = "NONE"
        }
      }
    }

    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name = "restrict-requests-without-authorization-header-metrics"
      sampled_requests_enabled = true
    }
  }

您需要像这样创建规则和正则表达式模式(可以是通配符):

规则:

rule {
    name     = "AuthorizationHeaderRule"
    priority = 1

    action {
      allow {}
    }

        statement {
          regex_pattern_set_reference_statement {
            arn = aws_wafv2_regex_pattern_set.your_regex_pattern.arn

            field_to_match {
              single_header {
                name = "authorization"
              }
            }

            text_transformation {
              priority = 2
              type     = "NONE"
            }
          }
      }

这可以是正则表达式模式:

resource "aws_wafv2_regex_pattern_set" "your_regex_pattern" {
  name  = "your-regex-pattern"
  scope = "REGIONAL"

  regular_expression {
    regex_string = "prefix-.*"
  }
}
http_headers_val_to_block = ["header01", "header02"]
resource "aws_wafv2_regex_pattern_set" "http_headers" {
  name        = "HTTP_headers"
  description = "HTTP headers regex pattern set"
  scope       = "REGIONAL"
  tags        = var.tags

  dynamic "regular_expression" {
    for_each = var.http_headers_val_to_block
    content {
      regex_string = regular_expression.value
    }
  }
}
...
rule {
    name     = "IPs_and_HTTP_Header_Based_Rule"
    priority = 8

    action {
      block {}
    }

    statement {

      or_statement {
        statement {

          ip_set_reference_statement {
            arn = aws_wafv2_ip_set.toblock.arn
          }
        }

        statement {

          regex_pattern_set_reference_statement {
            arn = aws_wafv2_regex_pattern_set.http_headers.arn

            field_to_match {
              single_header {
                name = "referer"
              }
            }

            text_transformation {
              priority = 2
              type     = "LOWERCASE"
            }
          }
        }
      }
    }

    visibility_config {
      cloudwatch_metrics_enabled = false
      metric_name                = "IPs-and-HTTP-Header-Based-Rule-metric"
      sampled_requests_enabled   = false
    }
  }
...