GoogleCloudPlatform / terraform-validator

Terraform Validator is not an officially supported Google product; it is a library for conversion of Terraform plan data to CAI Assets. If you have been using terraform-validator directly in the past, we recommend migrating to `gcloud beta terraform vet`.
https://cloud.google.com/docs/terraform/policy-validation
Apache License 2.0
437 stars 93 forks source link

Rego policy is failing to restrict optional string parameter of terraform #1555

Open sujatak97 opened 1 year ago

sujatak97 commented 1 year ago

Statement: Rego policy to enable Verbose Logging in Cloud Armor Parameter: log_level

Defaults to NORMAL.
NORMAL - Normal log level.
VERBOSE - Verbose log level.

Rego Policy:

package templates.gcp.GCPCloudArmorEnableJsonParsingConstraintV1

            violation[{
                "msg": msg,
            }] {
                resource := input.review
              allowed_logging_types := input.parameters.allowed_logging_types
              logging_type_set := {x | x = allowed_logging_types[_]}
                resource.type == "google_compute_security_policy"
                msg := check_verbose_logging(resource, logging_type_set)
            }

            check_verbose_logging(resource, logging_type_set) = msg {
                count({resource.change.after.advanced_options_config[_].log_level} & logging_type_set) == 0
                msg := sprintf("Violation: Logging level should be %s for resource %s.%s.", [logging_type_set, resource.type, resource.name])
            }

This policy is raising the violation if we use log_level = "NORMAL" as expected. If we omit the log_level parameter in the Terraform script, no violation will be raised by this policy. It is bypassing our validation rule. I have tried with not keyword, but it is not working.

check_verbose_logging(resource, logging_type_set) = msg {
                not resource.change.after.advanced_options_config[_].log_level
                msg := sprintf("Violation: Log level is not mentioned. VERBOSE log level is required: %s", [resource.change.after.name])
            }

With null also not working resource.change.after.advanced_options_config[_].log_level == null Any solution to check missing terraform parameter?