{"id":13533528,"url":"https://github.com/aws-cloudformation/cloudformation-guard","last_synced_at":"2025-05-13T19:04:36.454Z","repository":{"id":37178327,"uuid":"271888852","full_name":"aws-cloudformation/cloudformation-guard","owner":"aws-cloudformation","description":"Guard offers a policy-as-code domain-specific language (DSL) to write rules and validate JSON- and YAML-formatted data such as CloudFormation Templates, K8s configurations, and Terraform JSON plans/configurations against those rules. Take this survey to provide feedback about cfn-guard: https://amazonmr.au1.qualtrics.com/jfe/form/SV_bpyzpfoYGGuuUl0","archived":false,"fork":false,"pushed_at":"2025-04-21T18:01:31.000Z","size":13369,"stargazers_count":1334,"open_issues_count":35,"forks_count":185,"subscribers_count":42,"default_branch":"main","last_synced_at":"2025-04-25T22:43:42.678Z","etag":null,"topics":["cfn-guard","cloudformation","compliance","governance","k8s","policy-as-code","policy-rule-evaluation","security","terraform"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/aws-cloudformation.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-06-12T20:56:45.000Z","updated_at":"2025-04-17T00:52:25.000Z","dependencies_parsed_at":"2024-01-17T17:46:45.922Z","dependency_job_id":"2062735b-efbd-4a5a-9553-454029de42ee","html_url":"https://github.com/aws-cloudformation/cloudformation-guard","commit_stats":{"total_commits":532,"total_committers":38,"mean_commits":14.0,"dds":0.768796992481203,"last_synced_commit":"b2bd008a09f5a802e78f8e88edba30a53b280298"},"previous_names":[],"tags_count":35,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aws-cloudformation%2Fcloudformation-guard","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aws-cloudformation%2Fcloudformation-guard/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aws-cloudformation%2Fcloudformation-guard/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aws-cloudformation%2Fcloudformation-guard/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/aws-cloudformation","download_url":"https://codeload.github.com/aws-cloudformation/cloudformation-guard/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250907665,"owners_count":21506068,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cfn-guard","cloudformation","compliance","governance","k8s","policy-as-code","policy-rule-evaluation","security","terraform"],"created_at":"2024-08-01T07:01:20.668Z","updated_at":"2025-04-25T22:43:49.115Z","avatar_url":"https://github.com/aws-cloudformation.png","language":"Rust","readme":"# AWS CloudFormation Guard\n\n**Validate Cloud Environments with Policy-as-Code**\n\nAWS CloudFormation Guard is an open-source general-purpose policy-as-code evaluation tool. It provides developers with a simple-to-use, yet powerful and expressive domain-specific language (DSL) to define policies and enables developers to validate JSON- or YAML- formatted structured data with those policies.\n\nThe Guard 3.0 release introduces support for stateful rules through built-in functions, SAM CLI as an alternative deployment method for `cfn-guard-lambda`, command auto-completions for shell, advanced regular expressions, improved handling of intrinsic functions for the test command, as well as the `--structured` flag to the validate command to emit JSON/YAML parseable output. Note that previously written tests may have to be reviewed due to the corrected behavior of intrinsic function handling. Please see the release notes for full details and examples.\n\nGuard can be used for the following domains:\n\n1. **Preventative Governance and Compliance (shift left):** validate Infrastructure-as-code (IaC) or infrastructure/service compositions such as CloudFormation Templates, CloudFormation ChangeSets, Terraform JSON configuration files, Kubernetes configurations, and more against Guard policies representing your organizational best practices for security, compliance, and more. For example, developers can use Guard policies with\n   1. Terraform plan (**in JSON format**) for deployment safety assessment checks or Terraform state files to detect live state deviations.\n   2. Static assessment of IaC templates to determine network reachability like Amazon Redshift cluster deployed inside a VPC and prevent the provision of such stacks.\n2. **Detective Governance and Compliance:** validate conformity of Configuration Management Database (CMDB) resources such as AWS Config-based configuration items (CIs). For example, developers can use Guard policies against AWS Config CIs to continuously monitor state of deployed AWS and non-AWS resources, detect violations from policies, and trigger remediation.\n3. **Deployment Safety:** validate CloudFormation ChangeSets to ensure changes are safe before deployment. For example, renaming an Amazon DynamoDB Table will cause a replacement of the Table. With Guard 3.0, you can prevent such changes in your CI/CD pipelines.\n\n\u003e **NOTE**: If you are using Guard 1.0 rules, we highly recommend adopting the latest version of Guard to simplify your current policy-as-code experience. Guard 2.0 and higher versions are backward incompatible with your Guard 1.0 rules and can result in breaking changes. The Guard 2.0 release was a complete re-write of the earlier 1.0 version to make the tool general-purpose.\n\u003e\n\u003e To migrate from Guard 1.0 rules to use the updated grammar, follow the steps given below.\n\u003e\n\u003e 1. Pull the release artifacts for the latest `2.x.x` release from the corresponding release page listed [here](https://github.com/aws-cloudformation/cloudformation-guard/releases).\n\u003e 2. Use `migrate` command to transition your existing 1.0 rules to use the updated grammar\n\u003e 3. Read about all new Guard features from the latest release, and modify your rules for enhanced experience\n\n**Guard In Action**\n\n![Guard In Action](images/guard-demo.gif)\n\n**Customer Feedback**\nTake this [survey](https://amazonmr.au1.qualtrics.com/jfe/form/SV_bpyzpfoYGGuuUl0) to provide feedback about cfn-guard\n\n## Table of Contents\n\n\u003c!-- no toc --\u003e\n\n- [FAQs](#faqs)\n- [Guard DSL](#guard-dsl)\n  - [Tenets](#tenets)\n  - [Features of Guard DSL](#features-of-guard-dsl)\n- [Guard CLI](#guard-cli)\n  - [Installation](#installation)\n  - [How does Guard CLI work?](#how-does-guard-cli-work?)\n- [Rule authoring references](#references)\n- [Built-in functions \u0026 stateful rules](#functions)\n- [AWS Rule Registry](#registry)\n- [Use Guard as a Docker Image](#docker)\n- [Use Guard as a Github Action](https://github.com/aws-cloudformation/cloudformation-guard/tree/main/action#readme)\n- [Use Guard as a CI tool](#ci)\n- [Use Guard as a pre-commit hook](#pre-commit-hook)\n- [Contribute using the DevContainer in VSCode](#devcontainer)\n- [License](#license)\n\n## FAQs\n\n**1) What is Guard?**\n\n\u003e Guard is an open-source command line interface (CLI) that provides developers a general purpose domain-specific language (DSL) to express policy-as-code and then validate their JSON- and YAML-formatted data against that code. Guard’s DSL is a simple, powerful, and expressive declarative language to define policies. It is built on the foundation of clauses, which are assertions that evaluate to `true` or `false`. Examples clauses can include simple validations like all Amazon Simple Storage Service (S3) buckets must have versioning enabled, or combined to express complex validations like preventing public network reachability of Amazon Redshift clusters placed in a subnet. Guard has support for looping, queries with filtering, cross query joins, single shot variable assignments, conditional executions, and composable rules. These features help developers to express simple and advanced policies for various domains.\n\n**2) What Guard is not?**\n\n\u003e Guard **is not** a general-purpose programming language. It is a **purpose-built** DSL that is designed for policy definition and evaluation. Both non-technical people and developers can easily pick up Guard. Guard is human-readable and machine enforceable.\n\n**3) Where can I use Guard?**\n\n\u003e You can use Guard to define any type of policy for evaluation. You can apply Guard in the context of multiple domains: a) validating IaC/service compositions such as [CloudFormation Templates](https://aws.amazon.com/cloudformation/resources/templates/), Terraform JSON configuration files, and Kubernetes configurations, b) verifying conformity of CMDB resources such as AWS Config-based CIs, and c) assessing security postures across resources like AWS Security Hub. The policy language and expression is common to all of them, based on simple Guard clauses.\n\n**3) What is a clause in Guard?**\n\n\u003e Clause is an assertion that evaluates to true or false. Clauses can either use binary operations to compare two values (e.g `==, \u003e` and `in`), or unary operations that takes only one value (e.g. `exists, empty,` and `is_list`). Here is a sample clause that compares `Type` to be a `AWS::S3::Bucket` :\n\n```\nType == /AWS::S3::Bucket/\n```\n\n**4) What are the supported** **types** **that can I use to define clauses?**\n\n\u003e Guard supports all primitives `string, integer (64), float (64), bool, char, regex` and specialized range expression like `r(10, 200)`, for specifying ranges of values. It supports general key value pair maps (a.k.a associative arrays/struct) like `{ \"my-map\": { \"nested-maps\": [ { \"key\": 10, \"value\": 20 } ] } },` and arrays of primitives or key-value pair maps like `[10, 20, 30] or [{ Key: \"MyApp\", Value: \"PROD}, ..]`.\n\n**5) What binary and unary comparison operators can I use?**\n\n\u003e _Unary Operators:_ `exists, empty, is_string, is_list, is_struct, is_bool, is_int, is_float, not(!)` \u003e _Binary Operators:_ `==, !=, \u003e, \u003e=, \u003c, \u003c=, IN `\n\u003e\n\u003e Most operators are self-explanatory. A few important points:\n\u003e\n\u003e 1. Refer [Guard: Clauses](docs/CLAUSES.md) to understand the usage of `exists` and `empty` operators\n\u003e 2. Clause `ports \u003e= [10, 20, 30]` implies that every element for `ports` is `\u003e= 30`. If your intention is range, then express it as `r[10, 30]` .\n\u003e 3. Clause `ports \u003e= 100` can have ports resolve to an array `[121, 200, 443]`. This check ensures that every element returned was \u003e= 100, and in the example shown this evaluates to `true.`\n\u003e 4. `IN` operator for collections (does not work for `string` type) to check if any value matches. For example:\n\n```\nProperties.SslPolicy IN [\"ELBSecurityPolicy-TLS-1-2-2017-01\", \"ELBSecurityPolicy-TLS-1-2-Ext-2018-06\"]\n```\n\n**6) How can I define advanced policy rules?**\n\n\u003e You can define advanced policy rules using Conjunctive normal form. For example, here is a clause that asserts that all S3 buckets have a) names that start with a common prefix, b) encryption turned on, and c) only KMS-based algorithm is used (to know more about the query part read [Guard: Query and Filtering](docs/QUERY_AND_FILTERING.md)) for IaC template.\n\n```\nlet s3_buckets = Resources.*[ Type == /S3::Bucket/ ]\n\n# Skip the checks if there are no S3 buckets present\nrule s3_bucket_name_encryption_check when %s3_buckets !empty {\n    %s3_buckets {\n        Properties {\n             # common prefix\n             BucketName == /^MyCompanyPrefix/\n\n             # encryption MUST BE on\n             BucketEncryption.ServerSideEncryptionConfiguration[*] {\n                # only KMS\n                ServerSideEncryptionByDefault.SSEAlgorithm IN\n                    [\"aws:KMS\"]\n             }\n        }\n    }\n}\n```\n\n**7) Can I easily test policy rules?**\n\n\u003e Yes. Guard supports a built-in unit testing framework to test policy rules and clauses. This gives customers confidence that their guard policy rules work as intended. You can learn more about this unit testing framework in this doc [Guard: Unit Testing](docs/UNIT_TESTING.md)\n\n**8)** **Does Guard support rule categories?**\n\n\u003e Yes. Guard supports running several rule-sets together for validating policies. You can create multiple rule files, each with its own intended purpose. For example, you can create one rules file for S3, second one for Dynamo DB, third one for access management, and so on. Alternatively, you can create a rules file for all your security related rules, second one for cost compliance, and so on. You can run Guard against all these rule files at once for evaluation. Refer example rules file [Guard: Clauses](docs/CLAUSES.md), [Guard: Complex Composition](docs/COMPLEX_COMPOSITION.md).\n\n**9) Where can I evaluate Guard policies?**\n\n\u003e Guard supports the entire spectrum of end-to-end evaluation of policy checks. The tool supports bringing in shift-left practices as close as running it directly at development time, integrated into code repositories via hooks like GitHub Actions for pull requests, and into CI/CD pipelines such as AWS CodePipeline pipelines and Jenkins (just exec process).\n\n**10) What are you not telling me? This sounds too good to be true.**\n\n\u003e Guard is a DSL and an accompanying CLI tool that allows easy-to-use definitions for declaring and enforcing policies. Today the tool supports local file-based execution of a category of policies. Guard doesn’t support the following things today, along with workarounds for some:\n\u003e\n\u003e 1. Sourcing of rules from external locations such as GitHub Release and S3 bucket. If you want this feature natively in Guard, please raise an issue or +1 an existing issue.\n\u003e 2. Ability to import Guard policy file by reference (local file or GitHub, S3, etc.). It currently only supports a directory on disk of policy files, that it would execute.\n\u003e 3. Parameter/Vault resolution for IaC tools such as CloudFormation or Terraform. Before you ask, the answer is NO. We will not add native support in Guard as the engine is general-purpose. If you need CloudFormation resolution support, raise an issue and we might have a solution for you. We do not support HCL natively. We do, however, support Terraform Plan in JSON to run policies against for deployment safety. If you need HCL support, raise an issue as well.\n\u003e 4. Ability to reference variables like `%s3_buckets`, inside error messages. Both JSON/Console output for evaluation results contain some of this information for inference. We also do not support using variable references to create dynamic regex expressions. However, we support variable references inside queries for cross join support, like `Resources.%references.Properties.Tags`.\n\u003e 5. Support for specifying variable names when accessing map or list elements to capture these values. For example, consider this check `Resources[resource_name].Properties.Tags not empty`, here `resource_name` captures the key or index value. The information is tracked as a part of the evaluation context today and present in both console/JSON outputs. This support will be extended to regex expression variable captures as well.\n\u003e 6. There are [known issues](docs/KNOWN_ISSUES.md) with potential workarounds that we are tracking towards resolution\n\n**11) What are we really thankful about?**\n\n\u003e Where do we start? Hmm.... we want to thank Rust [language’s forums](https://users.rust-lang.org/), [build management, and amazing ecosystem](https://crates.io/) without which none of this would have been possible. We are not the greatest Rust practitioners, so if we did something that is not idiomatic Rust, please raise a PR.\n\u003e\n\u003e We want to make a special mention to [nom](https://github.com/Geal/nom) combinator parser framework to write our language parser in. This was an excellent decision that improved readability, testability, and composition. We highly recommend it. There are some rough edges, but it’s just a wonderful, awesome library. Thank you. Apart from that, we are consumers of many crates including [hyper](https://crates.io/crates/hyper) for HTTP handling, [simple logger](https://crates.io/crates/simple_logger), and many more. We also want to thank the open-source community for sharing their feedback with us through GitHub issues/PRs.\n\u003e\n\u003e And of course AWS for supporting the development and commitment to this project. Now read the docs and take it for a ride and tell us anything and everything.\n\n## Guard DSL\n\n### Tenets\n\n**(Unless you know better ones)**\n\nThese tenets help guide the development of the Guard DSL:\n\n- **Simple**: The language must be simple for customers to author policy rules, simple to integrate with an integrated development environment (IDE), readable for human comprehension, and machine enforceable.\n\n- **Unambiguous**: The language must not allow for ambiguous interpretations that make it hard for customers to comprehend the policy evaluation. The tool is targeted for security and compliance related attestations that need the auditor to consistently and unambiguously understand rules and their evaluations.\n\n- **Deterministic**: The language design must allow language implementations to have deterministic, consistent, and isolated evaluations. Results for repeated evaluations for the same context and rules must evaluate to the same result every time. Time to evaluate results inside near-identical environments must be within acceptable tolerance limits.\n\n- **Composable**: The language must support composition to help build higher order functionality such as checks for PCI compliance, by easily combining building blocks together. Composition should not increase the complexity for interpreting outcomes, syntax, or navigation.\n\n### Features of Guard DSL\n\n- **Clauses:** Provides the foundational underpinning for Guard. They are assertions that evaluate to true or false. You can combine clauses using [Conjunctive Normal Form](https://en.wikipedia.org/wiki/Conjunctive_normal_form). You can use them for direct assertions, as part of filters to select values, or for conditional evaluations. To learn more read [Guard: Clauses](docs/CLAUSES.md)\n\n- **Context-Aware Evaluations, `this` binding and Loops:** Automatic binding for context values when traversing hierarchical data with support for implicit looping over collections with an easy-to-use syntax. Collections can arise from accessing an array of elements, values for a map along with a filter, or from a query. To learn more read [Guard: Context-Aware Evaluations, this and Loops](docs/CONTEXTAWARE_EVALUATIONS_AND_LOOPS.md)\n\n- **Query \u0026 Filtering:** Queries support simple decimal dotted format syntax to access properties in the hierarchical data. Arrays/Collections are accessed using `[]` . Map or Struct’s values can use `*` for accessing values for all keys. All collections can be further narrowed to target specific instances inside the collection using filtering. To learn more read [Guard: Query and Filtering](docs/QUERY_AND_FILTERING.md)\n\n- **Variables, Projections, and Query Interpolation:** Guard supports single shot assignment to variables using a **`let`** keyword for assignment. All variable assignments resulting from a query is a list (result set). One can also assign static literals to variables. Variables are assessed using a prefix **`%`** and can be used inside the Query for interpolation. To learn more read [Guard: Query, Projection and Interpolation](docs/QUERY_PROJECTION_AND_INTERPOLATION.md)\n\n- **Complex Composition**: As stated earlier, clauses can be expressed in Conjunctive Normal Form. Clauses on separates lines are ANDs. Disjunctions are expressed using the `or|OR` keyword. You can group clauses in a named rule. You can then use named rules in other rules to create more advanced compositions. Furthermore, you can have multiple files containing named rules that together form a category of checks for a specific compliance like “ensure encryption at rest”. To learn more read [Guard: Complex Composition](docs/COMPLEX_COMPOSITION.md)\n\n## Guard CLI\n\n### Installation\n\n#### Installation from Pre-Built Release Binaries\n\n##### MacOS\n\nBy default this is built for macOS-12 (Monterey). See [OS Matrix](https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#github-hosted-runners)\n\n1. Open terminal of your choice. Default `Cmd+Space`, type `terminal`\n2. Cut-n-paste the commands below (default latest, add `-s -- -v \u003cVERSION\u003e` for other versions ie. `-s -- -v 3.1.2`)\n\n```bash\n$ curl --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/aws-cloudformation/cloudformation-guard/main/install-guard.sh | sh\n```\n\nRemember to add `~/.guard/bin/` to your `$PATH`.\n\nAlternatively, you can install the latest version with [Homebrew](https://brew.sh/).\n\n```bash\n$ brew install cloudformation-guard\n```\n\nYou would not need to modify `$PATH` this way.\n\n##### Ubuntu\n\n1. Open any terminal of your choice\n2. Cut-n-paste the commands below (default latest, add `-s -- -v \u003cVERSION\u003e` for other versions ie. `-s -- -v 3.1.2`)\n\n```bash\n$ curl --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/aws-cloudformation/cloudformation-guard/main/install-guard.sh | sh\n```\n\nRemember to add `~/.guard/bin/` to your `$PATH`.\n\n##### Windows\n\n1. Open PowerShell as Administrator\n2. Cut-n-paste the command below\n\n```shell\n$GuardWindowsInstallScript = Invoke-WebRequest https://raw.githubusercontent.com/aws-cloudformation/cloudformation-guard/main/install-guard.ps1; Invoke-Expression $($GuardWindowsInstallScript.Content)\n```\n\nIf you get an error regarding authorization to execute the script run the follow before retrying step 2:\n\n```shell\nSet-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass\n```\n\n#### Installation of Rust and Cargo\n\n##### Ubuntu/MacOS: Install Rust and Cargo\n\n```bash\n$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh\n```\n\nIf you have not already, run `source $HOME/.cargo/env` as recommended by the rust installer. Read [here](https://rustup.rs/) for more information.\n\nIf building on `Ubuntu`, it is recommended to run `sudo apt-get update; sudo apt install build-essential`.\n\n##### Windows 10: Install Rust and Cargo\n\n1. Create a Windows 10 workspace.\n2. Install the version of Microsoft Visual C++ Build Tools 2019 which provides just the Visual C++ build tools: https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019.\n3. Download the installer and run it.\n4. Select the \"Individual Components\" tab and check \"Windows 10 SDK\".\n5. Select the \"Language Packs\" tab and make sure that at least \"English\" is selected.\n6. Click \"Install\".\n7. Let it download and reboot if asked.\n8. Install [Rust](https://forge.rust-lang.org/infra/other-installation-methods.html#other-ways-to-install-rustup).\n9. Download [rust-init.exe](https://static.rust-lang.org/rustup/dist/i686-pc-windows-gnu/rustup-init.exe).\n10. Run it and accept the defaults.\n\n#### Cargo-based Installation\n\nNow that you have [rust and cargo installed](https://doc.rust-lang.org/cargo/getting-started/installation.html), installation of cfn-guard is easy:\n\n```bash\n$ cargo install cfn-guard\n```\n\nCheck `help` to see if it is working.\n\n```bash\n$ cfn-guard help\ncfn-guard 3.1.2\n\n  Guard is a general-purpose tool that provides a simple declarative syntax to define\n  policy-as-code as rules to validate against any structured hierarchical data (like JSON/YAML).\n  Rules are composed of clauses expressed using Conjunctive Normal Form\n  (fancy way of saying it is a logical AND of OR clauses). Guard has deep\n  integration with CloudFormation templates for evaluation but is a general tool\n  that equally works for any JSON- and YAML- data.\n\nUsage: cfn-guard [COMMAND]\n\nCommands:\n  parse-tree   Prints out the parse tree for the rules defined in the file.\n  test         Built in unit testing capability to validate a Guard rules file against\n               unit tests specified in YAML format to determine each individual rule's success\n               or failure testing.\n\n  validate     Evaluates rules against the data files to determine success or failure.\n               You can point rules flag to a rules directory and point data flag to a data directory.\n               When pointed to a directory it will read all rules in the directory file and evaluate\n               them against the data files found in the directory. The command can also point to a\n               single file and it would work as well.\n               Note - When pointing the command to a directory, the directory may not contain a mix of\n               rules and data files. The directory being pointed to must contain only data files,\n               or rules files.\n\n  rulegen      Autogenerate rules from an existing JSON- or YAML- formatted data. (Currently works with only CloudFormation templates)\n  completions  Generate auto-completions for all the sub-commands in shell.\n  help         Print this message or the help of the given subcommand(s)\n\nOptions:\n  -h, --help     Print help\n  -V, --version  Print version\n\n```\n\n### How does Guard CLI work?\n\nThe two common Guard CLI commands are `validate` and `test`.\n\n#### Validate\n\nValidate command is used when you need to assess the compliance or security posture as defined by a set of policy files against incoming JSON/YAML data. Common data payloads used are CloudFormation Templates, CloudFormation ChangeSets, Kubernetes Pod policies, Terraform Plan/Configuration in JSON format, and more. Here is an example run of the `validate` command for assessing Kubernetes Pod Container configurations\n\n1. Save the sample policy rules file below as `k8s-pod-containers-limits.guard`:\n\n```\n#\n# Kubernetes container based limit checks\n#\n\n#\n# These set of rules primarily apply to the version 1 of the API spec (including v1Beta) and\n# the kind of document is a 'Pod'\n#\nrule version_and_kind_match\n{\n    apiVersion == /v1/\n    kind == 'Pod'\n}\n\n#\n# For the 'Pod' document ensure that containers have resource limits set\n# for memory\n#\nrule ensure_container_has_memory_limits when version_and_kind_match\n{\n    spec.containers[*]\n    {\n       resources.limits\n       {\n            #\n            # Ensure that memory attribute is set\n            #\n            memory exists\n            \u003c\u003c\n                Id: K8S_REC_22\n                Description: Memory limit must be set for the container\n            \u003e\u003e\n        }\n   }\n\n}\n\n#\n# For the 'Pod' document ensure that containers have resource limits set\n# for cpu\n#\nrule ensure_container_has_cpu_limits when version_and_kind_match\n{\n    spec.containers[*]\n    {\n       resources.limits\n       {\n            #\n            # Ensure that cpu attribute is set\n            #\n            cpu exists\n            \u003c\u003c\n                Id: K8S_REC_24\n                Description: Cpu limit must be set for the container\n            \u003e\u003e\n       }\n   }\n}\n```\n\n2. Paste the command below and hit `enter`\n\n```bash\ncfn-guard validate -r k8s-pod-containers-limits.guard\n```\n\n3. Cut-n-paste the sample configuration below for k8s pods on STDIN and then hit `CTRL+D`:\n\n```yaml\napiVersion: v1\nkind: Pod\nmetadata:\n  name: frontend\nspec:\n  containers:\n    - name: app\n      image: \"images.my-company.example/app:v4\"\n      resources:\n        requests:\n          memory: 64Mi\n          cpu: 0.25\n        limits:\n          memory: 128Mi\n    - name: log-aggregator\n      image: \"images.my-company.example/log-aggregator:v6\"\n      resources:\n        requests:\n          memory: 64Mi\n          cpu: 0.25\n        limits:\n          memory: 128Mi\n          cpu: 0.75\n```\n\n![Execution of validate](images/guard-validate.png)\n\nThe container `app` does not contain CPU limits specified, which fails the overall evaluation as shown in the screenshot.\n\n#### Using Input Parameters\n\nGuard allows you to use input parameters for dynamic data lookups during validation. This feature is particularly useful when you need to reference external data in your rules. However, when specifying input parameter keys, Guard requires that there are no conflicting paths.\n\n##### How to use\n\n1. Use the `--input-parameters` or `-i` flag to specify files containing input parameters. Multiple input parameter files can be specified and will be combined to form a common context. Input parameter keys can not have conflicting paths.\n2. Use the `--data` or `-d` flag to specify the actual template file to be validated.\n\n##### Example Usage\n\n1. Create an input parameter file (e.g., `network.yaml`):\n\n```yaml\nNETWORK:\n  allowed_security_groups: [\"sg-282850\", \"sg-292040\"]\n  allowed_prefix_lists: [\"pl-63a5400a\", \"pl-02cd2c6b\"]\n```\n\n2. Reference these parameters in your guard rule file (e.g., `security_groups.guard`):\n\n```\nlet groups = Resources.*[ Type == 'AWS::EC2::SecurityGroup' ]\n\nlet permitted_sgs = NETWORK.allowed_security_groups\nlet permitted_pls = NETWORK.allowed_prefix_lists\nrule check_permitted_security_groups_or_prefix_lists(groups) {\n    %groups {\n        this in %permitted_sgs or\n        this in %permitted_pls\n    }\n}\n\nrule CHECK_PERMITTED_GROUPS when %groups !empty {\n    check_permitted_security_groups_or_prefix_lists(\n       %groups.Properties.GroupName\n    )\n}\n```\n\n3. Create a failing data template (e.g., `security_groups_fail.yaml`):\n\n```yaml\n# ---\n# AWSTemplateFormatVersion: 2010-09-09\n# Description: CloudFormation - EC2 Security Group\n\nResources:\n  mySecurityGroup:\n    Type: \"AWS::EC2::SecurityGroup\"\n    Properties:\n      GroupName: \"wrong\"\n```\n\n4. Run the validate command:\n\n```\ncfn-guard validate -r security_groups.guard -i network.yaml -d security_groups_fail.yaml\n```\n\nIn this command:\n\n- `-r` specifies the rule file\n- `-i` specifies the input parameter file\n- `-d` specifies the data file (template) to be validated\n\n##### Multiple Input Parameters\n\nYou can specify multiple input parameter files:\n\n```\ncfn-guard validate -r rules.guard -i params1.yaml -i params2.yaml -d template.yaml\n```\n\nAll files specified with `-i` will be combined to form a single context for parameter lookup.\n\n#### Test\n\nTest command is used during the development of guard policy rules files. Test provides a simple integrated unit-test frameworks that allows authors to individually test each policy file for different types of inputs. Unit testing helps authors gain confidence that the rule does indeed conform to expectations. It can also be used as regression tests for rules. Here is example run for `test` command\n\n1. Save the sample policy rules file below as `api_gateway_private_access.guard`:\n\n```\n#\n# Select from Resources section of the template all ApiGateway resources\n# present in the template.\n#\nlet api_gws = Resources.*[ Type == 'AWS::ApiGateway::RestApi' ]\n\n#\n# Rule intent\n# a) All ApiGateway instances deployed must be private\n# b) All ApiGateway instances must have atleast one IAM policy condition key to allow access from a VPC\n#\n# Expectations:\n# 1) SKIP when there are not API Gateway instances in the template\n# 2) PASS when ALL ApiGateway instances MUST be \"PRIVATE\" and\n#              ALL ApiGateway instances MUST have one IAM Condition key with aws:sourceVpc or aws:SourceVpc\n# 3) FAIL otherwise\n#\n#\n\nrule check_rest_api_is_private when %api_gws !empty {\n  %api_gws {\n    Properties.EndpointConfiguration.Types[*] == \"PRIVATE\"\n  }\n}\n\nrule check_rest_api_has_vpc_access when check_rest_api_is_private {\n  %api_gws {\n    Properties {\n      #\n      # ALL ApiGateways must have atleast one IAM statement that has Condition keys with\n      #     aws:sourceVpc\n      #\n      some Policy.Statement[*] {\n        Condition.*[ keys == /aws:[sS]ource(Vpc|VPC|Vpce|VPCE)/ ] !empty\n      }\n    }\n  }\n}\n```\n\n2. Save the sample test file below as `api_gateway_private_access_tests.yaml`:\n\n```yaml\n---\n- input: {}\n  expectations:\n    rules:\n      check_rest_api_is_private: SKIP\n      check_rest_api_has_vpc_access: SKIP\n- input:\n    Resources: {}\n  expectations:\n    rules:\n      check_rest_api_is_private: SKIP\n      check_rest_api_has_vpc_access: SKIP\n- input:\n    Resources:\n      apiGw:\n        Type: AWS::ApiGateway::RestApi\n  expectations:\n    rules:\n      check_rest_api_is_private: FAIL\n      check_rest_api_has_vpc_access: SKIP\n- input:\n    Resources:\n      apiGw:\n        Type: AWS::ApiGateway::RestApi\n        Properties:\n          EndpointConfiguration:\n            Types: PRIVATE\n  expectations:\n    rules:\n      check_rest_api_is_private: PASS\n      check_rest_api_has_vpc_access: FAIL\n- input:\n    Resources:\n      apiGw:\n        Type: AWS::ApiGateway::RestApi\n        Properties:\n          EndpointConfiguration:\n            Types: [PRIVATE, REGIONAL]\n  expectations:\n    rules:\n      check_rest_api_is_private: FAIL\n      check_rest_api_has_vpc_access: SKIP\n- input:\n    Resources:\n      apiGw:\n        Type: AWS::ApiGateway::RestApi\n        Properties:\n          EndpointConfiguration:\n            Types: PRIVATE\n          Policy:\n            Statement:\n              - Action: Allow\n                Resource: \"*\"\n                Condition:\n                  StringLike:\n                    \"aws:sourceVPC\": vpc-12345678\n  expectations:\n    rules:\n      check_rest_api_is_private: PASS\n      check_rest_api_has_vpc_access: PASS\n```\n\n3. Run the test command\n\n```bash\ncfn-guard test -r api_gateway_private_access.guard -t api_gateway_private_access_tests.yaml\n```\n\n![Execution of test](images/guard-test.png)\n\nRead [Guard: Unit Testing](docs/UNIT_TESTING.md) for more information on unit testing. To know about other commands read the [Readme in the guard directory](guard/README.md).\n\n## \u003ca name=\"references\"\u003e\u003c/a\u003e Rule authoring references\n\nAs a starting point for writing Guard rules for yourself or your organisation we recommend following [this official guide](https://docs.aws.amazon.com/cfn-guard/latest/ug/writing-rules.html)\n\n### Quick links:\n\n[Writing AWS CloudFormation Guard rules](https://docs.aws.amazon.com/cfn-guard/latest/ug/writing-rules.html)\n\n1. [Clauses](https://docs.aws.amazon.com/cfn-guard/latest/ug/writing-rules.html#clauses)\n2. [Using queries in clauses](https://docs.aws.amazon.com/cfn-guard/latest/ug/writing-rules.html#clauses-queries)\n3. [Using operators in clauses](https://docs.aws.amazon.com/cfn-guard/latest/ug/writing-rules.html#clauses-operators)\n4. [Using custom messages in clauses](https://docs.aws.amazon.com/cfn-guard/latest/ug/writing-rules.html#clauses-custom-messages)\n5. [Combining clauses](https://docs.aws.amazon.com/cfn-guard/latest/ug/writing-rules.html#combining-clauses)\n6. [Using blocks with Guard rules](https://docs.aws.amazon.com/cfn-guard/latest/ug/writing-rules.html#blocks)\n7. [Defining queries and filtering](https://docs.aws.amazon.com/cfn-guard/latest/ug/query-and-filtering.html)\n8. [Assigning and referencing variables in AWS CloudFormation Guard rules](https://docs.aws.amazon.com/cfn-guard/latest/ug/variables.html)\n9. [Composing named-rule blocks in AWS CloudFormation Guard](https://docs.aws.amazon.com/cfn-guard/latest/ug/named-rule-block-composition.html)\n10. [Writing clauses to perform context-aware evaluations](https://docs.aws.amazon.com/cfn-guard/latest/ug/context-aware-evaluations.html)\n\n## \u003ca name=\"functions\"\u003e\u003c/a\u003e Built-in functions \u0026 stateful rules\n\nGuard 3.0 introduces support for functions, allowing for stateful rules that can run on a value that's evaluated based\non some properties extracted out of a data template.\n\n### Sample template\n\nImagine we have a property in our template which consists of a list called as `Collection` and we need to ensure\nit has at least 3 items in it.\n\n```yaml\nResources:\n  newServer:\n    Type: AWS::New::Service\n    Collection:\n      - a\n      - b\n```\n\n### Sample rule\n\nWe can write a rule to check this condition as follows:\n\n```\nlet server = Resources.*[ Type == 'AWS::New::Service' ]\nrule COUNT_CHECK when %server !empty {\n    let collection = %server.Collection.*\n    let count_of_items = count(%collection)\n    %count_of_items \u003e= 3\n    \u003c\u003c\n      Violation: Collection should contain at least 3 items\n    \u003e\u003e\n}\n```\n\nExpected outcome is that rule fails showing us the violation message since our template is non-compliant.\n\nFor detailed documentation regarding all supported functions, please [follow this link](./docs/FUNCTIONS.md). For limitations of functions usage, please read [this note](./docs/KNOWN_ISSUES.md#function-limitation).\n\n## \u003ca name=\"registry\"\u003e\u003c/a\u003e AWS Rule Registry\n\nAs a reference for Guard rules and rule-sets that contain (on a best-effort basis) the compliance policies that adhere\nto the industry best practices around usages across AWS resources, we have recently launched\n[AWS Guard Rules Registry](https://github.com/aws-cloudformation/aws-guard-rules-registry).\n\n## \u003ca name=\"docker\"\u003e\u003c/a\u003e Use Guard as a Docker Image\n\nGuard is also published as an ECR image in [ECR public gallery](https://gallery.ecr.aws/aws-cloudformation/cloudformation-guard) and can be used as an image in a docker container.\n\n### Prerequisites\n\n1. Install docker. Follow [this guide](https://docs.docker.com/engine/install/).\n1. Have a directory ready on the host you are downloading the docker image to that contains data templates and Guard rules you are planning to use, we may mount this directory and use the files as input to `cfn-guard`. We'll refer this directory to be called `guard-files` in the rest of this guide\n\n### Usage Guide\n\nTo use the binary, we should pull the latest docker image, we may do so using the following command:\n\n```bash\ndocker pull public.ecr.aws/aws-cloudformation/cloudformation-guard:latest\n```\n\nNow go ahead and run the docker image, using the files from directory we have our templates and rules file in, using:\n\n```bash\ndocker run \\\n  --mount src=/path/to/guard-files,target=/container/guard-files,type=bind \\\n  -it public.ecr.aws/aws-cloudformation/cloudformation-guard:latest \\\n  ./cfn-guard validate -d /container/guard-files/template.yml -r /container/guard-files/rule.guard\n```\n\nWe should see the evaluation result emitted out on the console.\n\n### Tagging convention\n\n- We use the tag `latest` for the most recent docker image that gets published in sync with `main` branch of the `cloudformation-guard` GitHub repository.\n- We use the convention `\u003cbranch_name\u003e.\u003cgithub_shorthand_commit_hash\u003e` for tags of historical docker images\n\n## \u003ca name=\"ci\"\u003e\u003c/a\u003e Use Guard as a CI tool\n\nGuard is great for CI checks with the Junit output format, making the process of validating or testing your templates seamless and simple. Check out the examples below.\n\n### GitHub Actions\n\n#### Junit\n\n![GitHub Actions](images/github.png)\n\n[Get the template here!](https://github.com/aws-cloudformation/cloudformation-guard/tree/main/guard-examples/ci/.github/workflows/junit-test-and-validate.yml)\n\n#### SARIF\n\n![GitHub Actions](images/sarif-gh.png)\n\n[Get the template here!](https://github.com/aws-cloudformation/cloudformation-guard/tree/main/guard-examples/ci/.github/workflows/sarif-validate.yml)\n\n### CircleCI\n\n#### Junit\n\n![CircleCI](images/circleci.png)\n\n[Get the template here!](https://github.com/aws-cloudformation/cloudformation-guard/tree/main/guard-examples/ci/.circleci/config.yml)\n\n## \u003ca name=\"pre-commit-hook\"\u003e\u003c/a\u003e Use Guard as a pre-commit hook\n\nGuard is available as a pre-commit hook and offers both the `test` and `validate` operations. You can use them by adding a variation of the following configuration to your `.pre-commit-config.yaml` file:\n\n```yaml\n# Since the cfn-guard hook's tagging strategy is incompatible\n# with pre-commit's autoupdate feature, you may want to use\n# the pre-commit-update hook. If you don't require the autoupdate\n# feature, you may skip the pre-commit-update hook.\nrepos:\n  # pre-commit-update hook\n  - repo: https://gitlab.com/vojko.pribudic.foss/pre-commit-update\n    rev: v0.5.0\n    hooks:\n      - id: pre-commit-update\n        args: [--tag-prefix, cloudformation-guard, pre-commit-v]\n  # cfn-guard pre-commit hook\n  - repo: https://github.com/aws-cloudformation/cloudformation-guard\n    rev: pre-commit-v0.0.2\n    hooks:\n      # Validate\n      - id: cfn-guard\n        args:\n          - --operation=validate # Specify the validate operation\n          - --rules=path/to/rules/ # Rules directory\n        files: ^path/to/data/.* # Directory to watch for changes and validate against\n      # Test\n      - id: cfn-guard\n        args:\n          - --operation=test # Specify the test operation\n          - --dir=path/to/resources/ # Directory that contains rules \u0026 their tests\n        files: ^path/to/resources.* # Same directory supplied to the --dir arg so that rule and test file changes trigger a run\n```\n\n**NOTE**: The args for the pre-commit hook are not identical to the flags you would pass directly to Guard. In the case of this hook, you cannot pass a `data` flag to `validate` as it depends on the `filenames` from the hook and you can only use the `dir` flag for the `test` hook.\n\n## \u003ca name=\"devcontainer\"\u003e\u003c/a\u003e Contribute using the DevContainer in VSCode\n\n### Setup\n\n**NOTE**: The devcontainer supports zsh and bash with theming and aliases. You can choose which shell you like in the terminal options in your VSCode session.\n\n1. Follow the prerequisite instructions [here](https://code.visualstudio.com/learn/develop-cloud/containers).\n1. In VSCode following the install, open the command palette.\n1. Search \"Dev Containers: Build Container\"\n1. Once done, open the project inside the container.\n\n### Aliases\n\n- `gval`: `cargo run --bin cfn-guard validate`\n- `gtest`: `cargo run --bin cfn-guard test`\n- `gparse`: `cargo run --bin cfn-guard parse-tree`\n- `cb`: `cargo build`\n- `ct`: `cargo nextest run`\n- `cn`: `cargo +nightly`\n\n## License\n\nThis project is licensed under the Apache-2.0 License.\n","funding_links":[],"categories":["Policy as code","Public Cloud Governance","Rust","terraform","Authoring and Testing Tools","Other"],"sub_categories":["AWS Governance","Hooks"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faws-cloudformation%2Fcloudformation-guard","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faws-cloudformation%2Fcloudformation-guard","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faws-cloudformation%2Fcloudformation-guard/lists"}