Skip to content

googleComputeSecurityPolicy

A Security Policy defines an IP blacklist or whitelist that protects load balanced Google Cloud services by denying or permitting traffic from specified IP ranges. For more information see the official documentation and the API.

Security Policy is used by googleComputeBackendService.

Example Usage

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as google from "./.gen/providers/google";
/*The following providers are missing schema information and might need manual adjustments to synthesize correctly: google.
For a more precise conversion please use the --provider flag in convert.*/
new google.computeSecurityPolicy.ComputeSecurityPolicy(this, "policy", {
  name: "my-policy",
  rule: [
    {
      action: "deny(403)",
      description: "Deny access to IPs in 9.9.9.0/24",
      match: [
        {
          config: [
            {
              src_ip_ranges: ["9.9.9.0/24"],
            },
          ],
          versioned_expr: "SRC_IPS_V1",
        },
      ],
      priority: "1000",
    },
    {
      action: "allow",
      description: "default rule",
      match: [
        {
          config: [
            {
              src_ip_ranges: ["*"],
            },
          ],
          versioned_expr: "SRC_IPS_V1",
        },
      ],
      priority: "2147483647",
    },
  ],
});

Example Usage - With reCAPTCHA configuration options

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as google from "./.gen/providers/google";
/*The following providers are missing schema information and might need manual adjustments to synthesize correctly: google.
For a more precise conversion please use the --provider flag in convert.*/
const googleRecaptchaEnterpriseKeyPrimary =
  new google.recaptchaEnterpriseKey.RecaptchaEnterpriseKey(this, "primary", {
    display_name: "display-name",
    labels: [
      {
        "label-one": "value-one",
      },
    ],
    project: "my-project-name",
    web_settings: [
      {
        allow_all_domains: true,
        allowed_domains: ["localhost"],
        integration_type: "INVISIBLE",
      },
    ],
  });
new google.computeSecurityPolicy.ComputeSecurityPolicy(this, "policy", {
  description: "basic security policy",
  name: "my-policy",
  recaptcha_options_config: [
    {
      redirect_site_key: googleRecaptchaEnterpriseKeyPrimary.name,
    },
  ],
  type: "CLOUD_ARMOR",
});

Example Usage - With header actions

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as google from "./.gen/providers/google";
/*The following providers are missing schema information and might need manual adjustments to synthesize correctly: google.
For a more precise conversion please use the --provider flag in convert.*/
new google.computeSecurityPolicy.ComputeSecurityPolicy(this, "policy", {
  name: "my-policy",
  rule: [
    {
      action: "allow",
      description: "default rule",
      match: [
        {
          config: [
            {
              src_ip_ranges: ["*"],
            },
          ],
          versioned_expr: "SRC_IPS_V1",
        },
      ],
      priority: "2147483647",
    },
    {
      action: "allow",
      header_action: [
        {
          request_headers_to_adds: [
            {
              header_name: "reCAPTCHA-Warning",
              header_value: "high",
            },
            {
              header_name: "X-Resource",
              header_value: "test",
            },
          ],
        },
      ],
      match: [
        {
          expr: [
            {
              expression:
                'request.path.matches("/login.html") && token.recaptcha_session.score < 0.2',
            },
          ],
        },
      ],
      priority: "1000",
    },
  ],
});

Example Usage - With enforceOnKey value as empty string

A scenario example that won't cause any conflict between enforceOnKey and enforceOnKeyConfigs, because enforceOnKey was specified as an empty string:

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as google from "./.gen/providers/google";
/*The following providers are missing schema information and might need manual adjustments to synthesize correctly: google.
For a more precise conversion please use the --provider flag in convert.*/
new google.computeSecurityPolicy.ComputeSecurityPolicy(this, "policy", {
  description: "throttle rule with enforce_on_key_configs",
  name: "%s",
  rule: [
    {
      action: "throttle",
      description: "default rule",
      match: [
        {
          config: [
            {
              src_ip_ranges: ["*"],
            },
          ],
          versioned_expr: "SRC_IPS_V1",
        },
      ],
      priority: "2147483647",
      rate_limit_options: [
        {
          conform_action: "allow",
          enforce_on_key: "",
          enforce_on_key_configs: [
            {
              enforce_on_key_type: "IP",
            },
          ],
          exceed_action: "redirect",
          exceed_redirect_options: [
            {
              target: "<https://www.example.com>",
              type: "EXTERNAL_302",
            },
          ],
          rate_limit_threshold: [
            {
              count: 10,
              interval_sec: 60,
            },
          ],
        },
      ],
    },
  ],
});

Argument Reference

The following arguments are supported:

  • name - (Required) The name of the security policy.

  • description - (Optional) An optional description of this security policy. Max size is 2048.

  • project - (Optional) The project in which the resource belongs. If it is not provided, the provider project is used.

  • rule - (Optional) The set of rules that belong to this policy. There must always be a default rule (rule with priority 2147483647 and match "*"). If no rules are provided when creating a security policy, a default rule with action "allow" will be added. Structure is documented below.

  • advancedOptionsConfig - (Optional) Advanced Configuration Options. Structure is documented below.

  • adaptiveProtectionConfig - (Optional) Configuration for Google Cloud Armor Adaptive Protection. Structure is documented below.

  • recaptchaOptionsConfig - (Optional) reCAPTCHA Configuration Options. Structure is documented below.

  • type - The type indicates the intended use of the security policy. This field can be set only at resource creation time.

    • CLOUD_ARMOR - Cloud Armor backend security policies can be configured to filter incoming HTTP requests targeting backend services. They filter requests before they hit the origin servers.
    • CLOUD_ARMOR_EDGE - Cloud Armor edge security policies can be configured to filter incoming HTTP requests targeting backend services (including Cloud CDN-enabled) as well as backend buckets (Cloud Storage). They filter requests before the request is served from Google's cache.
    • CLOUD_ARMOR_INTERNAL_SERVICE - Cloud Armor internal service policies can be configured to filter HTTP requests targeting services managed by Traffic Director in a service mesh. They filter requests before the request is served from the application.

The advancedOptionsConfig block supports:

  • jsonParsing - Whether or not to JSON parse the payload body. Defaults to disabled.

    • DISABLED - Don't parse JSON payloads in POST bodies.
    • STANDARD - Parse JSON payloads in POST bodies.
  • jsonCustomConfig - Custom configuration to apply the JSON parsing. Only applicable when jsonParsing is set to standard. Structure is documented below.

  • logLevel - Log level to use. Defaults to normal.

    • NORMAL - Normal log level.
    • VERBOSE - Verbose log level.

The jsonCustomConfig block supports:

  • contentTypes - A list of custom Content-Type header values to apply the JSON parsing. The format of the Content-Type header values is defined in RFC 1341. When configuring a custom Content-Type header value, only the type/subtype needs to be specified, and the parameters should be excluded.

The rule block supports:

  • action - (Required) Action to take when match matches the request. Valid values:

    • allow: allow access to target.
    • deny(): deny access to target, returns the HTTP response code specified (valid values are 403, 404, and 502).
    • rate_based_ban: limit client traffic to the configured threshold and ban the client if the traffic exceeds the threshold. Configure parameters for this action in RateLimitOptions. Requires rateLimitOptions to be set.
    • redirect: redirect to a different target. This can either be an internal reCAPTCHA redirect, or an external URL-based redirect via a 302 response. Parameters for this action can be configured via redirectOptions.
    • throttle: limit client traffic to the configured threshold. Configure parameters for this action in rateLimitOptions. Requires rateLimitOptions to be set for this.
  • priority - (Required) An unique positive integer indicating the priority of evaluation for a rule. Rules are evaluated from highest priority (lowest numerically) to lowest priority (highest numerically) in order.

  • match - (Required) A match condition that incoming traffic is evaluated against. If it evaluates to true, the corresponding action is enforced. Structure is documented below.

  • preconfiguredWafConfig - (Optional, Beta) Preconfigured WAF configuration to be applied for the rule. If the rule does not evaluate preconfigured WAF rules, i.e., if evaluatePreconfiguredWaf() is not used, this field will have no effect. Structure is documented below.

  • description - (Optional) An optional description of this rule. Max size is 64.

  • preview - (Optional) When set to true, the action specified above is not enforced. Stackdriver logs for requests that trigger a preview action are annotated as such.

  • rateLimitOptions - (Optional) Must be specified if the action is "rate_based_ban" or "throttle". Cannot be specified for other actions. Structure is documented below.

  • redirectOptions - (Optional) Can be specified if the action is "redirect". Cannot be specified for other actions. Structure is documented below.

  • headerAction - (Optional) Additional actions that are performed on headers. Structure is documented below.

The match block supports:

  • config - (Optional) The configuration options available when specifying versionedExpr. This field must be specified if versionedExpr is specified and cannot be specified if versionedExpr is not specified. Structure is documented below.

  • versionedExpr - (Optional) Predefined rule expression. If this field is specified, config must also be specified. Available options:

    • SRC_IPS_V1: Must specify the corresponding srcIpRanges field in config.
  • expr - (Optional) User defined CEVAL expression. A CEVAL expression is used to specify match criteria such as origin.ip, source.region_code and contents in the request header. Structure is documented below.

The config block supports:

  • srcIpRanges - (Required) Set of IP addresses or ranges (IPV4 or IPV6) in CIDR notation to match against inbound traffic. There is a limit of 10 IP ranges per rule. A value of '*' matches all IPs (can be used to override the default behavior).

The expr block supports:

  • expression - (Required) Textual representation of an expression in Common Expression Language syntax. The application context of the containing message determines which well-known feature set of CEL is supported.

The preconfiguredWafConfig block supports:

  • exclusion - (Optional) An exclusion to apply during preconfigured WAF evaluation. Structure is documented below.

The exclusion block supports:

  • requestHeader - (Optional) Request header whose value will be excluded from inspection during preconfigured WAF evaluation. Structure is documented below.

  • requestCookie - (Optional) Request cookie whose value will be excluded from inspection during preconfigured WAF evaluation. Structure is documented below.

  • requestUri - (Optional) Request query parameter whose value will be excluded from inspection during preconfigured WAF evaluation. Note that the parameter can be in the query string or in the POST body. Structure is documented below.

  • requestQueryParam - (Optional) Request URI from the request line to be excluded from inspection during preconfigured WAF evaluation. When specifying this field, the query or fragment part should be excluded. Structure is documented below.

  • targetRuleSet - (Required) Target WAF rule set to apply the preconfigured WAF exclusion.

  • targetRuleIds - (Optional) A list of target rule IDs under the WAF rule set to apply the preconfigured WAF exclusion. If omitted, it refers to all the rule IDs under the WAF rule set.

The requestHeader, requestCookie, requestUri and requestQueryParam blocks support:

  • operator - (Required) You can specify an exact match or a partial match by using a field operator and a field value.

    • EQUALS: The operator matches if the field value equals the specified value.
    • STARTS_WITH: The operator matches if the field value starts with the specified value.
    • ENDS_WITH: The operator matches if the field value ends with the specified value.
    • CONTAINS: The operator matches if the field value contains the specified value.
    • EQUALS_ANY: The operator matches if the field value is any value.
  • value - (Optional) A request field matching the specified value will be excluded from inspection during preconfigured WAF evaluation. The field value must be given if the field operator is not "EQUALS_ANY", and cannot be given if the field operator is "EQUALS_ANY".

The rateLimitOptions block supports:

  • conformAction - (Required) Action to take for requests that are under the configured rate limit threshold. Valid option is "allow" only.

  • exceedAction - (Required) When a request is denied, returns the HTTP response code specified. Valid options are "deny()" where valid values for status are 403, 404, 429, and 502.

  • rateLimitThreshold - (Required) Threshold at which to begin ratelimiting. Structure is documented below.

  • banDurationSec - (Optional) Can only be specified if the action for the rule is "rate_based_ban". If specified, determines the time (in seconds) the traffic will continue to be banned by the rate limit after the rate falls below the threshold.

  • banThreshold - (Optional) Can only be specified if the action for the rule is "rate_based_ban". If specified, the key will be banned for the configured 'ban_duration_sec' when the number of requests that exceed the 'rate_limit_threshold' also exceed this 'ban_threshold'. Structure is documented below.

  • enforceOnKey - (Optional) Determines the key to enforce the rate_limit_threshold on. If not specified, defaults to "ALL".

    • ALL: A single rate limit threshold is applied to all the requests matching this rule.
    • IP: The source IP address of the request is the key. Each IP has this limit enforced separately.
    • HTTP_HEADER: The value of the HTTP header whose name is configured under "enforceOnKeyName". The key value is truncated to the first 128 bytes of the header value. If no such header is present in the request, the key type defaults to ALL.
    • XFF_IP: The first IP address (i.e. the originating client IP address) specified in the list of IPs under X-Forwarded-For HTTP header. If no such header is present or the value is not a valid IP, the key type defaults to ALL.
    • HTTP_COOKIE: The value of the HTTP cookie whose name is configured under "enforceOnKeyName". The key value is truncated to the first 128 bytes of the cookie value. If no such cookie is present in the request, the key type defaults to ALL.
    • HTTP_PATH: The URL path of the HTTP request. The key value is truncated to the first 128 bytes
    • SNI: Server name indication in the TLS session of the HTTPS request. The key value is truncated to the first 128 bytes. The key type defaults to ALL on a HTTP session.
    • REGION_CODE: The country/region from which the request originates.
  • enforceOnKeyName - (Optional) Rate limit key name applicable only for the following key types: HTTP_HEADER -- Name of the HTTP header whose value is taken as the key value. HTTP_COOKIE -- Name of the HTTP cookie whose value is taken as the key value.

  • enforceOnKeyConfigs - (Optional, Beta) If specified, any combination of values of enforce_on_key_type/enforce_on_key_name is treated as the key on which ratelimit threshold/action is enforced. You can specify up to 3 enforce_on_key_configs. If enforceOnKeyConfigs is specified, enforce_on_key must be set to an empty string. Structure is documented below.

    Note: To avoid the conflict between enforceOnKey and enforceOnKeyConfigs, the field enforceOnKey needs to be set to an empty string.

The enforceOnKeyConfigs block supports:

  • enforceOnKeyName - (Optional) Rate limit key name applicable only for the following key types: HTTP_HEADER: Name of the HTTP header whose value is taken as the key value. HTTP_COOKIE: Name of the HTTP cookie whose value is taken as the key value.

  • enforceOnKeyType - (Optional) Determines the key to enforce the rate_limit_threshold on. If not specified, defaults to "ALL".

    • ALL: A single rate limit threshold is applied to all the requests matching this rule.
    • IP: The source IP address of the request is the key. Each IP has this limit enforced separately.
    • HTTP_HEADER: The value of the HTTP header whose name is configured under "enforceOnKeyName". The key value is truncated to the first 128 bytes of the header value. If no such header is present in the request, the key type defaults to ALL.
    • XFF_IP: The first IP address (i.e. the originating client IP address) specified in the list of IPs under X-Forwarded-For HTTP header. If no such header is present or the value is not a valid IP, the key type defaults to ALL.
    • HTTP_COOKIE: The value of the HTTP cookie whose name is configured under "enforceOnKeyName". The key value is truncated to the first 128 bytes of the cookie value. If no such cookie is present in the request, the key type defaults to ALL.
    • HTTP_PATH: The URL path of the HTTP request. The key value is truncated to the first 128 bytes
    • SNI: Server name indication in the TLS session of the HTTPS request. The key value is truncated to the first 128 bytes. The key type defaults to ALL on a HTTP session.
    • REGION_CODE: The country/region from which the request originates.
  • exceedRedirectOptions - (Optional) Parameters defining the redirect action that is used as the exceed action. Cannot be specified if the exceed action is not redirect. Structure is documented below.

The {ban/rateLimit}Threshold block supports:

  • count - (Required) Number of HTTP(S) requests for calculating the threshold.

  • intervalSec - (Required) Interval over which the threshold is computed.

  • The exceedRedirectOptions block supports:

  • type - (Required) Type of the redirect action.

  • target - (Optional) Target for the redirect action. This is required if the type is EXTERNAL_302 and cannot be specified for GOOGLE_RECAPTCHA.

The redirectOptions block supports:

  • type - (Required) Type of redirect action.

    • EXTERNAL_302: Redirect to an external address, configured in 'target'.
    • GOOGLE_RECAPTCHA: Redirect to Google reCAPTCHA.
  • target - (Optional) External redirection target when "EXTERNAL_302" is set in 'type'.

The headerAction block supports:

  • requestHeadersToAdds - (Required) The list of request headers to add or overwrite if they're already present. Structure is documented below.

The requestHeadersToAdds block supports:

  • headerName - (Required) The name of the header to set.

  • headerValue - (Optional) The value to set the named header to.

The adaptiveProtectionConfig block supports:

The layer7DdosDefenseConfig block supports:

  • enable - (Optional) If set to true, enables CAAP for L7 DDoS detection.

  • ruleVisibility - (Optional) Rule visibility can be one of the following: STANDARD - opaque rules. (default) PREMIUM - transparent rules.

The autoDeployConfig block supports:

  • loadThreshold - (Optional) Identifies new attackers only when the load to the backend service that is under attack exceeds this threshold.

  • confidenceThreshold - (Optional) Rules are only automatically deployed for alerts on potential attacks with confidence scores greater than this threshold.

  • impactedBaselineThreshold - (Optional) Rules are only automatically deployed when the estimated impact to baseline traffic from the suggested mitigation is below this threshold.

  • expirationSec - (Optional) Google Cloud Armor stops applying the action in the automatically deployed rule to an identified attacker after this duration. The rule continues to operate against new requests.

The recaptchaOptionsConfig block supports:

  • redirectSiteKey - (Required) A field to supply a reCAPTCHA site key to be used for all the rules using the redirect action with the type of GOOGLE_RECAPTCHA under the security policy. The specified site key needs to be created from the reCAPTCHA API. The user is responsible for the validity of the specified site key. If not specified, a Google-managed site key is used.

Attributes Reference

In addition to the arguments listed above, the following computed attributes are exported:

  • id - an identifier for the resource with format projects/{{project}}/global/securityPolicies/{{name}}

  • fingerprint - Fingerprint of this resource.

  • selfLink - The URI of the created resource.

Import

Security policies can be imported using any of the following formats

$ terraform import google_compute_security_policy.policy projects/{{project}}/global/securityPolicies/{{name}}
$ terraform import google_compute_security_policy.policy {{project}}/{{name}}
$ terraform import google_compute_security_policy.policy {{name}}