diff --git a/testbed/aws-cloudformation__cfn-lint/.pre-commit-config.yaml b/testbed/aws-cloudformation__cfn-lint/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1598ad124e314ff7727b2d2af899c5ca07c3cd25 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/.pre-commit-config.yaml @@ -0,0 +1,44 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.6.0 + hooks: + - id: check-ast + - id: check-json + exclude: "(test/fixtures/templates/bad/json_parse.json|test/fixtures/templates/bad/core/config_invalid_json.json|test/fixtures/templates/bad/duplicate.json)" + - id: check-toml + - id: check-vcs-permalinks + - id: check-yaml + exclude: "test/fixtures/templates/" + args: [--unsafe] + - id: debug-statements + - id: end-of-file-fixer + - id: mixed-line-ending + args: [--fix, auto] + - id: trailing-whitespace + - repo: https://github.com/psf/black + rev: 24.8.0 + hooks: + - id: black + - repo: https://github.com/PyCQA/isort + rev: 5.13.2 + hooks: + - id: isort + - repo: https://github.com/charliermarsh/ruff-pre-commit + rev: "v0.5.7" + hooks: + - id: ruff + - repo: https://github.com/PyCQA/bandit + rev: "1.7.9" + hooks: + - id: bandit + additional_dependencies: + - "bandit[toml]" + args: ["-c", "pyproject.toml"] + - repo: https://github.com/pre-commit/mirrors-mypy + rev: "v1.11.1" + hooks: + - id: mypy + additional_dependencies: + - "types-PyYAML" + - "types-regex" + - "types-requests" diff --git a/testbed/aws-cloudformation__cfn-lint/.pre-commit-hooks.yaml b/testbed/aws-cloudformation__cfn-lint/.pre-commit-hooks.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fe90c3f0b381f314139b04ff1cb17bdbdba9b90f --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/.pre-commit-hooks.yaml @@ -0,0 +1,18 @@ +- id: cfn-python-lint + name: AWS CloudFormation Linter + description: 'cfn-lint is a tool for finding issues with CloudFormation templates' + entry: cfn-lint + language: python + files: \.(json|yaml|yml)$ +- id: cfn-lint # we have removed most identifications to cfn-python-lint + name: AWS CloudFormation Linter + description: 'cfn-lint is a tool for finding issues with CloudFormation templates' + entry: cfn-lint + language: python + files: \.(json|yaml|yml)$ +- id: cfn-lint-rc # Provide a configuration to use with .cfnlintrc + name: AWS CloudFormation Linter + description: 'cfn-lint is a tool for finding issues with CloudFormation templates' + entry: cfn-lint + language: python + pass_filenames: false diff --git a/testbed/aws-cloudformation__cfn-lint/CHANGELOG.md b/testbed/aws-cloudformation__cfn-lint/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..7567caa2f75610a28f5679b50a833382eda351b0 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/CHANGELOG.md @@ -0,0 +1,3162 @@ +### v1.19.0 +## What's Changed +* Update CloudFormation schemas to `2024-11-07` by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3811 +* Fix [E3006](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3006) when both True and False are returned from `build_scenerios_on_region` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3813 +* Fix an issue when printing the graph overwriting the graph by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3814 +* Update [E1010](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1010) lang ext function support by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3817 +* Increase logic of boto automation by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3818 +* Allow `cloudfront` to be used in ARNs for account ID by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3821 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.18.4...v1.19.0 + +### v1.18.4 +## What's Changed +* Add `AutoRetryLimit` for `AWS::CodeBuild::Project` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3809 +* Fix validating min/maxLength whena property has an array for keyword `type` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3805 +* Update CloudFormation schemas to `2024-11-01` by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3807 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.18.3...v1.18.4 + +### v1.18.3 +## What's Changed +* Enhanced monitoring can be configured on aurora clusters by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3801 +* Update CloudFormation schemas to `2024-10-30` by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3799 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.18.2...v1.18.3 + +### v1.18.2 +## What's Changed +* Update more tests for condition keys by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3781 +* Update `Fn::FindInMap` resolver to handle `Ref` to psedueparams by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3785 +* Create a new jsonschema keyword `enumCaseInsensitive` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3789 +* Trim comma delimited lists for context by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3790 +* Update [E1029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1029) to support `Definition` in exceptions by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3792 +* Allow `5.7`/`8.0` for DB Engine Version by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3796 +* Update CloudFormation schemas to `2024-10-28` by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3795 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.18.1...v1.18.2 + +### v1.18.1 +## What's Changed +* Fix policy schema condition key patterns by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3779 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.18.0...v1.18.1 + +### v1.18.0 +## What's Changed +* Add `additionalProperties` false to IAM conditions by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3767 +* Update [E3601](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3601) to handle substitutions in rule by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3768 +* Update [E3601](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3601) to skip state machine validation when using a function by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3770 +* Add `^.*$` to exceptions for boto pattern detection by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3772 +* Bump `docker/library/python` from `3.12-alpine3.20` to `3.13-alpine3.20` by @dependabot in https://github.com/aws-cloudformation/cfn-lint/pull/3773 +* Expand boto auto detection to include sub properties by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3763 +* Update CloudFormation schemas to `2024-10-21` by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3758 +* Add logic for `AWS::EC2::Subnet.Id` format by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3761 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.17.2...v1.18.0 + +### v1.17.2 +## What's Changed +* Update language extensions `Fn::ForEach` for empty lists by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3764 +* Support Python 3.13 by @michael-k in https://github.com/aws-cloudformation/cfn-lint/pull/3765 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.17.1...v1.17.2 + +### v1.17.1 +## What's Changed +* Make an exception for DocDB Cluster Port return type by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3759 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.17.0...v1.17.1 + +### v1.17.0 +## What's Changed +* Update test results for `py3.8` deprecation by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3745 +* Add automation to creating boto patches by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3742 +* Update `Dockerfile` image location to ECR by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3746 +* Dynamically determine Account ID during transform by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3749 +* Update graph labels by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3752 +* Update lambda lifecycle runtimes by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3753 +* Update `HealthCheckType` enum for `AWS::AutoScaling::AutoScalingGroup` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3755 +* Update CloudFormation schemas to `2024-10-17` by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3748 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.16.1...v1.17.0 + +### v1.16.1 +## What's Changed +* Move `requireXor` to `SpotFleetRequestConfigData` by @stevengubler in https://github.com/aws-cloudformation/cfn-lint/pull/3737 +* Update CloudFormation schemas to `2024-10-10` by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3736 + +## New Contributors +* @stevengubler made their first contribution in https://github.com/aws-cloudformation/cfn-lint/pull/3737 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.16.0...v1.16.1 + +### v1.16.0 +## What's Changed +* Switch SAM validation [E3031](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3031) to use pre-transform by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3726 +* Bring back stateful resources json by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3728 +* Update GetAtt type checking by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3731 +* Add `MinActiveInstancesPercent` to `AutoScalingRollingUpdate` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3733 +* Update CloudFormation schemas to `2024-10-03` by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3732 and https://github.com/aws-cloudformation/cfn-lint/pull/3723 +* Update `requiredXor` for Vpc and Subnets by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3734 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.15.2...v1.15.3 + +### v1.15.2 +## What's Changed +* Exception for lambda authorizer uri by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3720 +* Update CloudFormation schemas to 2024-09-30 by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3709 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.15.1...v1.15.2 + +### v1.15.1 +## What's Changed +* Switch FN support inside Rules by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3712 +* Add equal vars for Rules to cnf building by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3714 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.15.0...v1.15.1 + +### v1.15.0 +## What's Changed +* Update state machine to support `StringMatches` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3705 +* Add rules for `Rules` section by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3703 +* Allow for secretsmanager dynamic refs in `Parameter` defaults by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3707 +* Update CloudFormation schemas to `2024-09-23` by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3702 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.14.2...v1.15.0 + +### v1.14.2 +## What's Changed +* Move KMS validation for `SSESpecification` on Tables by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3700 +* Update CloudFormation schemas to `2024-09-19` by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3698 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.14.1...v1.14.2 + +### v1.14.1 +## What's Changed +* Add [W3693](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W3693) for aurora cluster properties by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3695 +* Update ARN AWS regex in [E3601](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3601) by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3696 +* Update CloudFormation schemas to `2024-09-17` by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3692 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.14.0...v1.14.1 + +### v1.14.0 +## What's Changed +* Cloud9 ImageIds can be an alias by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3679 +* Exceptions for hardcoded authorizer uri in I3042 by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3684 +* Associate[CarrierIpAddress|PublicIpAddress] not with `NetworkInterfaceId` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3685 +* Escape pattern matching when using SAM and SSM parameter default value by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3686 +* Switch event rule `requiredXor` to `requiredOr` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3688 +* Bump peter-evans/create-pull-request from 6 to 7 by @dependabot in https://github.com/aws-cloudformation/cfn-lint/pull/3689 +* Bump pypa/gh-action-pip-audit from 1.0.8 to 1.1.0 by @dependabot in https://github.com/aws-cloudformation/cfn-lint/pull/3690 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.13.0...v1.14.0 + +### v1.13.0 +## What's Changed +* Add rule [E3674](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3674) to validate instance `PrivateIpAddress` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3657 +* Update schemas to not allow `Ipv6Addresses` and `Ipv6AddressCount` on `AWS::EC2::NetworkInterface` together by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3656 +* Update [E3044](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3044) to allow `EXTERNAL` to not have `REPLICA` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3670 +* Add rule [E3056](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3056) to validate `HealthCheckGracePeriodSeconds` on `AWS::ECS::Service` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3671 +* Update CloudFormation schemas to 2024-09-09 by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3647 +* Fail gracefully if no templates match wildcard by @thecodingsysadmin in https://github.com/aws-cloudformation/cfn-lint/pull/3603 + +## New Contributors +* @thecodingsysadmin made their first contribution in https://github.com/aws-cloudformation/cfn-lint/pull/3603 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.12.4...v1.13.0 + +### v1.12.4 +## What's Changed +* Return Symbol instead of None on Fn::Equals logic by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3663 +* Remove handlers and tagging/permissions from specs by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3661 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.12.3...v1.12.4 + +### v1.12.3 +## What's Changed +* Allow for patch in place by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3649 +* Add integration tests for AZ schema changes by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3655 +* Better support for rule Equals when static by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3659 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.12.2...v1.12.3 + +### v1.12.2 +## What's Changed +* Don't resolve pseudoparams in findinmap by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3653 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.12.1...v1.12.2 + +### v1.12.1 +## What's Changed +* Undo https://github.com/aws-cloudformation/cfn-lint/pull/3639 by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3650 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.12.0...v1.12.1 + +### v1.12.0 +## What's Changed +* GetAtts to array returns a string by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3639 +* Add Condition logic for template Rules by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3634 +* Another fix to pretty printer by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3641 +* Add ap-southeast-5 by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3624 +* Bring back better findinmap resolution by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3579 +* Prevent infinite loops in conditions by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3645 +* Update CloudFormation schemas to 2024-09-03 by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3644 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.11.1...v1.12.0 + +### v1.11.1 +## What's Changed +* Fix an issue with `dict_node` `get` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3628 +* Add params to findinmap value by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3629 +* Allow `Fn::Length` in `Fn::Select` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3633 +* Allow resource version to be an `integer` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3637 +* Add more exceptions [E1040](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1040) by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3636 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.11.0...v1.11.1 + +### v1.11.0 +## What's Changed +* Create rule [E3055](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3055) to validate CreationPolicy by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3609 +* Update CloudFormation schemas to 2024-08-21 by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3602 +* Generate schema artifacts on release by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3611 +* Fix integration tests by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3615 +* Add assumed role to policy AWS by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3621 +* Fix pretty print with pipes by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3622 +* Require at least one element in LSI `if` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3623 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.10.3...v1.11.0 + +### v1.10.3 +## What's Changed +* Look at `OriginGroups` too for rule [E3057](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3057) by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3607 +* Continue on template decode errors by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3605 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.10.2...v1.10.3 + +### v1.10.2 +## What's Changed +* Fix an issue when scanning metadata by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3596 +* Update getatt resolution for better regional support by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3597 +* anyOf only returns Ws and Is when there are Es by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3600 +* Update CloudFormation schemas to 2024-08-15 by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3591 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.10.1...v1.10.2 + +### v1.10.1 +## What's Changed +* Update rule [E3054](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3054) to not alert when `NetworkMode` is set to `awsvpc` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3593 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.10.0...v1.10.1 + +### v1.10.0 +## What's Changed +* Add rule [E3052](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3052), [E3053](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3053), [E3054](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3054) to validate ECS configs by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3546 +* Add rule to [E3057](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3057) to validate TargetOriginId in a DefaultCacheBehavior by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3561 +* Update CloudFormation schemas to 2024-08-12 by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3581 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.9.7...v1.10.0 + +### v1.9.7 +## What's Changed +* Add Value to path in [E6101](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E6101) as we descend by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3582 +* Smarter flow to rule [E6101](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E6101) by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3583 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.9.6...v1.9.7 + +### v1.9.6 +## What's Changed +* Update schema patching and fix some issues by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3570 +* Update regex pattern for rule I3042 by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3572 +* Better logic for empty yaml files by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3574 +* Update pre-commit to 2024-08-08 by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3575 +* Update CloudFormation schemas to 2024-08-08 by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3569 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.9.5...v1.9.6 + +### v1.9.5 +## What's Changed +* Increase the max value of `AWS::Cognito::UserPoolClient#RefreshTokenValidity` to `315360000` by @BR0kEN- in https://github.com/aws-cloudformation/cfn-lint/pull/3567 +* Update CloudFormation schemas to 2024-08-05 by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3539 + +## New Contributors +* @BR0kEN- made their first contribution in https://github.com/aws-cloudformation/cfn-lint/pull/3567 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.9.4...v1.9.5 + +### v1.9.4 +## What's Changed +* Add logic to handle Ref `AWS::NoValue` in list by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3563 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.9.3...v1.9.4 + +### v1.9.3 +## What's Changed +* Update schema filtering to use new condition logic by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3552 +* Update [E3615](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3615) to validate all CloudWatch Alarm periods by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3556 +* Better type checking for `null` types by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3557 +* Add `dependentExcluded` for `AbortIncompleteMultipartUpload` in `AWS::S3::Bucket` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3558 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.9.2...v1.9.3 + +### v1.9.2 +## What's Changed +* Update [W3663](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W3663) to skip validation when Sub by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3548 +* Update [E3673](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3673) to return the rule in `ValidationError` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3548 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.9.1...v1.9.2 + +### v1.9.1 +## What's Changed +* Update rule [E3049](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3049) to only trigger when host port is 0 by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3543 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.9.0...v1.9.1 + +### v1.9.0 +## What's Changed +* Better iam policies by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3530 +* Create rule [W3663](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W3663) to validate lmbd permission account by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3523 +* Context condition logic by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3532 +* Create rule [E3673](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3673) to validate ImageId being required on an instance by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3513 +* Create rule [E3049](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3049) to validate ECS Task/Service and LB target configuration with dynamic host ports by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3513 +* Allow more types in Metadata by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3536 +* Update CloudFormation schemas to 2024-07-29 by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3533 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.8.2...v1.9.0 + +### v1.8.2 +## What's Changed +* `AutoMinorVersionUpgrade` can be used with Aurora clusters by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3522 +* A bunch of fixes for state machines by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3528 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.8.1...v1.8.2 + +### v1.8.1 +## What's Changed +* Don't scan `DefinitionString` in rule [E3601](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3601) @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3519 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.8.0...v1.8.1 + +### v1.8.0 +## What's Changed +* Add rule [E3663](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3663) to validate lambda fn env vars by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3505 +* Allow for vCPU and GB in ECS task rules [E3047](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3047) and [E3048](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3048) by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3515 +* Update CloudFormation schemas to 2024-07-17 by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3504 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.7.2...v1.8.0 + +### v1.7.2 +## What's Changed +* Add 1.0 to SSM document versions by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3511 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.7.1...v1.7.2 + +### v1.7.1 +## What's Changed +* Fix sub regex resolver to always return a string by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3508 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.7.0...v1.7.1 + +### v1.7.0 +## What's Changed +* Don't validate [W2001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2001) when using Transform by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3501 +* Fix an issue with endless loops in Fn::Sub by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3503 +* Move rule to [E2532](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2532) to [E3601](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3601) by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3502 +* Add start to SSM json schemas by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3471 +* Add two new rules to validate fargate tasks by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3464 +* Update CloudFormation schemas to 2024-07-15 by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3494 +* Convert resolver errors to warnings by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3493 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.6.1...v1.7.0 + +### v1.6.1 +## What's Changed +* SAM transform replace AutoPublishCodeSha256 by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3497 +* Change return type of conditions `build_scenerios_on_region` to be a `list[bool]` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3498 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.6.0...v1.6.1 + +### v1.6.0 +## What's Changed +* Update CloudFormation schemas to 2024-07-11 by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3484 +* Return all errors from resolution by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3489 +* Disable [W1020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W1020) when using SAM by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3491 +* Use region when looking for a resolver being satisfied by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3490 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.5.3...v1.6.0 + +### v1.5.3 +## What's Changed +* Load registry schemas before implementing patching by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3486 +* Force resolve validation to not use strict types by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3488 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.5.2...v1.5.3 + +### v1.5.2 +## What's Changed +* Update CloudFormation schemas to 2024-07-09 by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3457 +* Update logging configuration to not log when used as a library by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3479 +* Add `AWS::ServiceCatalog::CloudFormationProvisionedProduct` to exceptions for [E1040](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1040) by @kylekluever in https://github.com/aws-cloudformation/cfn-lint/pull/3481 +* Allow ICMP to have `FromPort` other than -1 with `ToPort` -1 by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3482 + +## New Contributors +* @kylekluever made their first contribution in https://github.com/aws-cloudformation/cfn-lint/pull/3481 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.5.1...v1.5.2 + +### v1.5.1 +## What's Changed +* Switch type comparison in BaseFn to use is_types_compatible by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3461 +* Update [E2015](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2015) to split defaults on comma by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3466 +* Don't fail `anyOf` on warnings by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3469 +* Allow `Transform` section to have the full transform def by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3470 +* Update `GetAtt` logic for `AWS::ServiceCatalog::CloudFormationProvisionedProduct` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3475 +* Remove `requiredXor` for `AWS::EC2::Instance` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/#3477 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.5.0...v1.5.1 + +### v1.5.0 +## What's Changed +* Update mappings to support transforms at the root level by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3439 +* Update `CfnLintJsonSchema` based rules for dynamic references by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3442 +* Fix tagging examples by @michael-k in https://github.com/aws-cloudformation/cfn-lint/pull/3448 +* Add `full` keyword to optional dependencies by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3454 +* Load registry schemas if type match by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3450 +* Update helpers.py with DocDB snapshot type by @marty-sullivan in https://github.com/aws-cloudformation/cfn-lint/pull/3455 +* Update CloudFormation schemas to 2024-07-02 by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3447 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.4.2...v1.5.0 + +### v1.4.2 +## What's Changed +* Fix JSON based tags for many types by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3437 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.4.1...v1.4.2 + +### v1.4.1 +## What's Changed +* Fix JSON based tags for many of the Glue types by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3434 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.4.0...v1.4.1 + +### v1.4.0 +## What's Changed +* Default `EngineMode` for [E3686](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3686) is `provisioned` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3425 +* Update docdb engine version to have `5.0.0` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3428 +* In legacy RulesCollection validate the rule is enabled before returning result by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3429 +* Convert all json properties to support `string` and `object` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3423 +* Patch in better validation for `Tags` properties that just have `type` `object` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3423 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.3.7...v1.4.0 + +### v1.3.7 +## What's Changed +* Consider output conditions in [E6101](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E6101) by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3414 +* Bring back `Transform` after SAM removes them by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3417 +* Handle `Fn::Transform`s inside Mappings by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3419 +* Add logic to update [E3682](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3682) to require `Engine` by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3419 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.3.6...v1.3.7 + +### v1.3.6 +## What's Changed +* Remove falsy issues with FindInMap resolution by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3410 +* Remove resolution errors when default value Ref AWS::NoValue and bad mappings in FindInMap by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3410 +* Patch AWS::ImageBuilder::ContainerRecipe.InstanceConfiguration by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3413 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.3.5...v1.3.6 + +### v1.3.5 +## What's Changed +* Allow Ref AWS::NoValue in FindInMap parameters by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3399 +* Update policy principal validation logic by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3400 +* Add Fn::Cidr as Fn::Join supported function by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3401 +* Update CloudFormation schemas to 2024-06-25 by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3313 +* Return resolution errors by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3402 +* Don't issue dynamicref issues in other fns by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3404 +* Greatly simplify `FindInMap` resolution by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3406 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.3.4...v1.3.5 + +### v1.3.4 +## What's Changed +* Clean up errors in the schemas by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3375 +* Relax [E3041](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3041) to support DNS root records by @jakob-keller in https://github.com/aws-cloudformation/cfn-lint/pull/3377 +* Allow `AllowedPattern` with AWS type parameters by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3388 +* Default fn validator context will be not strict type checking by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3386 +* Update IAM resource ARN patterns by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3389 +* Update resolution validation to only return an error if there are no valid values by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3390 +* Better resolution of mappings in transform by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3392 + + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.3.3...v1.3.4 + +### v1.3.3 +## What's Changed +* Remove rule setting in `PropertyNames` rule by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3365 +* update logic in rule [E3686](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3686) by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3367 +* Patch `AWS::Glue::SecurityConfiguration` and other resource issues by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3371 +* Parameter of `List` can have an integer default by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3372 +* Better comparison of json schema types for cfn usage by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3373 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.3.2...v1.3.3 + +### v1.3.2 +## What's Changed +* Switch max condition logic to attemptes over returned by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3359 +* Update maintenance job to get data from boto by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3361 +* Update md5 creation to work better on FIPS compliant OSes by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3362 +* Add in awslogs-create-group to ECS task logging by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3363 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.3.1...v1.3.2 + +### v1.3.1 +## What's Changed +* Update some docs by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3314 +* Update policy can have non strict types by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3315 +* Add AWS::SSM::Parameter::Value to use AllowedPattern by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3332 +* Allow `Fn::GetAtt` to be an array in Join by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3333 +* Skip empty strings in action validation by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3337 +* Don't validate dynamic references inside fn by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3335 +* Only escape type checking for pkg params when strict types is false by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3338 +* Remove additionalItems in prefix validation by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3339 +* Remove pattern from tag key/value validation by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3341 +* Add logic to ImageId format for SSM by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3340 +* Remove Refs to yourself in Fn::Sub by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3342 +* Update resource pattern for policy validation by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3343 +* Update logic on GetAtts for resources that have all attrs by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3344 +* Allow capital letters for rule W3687 by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3345 +* Skip getatt validation with custom resources by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3346 +* Remove AWS::EC2::LaunchTemplate requiredXor value for data by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3347 +* Update Null conditions to be scalar or singular by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3349 +* Condition satisfaction checks to raise error when unknown by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3350 +* Remove \/ as valid escape in yaml by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3331 +* Update CodeBuild::Project FilterGroup types by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3351 +* Update SQS MessageRetentionPeriod minimum by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3355 +* Backwards compatiblity for cloudformation-cli module validation by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3354 +* Allow OAI IDs in IAM policies by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3357 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.3.0...v1.3.1 + +### v1.3.0 +## What's Changed +* Allow IAM principal to be str or a list by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3306 +* Update CloudFormation schemas to 2024-06-18 by @github-actions in https://github.com/aws-cloudformation/cfn-lint/pull/3309 +* Array of strings are allowed as output value types by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3312 + + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.2.5.a11...v1.3.0 + +### v1.2.5a11 +## What's Changed +* Update CloudFormation schemas to 2024-06-17 by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3299 +* Cleanup rule pytest logic to make life easier by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3285 +* Cleanup `cfn_path` generation by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3287 +* Add error catching to better handle rule issues by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3289 +* Fix an issue with SSM params for ForEach by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3294 +* V1 - more typing and cleanup by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3296 +* Update resolver logic to see if parameter will result in applied conditions still being valid by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3303 +* Update rule [W2531](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2531) to validate when the specified runtime is deprecated by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3304 +* Update rule [E2531](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2531) to validate when you can no longer create a lambda function with the specified runtime by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3304 +* Create rule [E2533](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2533) to validate when you can no longer update a lambda function with the specified runtime by @kddejong in https://github.com/aws-cloudformation/cfn-lint/pull/3304 + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.2.5.a10...v1.2.5.a11 + +### v1.2.5a10 +## What's Changed +* Update CloudFormation schemas to `2024-06-07` by @kddejong in (pull #[3249](https://github.com/aws-cloudformation/cfn-lint/pull/3249)) +* Add rule [E3040](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3040) to validate a developer isn't using a read only property by @kddejong in (pull #[3275](https://github.com/aws-cloudformation/cfn-lint/pull/3275)) +* Add AWS custom `format` types `AWS::EC2::SecurityGroup.GroupId`, `AWS::EC2::SecurityGroup.GroupName` by @kddejong in (pull #[3274](https://github.com/aws-cloudformation/cfn-lint/pull/3274)) +* Add AWS custom `format` types `AWS::EC2::VPC.Id`, `AWS::EC2::Image.Id` by @kddejong in (pull #[3271](https://github.com/aws-cloudformation/cfn-lint/pull/3271)) +* Break resolver functionality into its own package by @kddejong in (pull #[3271](https://github.com/aws-cloudformation/cfn-lint/pull/3271)) +* Remove `awsType` and convert them to `cfnLint` keyword by @kddejong in (pull #[3262](https://github.com/aws-cloudformation/cfn-lint/pull/3262)) + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.2.5.a9...v1.2.5.a10 + + +### v1.2.5a9 +## What's Changed +* Update CloudFormation schemas to 2024-05-14 by @kddejong in (pull #[3234](https://github.com/aws-cloudformation/cfn-lint/pull/3234)) +* Upgrade more rules to v1 by @kddejong (pull #[3243](https://github.com/aws-cloudformation/cfn-lint/pull/3243)), (pull #[3237](https://github.com/aws-cloudformation/cfn-lint/pull/3237)), (pull #[3222](https://github.com/aws-cloudformation/cfn-lint/pull/3222)) +* Enumerate FindInMap when can't be resolved (pull #[3247](https://github.com/aws-cloudformation/cfn-lint/pull/3247)) +* Cleanup Rules from ` __init__` by @kddejong (pull #[3235](https://github.com/aws-cloudformation/cfn-lint/pull/3235)) +* Add ability for child rule to claim who their parent is by @kddejong (pull #[3231](https://github.com/aws-cloudformation/cfn-lint/pull/3231)) +* Make `cfnLint` keyword dynamic by @kddejong (pull #[3225](https://github.com/aws-cloudformation/cfn-lint/pull/3225)) +* Remove rule [E2504](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2504) and add back in [E3671](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3671) by @kddejong (pull #[3220](https://github.com/aws-cloudformation/cfn-lint/pull/3220)) + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.2.5.a8...v1.2.5.a9 + + +### v1.2.5a8 +## What's Changed +* Update CloudFormation schemas to 2024-05-03 by @kddejong in (pull #[3192](https://github.com/aws-cloudformation/cfn-lint/pull/3192)) +* Fix issue in [I3013](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I3013) with multiple resources (#) by @kddejong (pull #[3212](https://github.com/aws-cloudformation/cfn-lint/pull/3212)) +* Allow `Fn::Transform` inside a `Fn::Sub` (pull #[3213](https://github.com/aws-cloudformation/cfn-lint/pull/3213)) + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.2.5.a7...v1.2.5.a8 + +### v1.2.5a7 +## What's Changed +* Update CloudFormation schemas to 2024-04-24 by @kddejong in (pull #[3159](https://github.com/aws-cloudformation/cfn-lint/pull/3159)) +* Fix config of regions in TemplateRunner by @kddejong in (pull #[3164](https://github.com/aws-cloudformation/cfn-lint/pull/3164)) + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.2.5.a6...v1.2.5.a7 + +### v1.2.5a6 +## What's Changed +* Add a bunch of DynamoDB rules and schema changes by @kddejong in (pull #[3133](https://github.com/aws-cloudformation/cfn-lint/pull/3133)) +* Don't support resources in a FindInMap by @kddejong (pull #[3120](https://github.com/aws-cloudformation/cfn-lint/pull/3120)) +* Create rules W3689 and W3688 to do validation of AWS::RDS::DBCluster by @kddejong (pull #[3118](https://github.com/aws-cloudformation/cfn-lint/pull/3118)) +* Create rules E3660 to do validation of Rest API configuration with OpenAPI by @kddejong (pull #[3117](https://github.com/aws-cloudformation/cfn-lint/pull/3117)) +* Update specs to 2024/04/15 (pull #[3146](https://github.com/aws-cloudformation/cfn-lint/pull/3146)) + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.2.5.a5...v1.2.5.a6 + +### v1.2.5a5 +## What's Changed +* Show all errors in a validation schema by @kddejong in (pull #[3097](https://github.com/aws-cloudformation/cfn-lint/pull/3097)) +* Remove `description` from schemas (pull #[3094](https://github.com/aws-cloudformation/cfn-lint/pull/3094)) +* Update specs to 2024/03/14 (pull #[3094](https://github.com/aws-cloudformation/cfn-lint/pull/3094)) + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.2.5.a4...v1.2.5.a5 + +### v1.2.5a4 +## What's Changed +* New rules for RDS DBCluster E3692,E3694,E3694 by @kddejong in (pull #[3094](https://github.com/aws-cloudformation/cfn-lint/pull/3094)) +* New rule E3689 to validate DBCluster monitoring config by @kddejong in (pull #[3089](https://github.com/aws-cloudformation/cfn-lint/pull/3089)) +* New rule W4005 to validate cfn-lint config in metadata @kddejong in (pull #[3088](https://github.com/aws-cloudformation/cfn-lint/pull/3088)) +* Update specs to 2024/03/11 (pull #[3094](https://github.com/aws-cloudformation/cfn-lint/pull/3094)) + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.2.5.a3...v1.2.5.a4 + +### v1.2.5a3 +## What's Changed +* Increased validation of dynamic references by @kddejong in (pull #[3064](https://github.com/aws-cloudformation/cfn-lint/pull/3064)) +* Increased GetAtt and Sub typing support by @kddejong in (pull #[3075](https://github.com/aws-cloudformation/cfn-lint/pull/3075)) +* Add requiredXor for CloudFront distribution cache behavior by @kddejong in (pull #[3078](https://github.com/aws-cloudformation/cfn-lint/pull/3078)) +* Update specs to 2024/02/28 (pull #[3081](https://github.com/aws-cloudformation/cfn-lint/pull/3081)) + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.2.5.a2...v1.2.5.a3 + +### v1.2.5a2 +## What's Changed +* Set Application location when its a string by @kddejong in (pull #[3060](https://github.com/aws-cloudformation/cfn-lint/pull/3060)) +* Add getatt support for registry schemas by @kddejong in (pull #[3061](https://github.com/aws-cloudformation/cfn-lint/pull/3061)) +* Remove some extra unneeded code by @kddejong in (pull #[3062](https://github.com/aws-cloudformation/cfn-lint/pull/3062)) +* Remove rule W1011 (pull #[3055](https://github.com/aws-cloudformation/cfn-lint/pull/3055)) + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.2.5.a1...v1.2.5.a2 + +### v1.2.5a1 +###### Features +* Fix an issue when determining if it is supposed to be nested `json` @kddejong (pull #[3050](https://github.com/aws-cloudformation/cfn-lint/pull/3050)) +* Fix an issue where Resource `Type` validation was happening twice @kddejong (pull #[3050](https://github.com/aws-cloudformation/cfn-lint/pull/3050)) + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.2.4.a1...v1.2.5.a1 + +### v1.2.4a1 +###### Features +* Switch from `awsType` to `cfnLint` @kddejong +* Update rule to [W3037](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W3037) for json schema based validation @kddejong +* Update rule [E3025](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3025) to validate RDS instance class by license @kddejong +* Remove need for `sub_node` + +**Full Changelog**: https://github.com/aws-cloudformation/cfn-lint/compare/v1.2.3.a1...v1.2.4.a1 + +### v1.2.3a1 +###### Features +- Add rule [E3019](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3019) to validate primaryIdentifiers are unique (pull #[3023](https://github.com/aws-cloudformation/cfn-lint/pull/3023)) +- Add rule [E3687](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3687) to validate ToPort and FromPort (pull #[E3026](https://github.com/aws-cloudformation/cfn-lint/pull/E3026)) +- Add rule [W3687](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W3687) to validate ToPort and FromPort (pull #[E3026](https://github.com/aws-cloudformation/cfn-lint/pull/E3026)) +- Add rule [E3688](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3688) to validate both ToPort,FromPort are -1 (pull #[E3026](https://github.com/aws-cloudformation/cfn-lint/pull/E3026)) +- Add rule [E3021](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3021) for validate tagging values (pull #[3031](https://github.com/aws-cloudformation/cfn-lint/pull/3031)) +###### CloudFormation Specifications +- Update `ResourcePath` `pattern` to check for starting `/` (pull #[3019](https://github.com/aws-cloudformation/cfn-lint/pull/3019)) +###### Fixes +- Handle refs in REF type checks (pull #[3024](https://github.com/aws-cloudformation/cfn-lint/pull/3024)) +- Ignore_checks was being ignored when the rule was a parent (pull #[3032](https://github.com/aws-cloudformation/cfn-lint/pull/3032)) +- Additional GetAtt support for non registry resources (pull #[3027](https://github.com/aws-cloudformation/cfn-lint/pull/3027)) + +### v1.2.2a1 +###### Features +- Add rule [E3046](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2530) to validate ECS log config when AWS (pull #[2990](https://github.com/aws-cloudformation/cfn-lint/pull/2990)) +- Add `dependentExcluded` keyword to json schema validation (pull #[3002](https://github.com/aws-cloudformation/cfn-lint/pull/3002)) +- Add `requiredXor` keyword to json schema validation (pull #[2997](https://github.com/aws-cloudformation/cfn-lint/pull/2997)) +- Add `requiredOr` keyword to json schema validation (pull #[2997](https://github.com/aws-cloudformation/cfn-lint/pull/2997)) +- Add `uniqueKeys` keyword to json schema validation (pull #[2992](https://github.com/aws-cloudformation/cfn-lint/pull/2992)) +###### Fixes +- Make context more effecient (pull #[3007](https://github.com/aws-cloudformation/cfn-lint/pull/3007)) + +### v1.2.1a3 +###### Fixes +- Pass through all errors from `Fn::If`` (pull #[2583](https://github.com/aws-cloudformation/cfn-lint/pull/2583)) + +### v1.2.1a2 +###### Fixes +- Redo AWS::CloudFormation::Init validation (pull #[2583](https://github.com/aws-cloudformation/cfn-lint/pull/2583)) +- Redo runner logic and keep backwards compatibility of the API (pull #[2583](https://github.com/aws-cloudformation/cfn-lint/pull/2583)) + +### v1.2.1a1 +###### Fixes +- Fix `FnGetAtt` to better validate GetAtt types against JSON Schemas (pull #[2583](https://github.com/aws-cloudformation/cfn-lint/pull/2583)) + +### v1.2.0a1 +###### Features +- Convert Outputs, Parameters, and Mappings validationg to JSON Schema rules (pull #[2583](https://github.com/aws-cloudformation/cfn-lint/pull/2583)) +###### CloudFormation Specifications +- Update CloudFormation schemas from 2023/11/13 (pull #[2583](https://github.com/aws-cloudformation/cfn-lint/pull/2583)) + +### v1.1.0a2 +###### CloudFormation Specifications +- Update CloudFormation schemas from 2023/06/21 (pull #[2774](https://github.com/aws-cloudformation/cfn-lint/pull/2774)) +###### Fixes +- Move required field for lambda eventsource mappings (pull #[2775](https://github.com/aws-cloudformation/cfn-lint/pull/2775)) + +### v1.1.0a1 +###### Fixes +- Internalize json schema work and customize for CloudFormation purposes (pull #[2730](https://github.com/aws-cloudformation/cfn-lint/issues/2730)) +- Fix an issue where disabled rules will result in an error (pull #[2739](https://github.com/aws-cloudformation/cfn-lint/issues/2739)) +- Fix an issue where GetAtts of arrays are dropped (pull #[2740](https://github.com/aws-cloudformation/cfn-lint/issues/2740)) +- Switch to pyproject.toml and pre-commit for lint (pull #[2749](https://github.com/aws-cloudformation/cfn-lint/issues/2749)) +- Move `cfnSchema` into patching as needed (pull #[2752](https://github.com/aws-cloudformation/cfn-lint/issues/2752)) +- Rework how we handle CloudFormation functions (pull #[2760](https://github.com/aws-cloudformation/cfn-lint/issues/2760)) + +### v1.0.0.rc2 +###### Fixes +- Rewrite JSON schema validators to better handle CloudFormation functions (pull #[2730](https://github.com/aws-cloudformation/cfn-lint/issues/2730)) +- Fix an issue when the resource type isn't available for an output (pull #[2730](https://github.com/aws-cloudformation/cfn-lint/issues/2730)) +- Update JSON schema for resource configuration to handle Language Extensions for `DeletionPolicy` (pull #[2730](https://github.com/aws-cloudformation/cfn-lint/issues/2730)) +- Update condition logic to include resource level conditions (pull #[2737](https://github.com/aws-cloudformation/cfn-lint/issues/2737)) + +### v1.0.0.rc1 +###### Fixes +- Test schemas and patch as needed (pull #[2725](https://github.com/aws-cloudformation/cfn-lint/issues/2725)) + +### v1.0.0.a3 +###### Features +- Large rewrite and simplification to JSON Schema validation (pull #[2606](https://github.com/aws-cloudformation/cfn-lint/issues/2606)) +- Allow for integration the configuration of additional registry schemas (pull #[2710](https://github.com/aws-cloudformation/cfn-lint/issues/2710)) +- Validate schema configuration (pull #[2708](https://github.com/aws-cloudformation/cfn-lint/issues/2708)) +- Add in `enum` values from botocore (pull #[2705](https://github.com/aws-cloudformation/cfn-lint/issues/2705) and #[2702](https://github.com/aws-cloudformation/cfn-lint/issues/2702)) +- Add many JSON schemas to provide additional validation (pull #[2693](https://github.com/aws-cloudformation/cfn-lint/issues/2693) and #[2687](https://github.com/aws-cloudformation/cfn-lint/issues/2687)) +- Add json schema for CW Alarm period when in the AWS namespace (pull #[2685](https://github.com/aws-cloudformation/cfn-lint/issues/2685)) +- Include launch template security group schema (pull #[2681](https://github.com/aws-cloudformation/cfn-lint/issues/2681)) +- Update rule E3033 to include minLength (pull #[2680](https://github.com/aws-cloudformation/cfn-lint/issues/2680)) + +### v1.0.0.a2 +###### Features +- Fix packaging missing new json files (pull #[2606](https://github.com/aws-cloudformation/cfn-lint/issues/2606)) + +### v1.0.0.a1 +###### Features +- Large re-write to migrate from CloudFormation specs to CloudFormation resource provider schemas (pull #[2606](https://github.com/aws-cloudformation/cfn-lint/issues/2606)) + +### v0.87.1 +###### CloudFormation Specifications +- Update CloudFormation specs to `172.0.0` (pull #[3181](https://github.com/aws-cloudformation/cfn-lint/pull/3181)) +###### Fixes +- Continue to walk the FindInMap components in transform (pull #[3203](https://github.com/aws-cloudformation/cfn-lint/pull/3203)) +- Fix an issue with refs in registry schemas (pull #[3189](https://github.com/aws-cloudformation/cfn-lint/pull/3189)) +- Add `AWS::Kinesis::Stream` to be a stateful resource (pull #[3188](https://github.com/aws-cloudformation/cfn-lint/pull/3188)) + +### v0.87.0 +###### CloudFormation Specifications +- Update CloudFormation specs to `171.0.0` (pull #[3160](https://github.com/aws-cloudformation/cfn-lint/pull/3160)) +###### Fixes +- When using a list param in foreach pass back select statements when no allowed value (pull #[3176](https://github.com/aws-cloudformation/cfn-lint/pull/3176)) +- Fix an issue with graphs and pydot and not quoting attrs (pull #[3177](https://github.com/aws-cloudformation/cfn-lint/pull/3177)) +- Update [I3013](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I3013) as read replicas don't need backup period (pull #[3171](https://github.com/aws-cloudformation/cfn-lint/pull/3171)) +- Change filenames to be OS specific paths (pull #[3170](https://github.com/aws-cloudformation/cfn-lint/pull/3170)) +- Update [E8001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E8001) to validate null Condition section (pull #[3169](https://github.com/aws-cloudformation/cfn-lint/pull/3169)) + +### v0.86.4 +###### CloudFormation Specifications +- Update CloudFormation specs to `170.0.0` (pull #[3149](https://github.com/aws-cloudformation/cfn-lint/pull/3149)) +###### Fixes +- Only pick up `.json` files when using registry schemas (pull #[3150](https://github.com/aws-cloudformation/cfn-lint/pull/3150)) +- Update IAM policy validation to not allow `Action` and `NotAction` (pull #[3145](https://github.com/aws-cloudformation/cfn-lint/pull/3145)) +- Update IAM policy validation to not allow `Principal` and `NotPrincipal` (pull #[3145](https://github.com/aws-cloudformation/cfn-lint/pull/3145)) +- Update IAM policy validation to not allow `Resource` and `NotResource` (pull #[3145](https://github.com/aws-cloudformation/cfn-lint/pull/3145)) + +### v0.86.3 +###### CloudFormation Specifications +- Update CloudFormation specs to `169.0.0` (pull #[3135](https://github.com/aws-cloudformation/cfn-lint/pull/3135)) +- Support `db2-ae` and `db2-se` RDS engines for `AWS::RDS::DBInstance.Engine` (pull #[3139](https://github.com/aws-cloudformation/cfn-lint/pull/3139)) +###### Fixes +- Safely get `readOnlyProperties` (pull #[3141](https://github.com/aws-cloudformation/cfn-lint/pull/3141)) + +### v0.86.2 +###### CloudFormation Specifications +- Update CloudFormation specs to `168.0.0` (pull #[3127](https://github.com/aws-cloudformation/cfn-lint/pull/3127)) +- Remove `AWS::RDS::DBCluster` from exclusive checks (pull #[3119](https://github.com/aws-cloudformation/cfn-lint/pull/3119)) +###### Fixes +- When doing a transform pass back FindInMap when resolution failure (pull #[3131](https://github.com/aws-cloudformation/cfn-lint/pull/3131)) +- Update deprecated Lambda runtimes (pull #[3113](https://github.com/aws-cloudformation/cfn-lint/pull/3113)) + +### v0.86.1 +###### CloudFormation Specifications +- Update CloudFormation specs to `165.0.0` (pull #[3092](https://github.com/aws-cloudformation/cfn-lint/pull/3092)) +###### Fixes +- RDS DB Cluster remove MasterUserPassword from exclusion with MasterUsername (pull #[3106](https://github.com/aws-cloudformation/cfn-lint/pull/3106)) +- fix an issue when searching for Ref in tojsonstring (pull #[3107](https://github.com/aws-cloudformation/cfn-lint/pull/3107)) + +### v0.86.0 +###### Feature +- Disable and configure certain rules when template is from CDK (pull #[2971](https://github.com/aws-cloudformation/cfn-lint/pull/2971)) +###### CloudFormation Specifications +- Update CloudFormation specs to `163.0.0` (pull #[3076](https://github.com/aws-cloudformation/cfn-lint/pull/3076)) + +### v0.85.3 +###### CloudFormation Specifications +- Update CloudFormation specs to `162.0.0` (pull #[3069](https://github.com/aws-cloudformation/cfn-lint/pull/3069)) +###### Fixes +- Raise error if any key in a mapping is null (pull #[3073](https://github.com/aws-cloudformation/cfn-lint/pull/3073)) +- Add getatt support for registry schemas (pull #[3061](https://github.com/aws-cloudformation/cfn-lint/pull/3061)) +- Set Application location when its a string in SAM transform (pull #[3060](https://github.com/aws-cloudformation/cfn-lint/pull/3060)) + +### v0.85.2 +###### CloudFormation Specifications +- Update CloudFormation specs to `160.0.0` (pull #[3054](https://github.com/aws-cloudformation/cfn-lint/pull/3054)) + +### v0.85.1 +###### CloudFormation Specifications +- Update CloudFormation specs to `158.0.0` (pull #[3039](https://github.com/aws-cloudformation/cfn-lint/pull/3039)) +###### Fixes +- Fix an issue with using SAM and a GetAtt (pull #[3042](https://github.com/aws-cloudformation/cfn-lint/pull/3042)) + +### v0.85.0 +###### Feature +- Update rule [E3027](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3027) to validate rate periods (pull #[3017](https://github.com/aws-cloudformation/cfn-lint/pull/3017)) +- Add support new language extension foreach capabilities `&{parameter}` (pull #[3033](https://github.com/aws-cloudformation/cfn-lint/pull/3033)) +- Passthrough metadata into SAM translator (pull #[3030](https://github.com/aws-cloudformation/cfn-lint/pull/3030)) +- Switch to using path and resource names for directives (pull #[3035](https://github.com/aws-cloudformation/cfn-lint/pull/3035)) +###### CloudFormation Specifications +- Update CloudFormation specs to `156.0.0` (pull #[3029](https://github.com/aws-cloudformation/cfn-lint/pull/3029)) + +### v0.84.0 +###### CloudFormation Specifications +- Update CloudFormation specs to `154.0.0` (pull #[3005](https://github.com/aws-cloudformation/cfn-lint/pull/3005)) +- Add db.serverless to neptune instance classes (pull #[3009](https://github.com/aws-cloudformation/cfn-lint/pull/3009)) +###### Fixes +- Drop python 3.7 support (pull #[3005](https://github.com/aws-cloudformation/cfn-lint/pull/3005)) + +### v0.83.8 +###### CloudFormation Specifications +- Update CloudFormation specs to `153.0.0` (pull #[2986](https://github.com/aws-cloudformation/cfn-lint/pull/2986)) +###### Fixes +- Remove rule [E2506](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2506) which results in false positive (pull #[3001](https://github.com/aws-cloudformation/cfn-lint/pull/3001)) +- Return dict str_node when doing transform (pull #[2996](https://github.com/aws-cloudformation/cfn-lint/pull/2996)) + +### v0.83.7 +###### CloudFormation Specifications +- Update CloudFormation specs to `152.0.0` (pull #[2984](https://github.com/aws-cloudformation/cfn-lint/pull/2984)) +- Add `ca-west-1` region (pull #[2980](https://github.com/aws-cloudformation/cfn-lint/pull/2980)) + +### v0.83.6 +###### CloudFormation Specifications +- Update CloudFormation specs to `151.0.0` (pull #[2969](https://github.com/aws-cloudformation/cfn-lint/pull/2969)) +###### Fixes +- Fix LanguageTransformer to better handle `Fn::GetAtt` dot notation in `Fn::Sub` (pull #[2974](https://github.com/aws-cloudformation/cfn-lint/pull/2974)) +- Update rule [E2530](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2530) and [I2530](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I2530) to support regionality of the `SnapStart` feature (pull #[2973](https://github.com/aws-cloudformation/cfn-lint/pull/2973)) + +### v0.83.5 +###### CloudFormation Specifications +- Update CloudFormation specs to `150.0.0` (pull #[2963](https://github.com/aws-cloudformation/cfn-lint/pull/2963)) +- Patch in `TargetObjectKeyFormat` for `AWS::S3::Bucket` (pull #[2966](https://github.com/aws-cloudformation/cfn-lint/pull/2966)) +###### Fixes +- Update rule [E3013](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3013) to ignore dynamic references in CloudFront aliases (pull #[2967](https://github.com/aws-cloudformation/cfn-lint/pull/2967)) + +### v0.83.4 +###### CloudFormation Specifications +- Update CloudFormation specs to `149.0.0` (pull #[2951](https://github.com/aws-cloudformation/cfn-lint/pull/2951)) +- Add `KeyID` as a target for `TargetKeyId` (pull #[2953](https://github.com/aws-cloudformation/cfn-lint/pull/2953)) + +### v0.83.3 +###### CloudFormation Specifications +- Update CloudFormation specs to include `python3.12` (pull #[2947](https://github.com/aws-cloudformation/cfn-lint/pull/2947)) + +### v0.83.2 +###### CloudFormation Specifications +- Update CloudFormation specs to `148.0.0` (pull #[2942](https://github.com/aws-cloudformation/cfn-lint/pull/2942)) +- Add in `LoadBalancerArn` to `LoadBalancerV2Arn` (pull #[2936](https://github.com/aws-cloudformation/cfn-lint/pull/2936)) + +### v0.83.1 +###### CloudFormation Specifications +- Update CloudFormation specs to `146.0.0` (pull #[2921](https://github.com/aws-cloudformation/cfn-lint/pull/2921)) +###### Fixes +- Update [E3036](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3036) and [E3035](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3035) to allow more FNs (pull #[2928](https://github.com/aws-cloudformation/cfn-lint/pull/2928)) +- Update [I3037](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I3037) to have exceptions `Command` (pull #[2927](https://github.com/aws-cloudformation/cfn-lint/pull/2927)) + +### v0.83.0 +###### Features +- Add rule [E3045](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3045) to validate `AccessControl`s are specified when using `AccessControl` (pull #[2906](https://github.com/aws-cloudformation/cfn-lint/pull/2906)) +- Add rule [W3045](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W3045) to alert on usage of legacy capability `AccessControl` (pull #[2906](https://github.com/aws-cloudformation/cfn-lint/pull/2906)) +###### CloudFormation Specifications +- Update CloudFormation specs to `145.0.0` (pull #[2909](https://github.com/aws-cloudformation/cfn-lint/pull/2909)) + +### v0.82.2 +###### Fixes +- Update [I2530](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I2530) validates its using Java runtimes greater than 8 (pull #[2916](https://github.com/aws-cloudformation/cfn-lint/pull/2916)) + +### v0.82.1 +###### Fixes +- Update [E2530](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2530) and [I2530](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I2530) to make sure `Runtime` is a string before using `startswith` (pull #[2912](https://github.com/aws-cloudformation/cfn-lint/pull/2912)) + +### v0.82.0 +###### Features +- Add rule [W2530](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2530) to warn when `SnapStart` isn't configured correctly (pull #[2905](https://github.com/aws-cloudformation/cfn-lint/pull/2905)) +- Add rule [I2530](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2530) to warn when `SnapStart` isn't configured on newer Java runtimes (pull #[2905](https://github.com/aws-cloudformation/cfn-lint/pull/2905)) +- Add rule [E2530](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2530) to error when `SnapStart` is configured on an unsupported runtime (pull #[2905](https://github.com/aws-cloudformation/cfn-lint/pull/2905)) +###### CloudFormation Specifications +- Update CloudFormation specs to `144.0.0` (pull #[2898](https://github.com/aws-cloudformation/cfn-lint/pull/2898)) + +### v0.81.0 +###### CloudFormation Specifications +- Update CloudFormation specs to `143.0.0` (pull #[2893](https://github.com/aws-cloudformation/cfn-lint/pull/2893)) +###### Fixes +- Update language transformation to pass through empty objects (pull #[2899](https://github.com/aws-cloudformation/cfn-lint/pull/2899)) +- Update rule [E1017](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1017) to allow `Fn::Select` to allow `Fn::Select` (pull #[2900](https://github.com/aws-cloudformation/cfn-lint/pull/2900)) +- Update rule [E2532](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2532) to support `ToleratedFailurePercentage` and `ItemBatcher` to `Map` (pull #[2901](https://github.com/aws-cloudformation/cfn-lint/pull/2901)) + +### v0.80.4 +###### CloudFormation Specifications +- Update CloudFormation specs to `142.0.0` (pull #[2889](https://github.com/aws-cloudformation/cfn-lint/pull/2889)) +###### Fixes +- Update rule [E2520](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2520) to allow for empty lists (pull #[2891](https://github.com/aws-cloudformation/cfn-lint/pull/2891)) + +### v0.80.3 +###### CloudFormation Specifications +- Update CloudFormation specs to `141.0.0` (pull #[2879](https://github.com/aws-cloudformation/cfn-lint/pull/2879)) +###### Fixes +- Update rule [E2532](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2532) to include `CausePath` and `ErrorPath` key types to `Fail` state (pull #[2884](https://github.com/aws-cloudformation/cfn-lint/pull/2884)) +- Update rule [E2520](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2520) to better match exclusive properties (pull #[2886](https://github.com/aws-cloudformation/cfn-lint/pull/2886)) + +### v0.80.2 +###### Fixes +- Revert change #[2878](https://github.com/aws-cloudformation/cfn-lint/pull/2878) (pull #[2882](https://github.com/aws-cloudformation/cfn-lint/pull/2882)) + +### v0.80.1 +###### CloudFormation Specifications +- Update CloudFormation specs to `140.0.0` (pull #[2870](https://github.com/aws-cloudformation/cfn-lint/pull/2870)) +- Add `OriginAccessControlId` to `OnlyOne` (pull #[2878](https://github.com/aws-cloudformation/cfn-lint/pull/2878)) +###### Fixes +- Allow `jsonschema` to be from v3.0.0 to v5 (pull #[2838](https://github.com/aws-cloudformation/cfn-lint/pull/2838)) + +### v0.79.11 +###### Fixes +- Update [E3031](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3031) so all regex checks are run (pull #[2873](https://github.com/aws-cloudformation/cfn-lint/pull/2873)) +- Update [E2520](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2520) to better skip properties we don't care about (pull #[2875](https://github.com/aws-cloudformation/cfn-lint/pull/2875)) + +### v0.79.10 +###### CloudFormation Specifications +- Update CloudFormation specs to `139.0.0` (pull #[2865](https://github.com/aws-cloudformation/cfn-lint/pull/2865)) +###### Fixes +- Force regex to be at least 2022 for typing parameter (pull #[2867](https://github.com/aws-cloudformation/cfn-lint/pull/2867)) + +### v0.79.9 +###### CloudFormation Specifications +- Update CloudFormation specs to `138.0.0` (pull #[2857](https://github.com/aws-cloudformation/cfn-lint/pull/2857)) +###### Fixes +- Fix `AWS::LanguageExtensions` to have regex escape for string replacement (pull #[2862](https://github.com/aws-cloudformation/cfn-lint/pull/2862)) + +### v0.79.8 +###### CloudFormation Specifications +- Update CloudFormation specs to `136.0.0` (pull #[2848](https://github.com/aws-cloudformation/cfn-lint/pull/2848)) +###### Fixes +- Added `ItemReader` key to StateMachine `Map` state (pull #[2850](https://github.com/aws-cloudformation/cfn-lint/pull/2850)) +- Update rule [E2503](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2503) to allow network load balancers to use security groups (pull #[2850](https://github.com/aws-cloudformation/cfn-lint/pull/2850)) + +### v0.79.7 +###### CloudFormation Specifications +- Add region `il-central-1` (pull #[2836](https://github.com/aws-cloudformation/cfn-lint/pull/2836)) +- Update CloudFormation specs to `135.0.0` (pull #[2837](https://github.com/aws-cloudformation/cfn-lint/pull/2837)) +###### Fixes +- Allow for `RetainExceptOnCreate` for `DeletionPolicy` (pull #[2834](https://github.com/aws-cloudformation/cfn-lint/pull/2834)) +- Fix language extension transform to resolve foreach refs in Sub parameters (pull #[2846](https://github.com/aws-cloudformation/cfn-lint/pull/2846)) +- Fix language extension transform to allow `Fn::FindInMap` to return arrays (pull #[2845](https://github.com/aws-cloudformation/cfn-lint/pull/2845)) + +### v0.79.6 +###### CloudFormation Specifications +- Fix `AWS::Glue::Job.Name` to use string min/max instead of number min/max (pull #[2831](https://github.com/aws-cloudformation/cfn-lint/pull/2831)) + +### v0.79.5 +###### CloudFormation Specifications +- Update schema to spec conversions to include include a default string minimum value of 0 if not specified (pull #[2824](https://github.com/aws-cloudformation/cfn-lint/pull/2824)) +- Update CloudFormation specs to `132.0.0` (pull #[2824](https://github.com/aws-cloudformation/cfn-lint/pull/2824)) +###### Fixes +- Fix `AWS::LanguageExtensions` to not empty out a hardcoded string `Fn::FindInmap` that cannot be resolved (pull #[2827](https://github.com/aws-cloudformation/cfn-lint/pull/2827)) + +### v0.79.4 +###### Fixes +- Fix `AWS::LanguageExtensions` to not fully resolve `Fn::FindInMap` unless in `Fn::ForEach` collection (pull #[2822](https://github.com/aws-cloudformation/cfn-lint/pull/2822)) +- Update `convert_dict` to include `Mark` instead of tuple for default value (pull #[2821](https://github.com/aws-cloudformation/cfn-lint/pull/2821)) + +### v0.79.3 +###### Fixes +- Fix `Conditions` logic to not crash on a condition that isn't found (pull #[2814](https://github.com/aws-cloudformation/cfn-lint/pull/2814)) +- Update rule [E1011](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1011) to better handle `Fn::FindInMap` with `AWS::LanguageExtensions` (pull #[2814](https://github.com/aws-cloudformation/cfn-lint/pull/2814)) +- Update rule [W2001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2001) to better handle `Ref` with `AWS::LanguageExtensions` (pull #[2814](https://github.com/aws-cloudformation/cfn-lint/pull/2814)) + +### v0.79.2 +###### Features +- Add rule [E1032](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1032) to validate ForEach with transform (pull #[2809](https://github.com/aws-cloudformation/cfn-lint/pull/2809)) +###### Fixes +- Fix `AWS::LanguageExtensions` regex for sub removal to handle pseudo parameters (pull #[2812](https://github.com/aws-cloudformation/cfn-lint/pull/2812)) + +### v0.79.1 +###### Features +- Add support for `Fn::ForEach` when using `AWS::LanguageExtensions` (pull #[2801](https://github.com/aws-cloudformation/cfn-lint/pull/2801)) + +### v0.78.2 +###### Features +- Add `test` function to test conditions given a scenario (pull #[2801](https://github.com/aws-cloudformation/cfn-lint/pull/2801)) +###### CloudFormation Specifications +- Update CloudFormation specs to `131.0.0` (pull #[2795](https://github.com/aws-cloudformation/cfn-lint/pull/2795)) +- Updated `DocumentDBEngineVersion` `AllowedValues` (pull #[2800](https://github.com/aws-cloudformation/cfn-lint/pull/2800)) + +### v0.78.1 +###### Features +- Update rule [E1018](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1018) to flag splitting dynamic references (pull #[2786](https://github.com/aws-cloudformation/cfn-lint/pull/2786)) +- New rule [W2533](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2533) to validate lambda zip deployment configuration (pull #[2682](https://github.com/aws-cloudformation/cfn-lint/pull/2682)) +- Supporting intrinsic function in `DeletionPolicy` and `UpdateReplacePolicy` (pull #[2784](https://github.com/aws-cloudformation/cfn-lint/pull/2784)) +###### CloudFormation Specifications +- Update CloudFormation specs to `130.0.0` (pull #[2783](https://github.com/aws-cloudformation/cfn-lint/pull/2783)) +###### Fixes +- Pin `jsonschema` to be under `4.18` (pull #[2792](https://github.com/aws-cloudformation/cfn-lint/pull/2792)) +- Fix using `include_experimental` in metadata (pull #[2785](https://github.com/aws-cloudformation/cfn-lint/pull/2785)) +- Fix rule [E1024](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1024) to better handle conditions (pull #[2780](https://github.com/aws-cloudformation/cfn-lint/pull/2780)) +### v1.0.0.a1 +###### Features +- Large re-write to migrate from CloudFormation specs to CloudFormation resource provider schemas (pull #[2606](https://github.com/aws-cloudformation/cfn-lint/issues/2606)) + +### v0.77.10 +###### CloudFormation Specifications +- Update CloudFormation specs to `127.0.0` (pull #[2763](https://github.com/aws-cloudformation/cfn-lint/pull/2763)) + +### v0.77.9 +###### CloudFormation Specifications +- Fix an issue with SSM patching (pull #[2765](https://github.com/aws-cloudformation/cfn-lint/pull/2765)) + +### v0.77.8 +###### CloudFormation Specifications +- Update CloudFormation specs to `126.0.0` (pull #[2753](https://github.com/aws-cloudformation/cfn-lint/pull/2753)) + +### v0.77.7 +###### Fixes +- Fix usage of comments and new lines in custom rules(pull #[2757](https://github.com/aws-cloudformation/cfn-lint/pull/2757)) + +### v0.77.6 +###### CloudFormation Specifications +- Update CloudFormation specs to `124.0.0` (pull #[2736](https://github.com/aws-cloudformation/cfn-lint/pull/2736)) +- Add `AWS::KMS::Key` to stateful resource list (pull #[2751](https://github.com/aws-cloudformation/cfn-lint/pull/2751)) +###### Fixes +- Update [E3012](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3012) documentation changes for more clarity (pull #[2747](https://github.com/aws-cloudformation/cfn-lint/pull/2747)) + +### v0.77.5 +###### CloudFormation Specifications +- Update CloudFormation specs to `121.0.0` (pull #[2723](https://github.com/aws-cloudformation/cfn-lint/pull/2723)) + +### v0.77.4 +###### CloudFormation Specifications +- Update CloudFormation specs to `120.0.0` (pull #[2714](https://github.com/aws-cloudformation/cfn-lint/pull/2714)) +###### Fixes +- Fix Conditions logic when checking a condition against a region. Now return True and False when the condition has no basis on region (pull #[2721](https://github.com/aws-cloudformation/cfn-lint/pull/2721)) +- Rebuild conditions inside the Template class when doing a Transform (pull #[2721](https://github.com/aws-cloudformation/cfn-lint/pull/2721)) + +### v0.77.3 +###### CloudFormation Specifications +- Update CloudFormation specs to `119.2.0` (pull #[2703](https://github.com/aws-cloudformation/cfn-lint/pull/2703)) +###### Fixes +- GetAtt can return objects along with FindInMap (pull #[2709](https://github.com/aws-cloudformation/cfn-lint/pull/2709)) + +### v0.77.2 +###### Features +- Add custom operators for regex, gt, lt (pull #[2694](https://github.com/aws-cloudformation/cfn-lint/pull/2694)) +###### CloudFormation Specifications +- Update CloudFormation specs to `119.1.0` (pull #[2698](https://github.com/aws-cloudformation/cfn-lint/pull/2698)) + +### v0.77.1 +###### CloudFormation Specifications +- Update CloudFormation specs to `119.1.0` (pull #[2678](https://github.com/aws-cloudformation/cfn-lint/pull/2678)) +- Update allowed values for `AWS::RDS::DBInstance.PerformanceInsightsRetentionPeriod` (pull #[2696](https://github.com/aws-cloudformation/cfn-lint/pull/2696)) +###### Fixes +- Update rule [E3001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3001) to evaluate if a resource with a condition is affected by the region (pull #[2691](https://github.com/aws-cloudformation/cfn-lint/pull/2691)) + +### v0.77.0 +###### Features +- Convert from `re` to `regex` (pull #[2643](https://github.com/aws-cloudformation/cfn-lint/pull/2643)) +- Implement `IS DEFINED` in custom rules (pull #[2656](https://github.com/aws-cloudformation/cfn-lint/pull/2656)) +###### CloudFormation Specifications +- Update CloudFormation specs to `119.0.0` (pull #[2660](https://github.com/aws-cloudformation/cfn-lint/pull/2660)) +- Patch `AWS::S3::Bucket.InventoryConfiguration.OptionalFields` to include `ChecksumAlgorithm` (pull #[2666](https://github.com/aws-cloudformation/cfn-lint/pull/2666)) +- Patch `AWS::Cognito::UserPool.UserPollTags` to be a map of strings (pull #[2671](https://github.com/aws-cloudformation/cfn-lint/pull/2671)) +###### Fixes +- Update SAM translation to substitute for a sub in `CodeUri` (pull #[2661](https://github.com/aws-cloudformation/cfn-lint/pull/2661)) +- Update language extensions to validate if a ref is iterable before assuming it is (pull #[2665](https://github.com/aws-cloudformation/cfn-lint/pull/2665)) +- Update rule [E3001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3001) to consider a resource level condition when evaluating if the resource type exists (pull #[2668](https://github.com/aws-cloudformation/cfn-lint/pull/2668)) +- Update rule [E3012](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3001) to validate if a map is actually a map (pull #[2669](https://github.com/aws-cloudformation/cfn-lint/pull/2669)) + +### v0.76.2 +###### CloudFormation Specifications +- Update CloudFormation specs to `118.1.0` (pull #[2644](https://github.com/aws-cloudformation/cfn-lint/pull/2644)) + +### v0.76.1 +###### Fixes +- Fix an issue with Conditions when a `Fn::Equals` has a string that isn't in a Parameters `AllowedValues` (pull #[2649](https://github.com/aws-cloudformation/cfn-lint/pull/2649)) + +### v0.76.0 +###### Features +- Convert conditions to SymPy (pull #[2624](https://github.com/aws-cloudformation/cfn-lint/pull/2624)) +- Include tests in sdist (pull #[2630](https://github.com/aws-cloudformation/cfn-lint/pull/2630)) +###### CloudFormation Specifications +- Update CloudFormation specs to `117.0.0` (pull #[2642](https://github.com/aws-cloudformation/cfn-lint/pull/2642)) +###### Fixes +- Fix SAM templates treated as normal by api (pull #[2646](https://github.com/aws-cloudformation/cfn-lint/pull/2646)) + +### v0.75.1 +###### CloudFormation Specifications +- Update CloudFormation specs to `116.0.0` (pull #[2620](https://github.com/aws-cloudformation/cfn-lint/pull/2620)) +- Add string length for `AWS::WAFRegional::RegexPatternSet.RegexPatternStrings` and `AWS::WAFv2::RegexPatternSet.RegularExpressionList` (pull #[2637](https://github.com/aws-cloudformation/cfn-lint/pull/2616), (pull #[2639](https://github.com/aws-cloudformation/cfn-lint/pull/2639)) + +### v0.75.0 +###### Features +- Read the default region from Env Vars (pull #[2618](https://github.com/aws-cloudformation/cfn-lint/pull/2618)) +###### Fixes +- Update rule [W2030](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2030) and [E3008](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3008) to read `ValueTypes` from `us-east-1` when `CACHED` (pull #[2635](https://github.com/aws-cloudformation/cfn-lint/pull/2635)) + +### v0.74.3 +###### Fixes +- Update rule [W2031](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2031), [E3031](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3031), [E3030](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3030), [E3034](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3034), and [E3033](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3033) to read `ValueTypes` from `us-east-1` when `CACHED` (pull #[2628](https://github.com/aws-cloudformation/cfn-lint/pull/2628)) + +### v0.74.2 +###### CloudFormation Specifications +- Update CloudFormation specs to `115.0.0` (pull #[2616](https://github.com/aws-cloudformation/cfn-lint/pull/2616)) +###### Fixes +- Fix custom rule inequality comparison (pull #[2614](https://github.com/aws-cloudformation/cfn-lint/pull/2614)) +- Restructure the decode module (pull #[2607](https://github.com/aws-cloudformation/cfn-lint/pull/2607)) + +### v0.74.1 +###### CloudFormation Specifications +- Update CloudFormation specs to `114.0.0` (pull #[2601](https://github.com/aws-cloudformation/cfn-lint/pull/2601)) +- Remove `AWS::Logs::LogGroup.RetentionInDays` `AllowedValues` (pull #[2604](https://github.com/aws-cloudformation/cfn-lint/pull/2604)) + +### v0.74.0 +###### Features +- Add rule [E3044](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3044) to validate the scheduling strategy for Fargate services (pull #[2559](https://github.com/aws-cloudformation/cfn-lint/pull/2559)) +###### CloudFormation Specifications +- Update CloudFormation specs to `113.0.0` (pull #[2591](https://github.com/aws-cloudformation/cfn-lint/pull/2591)) +###### Fixes +- Updated condition logic to limit the number of conditions that are processed (pull #[2598](https://github.com/aws-cloudformation/cfn-lint/pull/2598)) + +### v0.73.2 +###### CloudFormation Specifications +- Update CloudFormation specs to `112.0.0` (pull #[2580](https://github.com/aws-cloudformation/cfn-lint/pull/2580)) +###### Fixes +- Updated rule [E2532](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2532) by adding `ItemProcessor` to `Map` (pull #[2577](https://github.com/aws-cloudformation/cfn-lint/pull/2577)) +- Relax `networkx` dependency (pull #[2584](https://github.com/aws-cloudformation/cfn-lint/pull/2584)) +- Validate sub string checks are strings before running regex in graph and template (pull #[2589](https://github.com/aws-cloudformation/cfn-lint/pull/2589)) +- Update SAM transform pre-work to include `DefinitionBody` when `DisableExecuteApiEndpoint` is specified (pull #[2590](https://github.com/aws-cloudformation/cfn-lint/pull/2590)) + +### v0.73.1 +###### CloudFormation Specifications +- Patch back in `TargetRole` for `AWS::RDS::DBProxyEndpoint` (pull #[2581](https://github.com/aws-cloudformation/cfn-lint/pull/2581)) + +### v0.73.0 +###### CloudFormation Specifications +- Update CloudFormation specs to `111.0.0` (pull #[2572](https://github.com/aws-cloudformation/cfn-lint/pull/2572)) +- Add region `ap-southeast-4` (pull #[2568](https://github.com/aws-cloudformation/cfn-lint/pull/2568)) +- Remove `AWS::RDS::DBCluster` `MasterUsername` and `MasterUserPassword` from Inclusive (pull #[2571](https://github.com/aws-cloudformation/cfn-lint/pull/2571)) +###### Fixes +- Update SAM Translator version based on the SAM CLI requirement (pull #[2570](https://github.com/aws-cloudformation/cfn-lint/pull/2570)) + +### v0.72.10 +###### CloudFormation Specifications +- Update CloudFormation specs to `108.0.0` (pull #[2557](https://github.com/aws-cloudformation/cfn-lint/pull/2557)) +- Add `AWS::Organizations::Account` to `StatefulResources` (pull #[2560](https://github.com/aws-cloudformation/cfn-lint/pull/2560)) +###### Fixes +- Update rule [I3100](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I3100) regex family string matching (pull #[2558](https://github.com/aws-cloudformation/cfn-lint/pull/2558)) + +### v0.72.9 +###### CloudFormation Specifications +- Update CloudFormation specs to `107.0.0` (pull #[2546](https://github.com/aws-cloudformation/cfn-lint/pull/2550)) + +### v0.72.8 +###### Features +- Support `Fn::FindInMap` [enhancements](https://github.com/aws-cloudformation/cfn-language-discussion/commit/42cec9ce0d980a0832dc0fd1aed5750980280892?short_path=be2a597#diff-be2a59710611cc501f7361fcff1c335613d5dabb8326ce3ea746f4474f954bc5) when template is declared with `AWS::LanguageExtensions` (pull #[2512](https://github.com/aws-cloudformation/cfn-lint/pull/2512)) + +### v0.72.7 +###### CloudFormation Specifications +- Update CloudFormation specs to `106.0.0` (pull #[2546](https://github.com/aws-cloudformation/cfn-lint/pull/2546)) +###### Fixes +- Update rule [E1030](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1030) to include `Fn::FindInMap` when using `Fn::Length` (pull #[2547](https://github.com/aws-cloudformation/cfn-lint/pull/2547)) +- Update rule [E3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3002) to allow a `Fn::GetAtt` for an object (pull #[2548](https://github.com/aws-cloudformation/cfn-lint/pull/2548)) +- Update rule [E2532](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2532) to include current task properties (pull #[2549](https://github.com/aws-cloudformation/cfn-lint/pull/2549)) + +### v0.72.6 +###### CloudFormation Specifications +- Update CloudFormation specs to `105.0.0` (pull #[2530](https://github.com/aws-cloudformation/cfn-lint/pull/2530)) +###### Fixes +- Use a clean copy of the `cli_value` each time when merging config to avoid leaking config from one template to another (pull #[2536](https://github.com/aws-cloudformation/cfn-lint/pull/2536)) + +### v0.72.5 +###### Features +- Update rule [W1001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W1001) to support `Fn::Sub` (pull #[2525](https://github.com/aws-cloudformation/cfn-lint/pull/2525)) +###### CloudFormation Specifications +- Update CloudFormation specs to `102.0.0` (pull #[2523](https://github.com/aws-cloudformation/cfn-lint/pull/2523)) + +### v0.72.4 +###### Fixes +- Update `Template` function `get_valid_getatts` to better return None when a property type doesn't exist (pull #[2527](https://github.com/aws-cloudformation/cfn-lint/pull/2527)) + +### v0.72.3 +###### Features +- Update rule [E2015](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2015) to support the `AllowedValues` and `AllowedPattern` attributes for `CommaDelimitedList` parameters (pull #[2521](https://github.com/aws-cloudformation/cfn-lint/pull/2521)) +###### CloudFormation Specifications +- Update CloudFormation specs to `101.0.0` (pull #[2517](https://github.com/aws-cloudformation/cfn-lint/pull/2517)) +- Update `get_valid_getatts` to account for changes in the CloudFormation spec (pull #[2520](https://github.com/aws-cloudformation/cfn-lint/pull/2520)) +###### Fixes +- Don't validate rule [I3042](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I3042) when using SAM (pull #[2513](https://github.com/aws-cloudformation/cfn-lint/pull/2513)) + +### v0.72.2 +###### CloudFormation Specifications +- Update CloudFormation specs to `100.0.0` (pull #[2493](https://github.com/aws-cloudformation/cfn-lint/pull/2493)) +###### Fixes +- Update rule [E1011](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1011) to merge key validation into one method (pull #[2502](https://github.com/aws-cloudformation/cfn-lint/pull/2502)) + +### v0.72.1 +###### CloudFormation Specifications +- Add `ap-south-2` region (pull #[2503](https://github.com/aws-cloudformation/cfn-lint/pull/2503)) +###### Fixes +- Rebuild the graph after doing the transform (pull #[2502](https://github.com/aws-cloudformation/cfn-lint/pull/2502)) + +### v0.72.0 +###### Features +- Add more info into the graph including outputs and parameters(pull #[2452](https://github.com/aws-cloudformation/cfn-lint/pull/2452)) +###### CloudFormation Specifications +- Update CloudFormation specs to `99.0.0` (pull #[2486](https://github.com/aws-cloudformation/cfn-lint/pull/2486)) +- Add `eu-south-2` region (pull #[2490](https://github.com/aws-cloudformation/cfn-lint/pull/2490)) +###### Fixes +- Make sure regex patterns with `\w` are validating against ASCII (pull #[2487](https://github.com/aws-cloudformation/cfn-lint/pull/2487)) + +### v0.71.1 +###### Features +###### CloudFormation Specifications +- Add support for region `eu-central-2` (pull #[2478](https://github.com/aws-cloudformation/cfn-lint/pull/2478)) +- Update CloudFormation specs to `97.0.0` (pull #[2475](https://github.com/aws-cloudformation/cfn-lint/pull/2475)) + +### v0.71.0 +###### Features +- Reduce storage on disk by reducing regional specs to only have differences from `us-east-1` spec (pull #[2457](https://github.com/aws-cloudformation/cfn-lint/pull/2457)) +###### CloudFormation Specifications +- Update CloudFormation specs to `96.0.0` (pull #[2461](https://github.com/aws-cloudformation/cfn-lint/pull/2461)) +###### Fixes +- Fix an issue with junit/pretty formatter/core process to get all rules even on parse failure (pull #[2462](https://github.com/aws-cloudformation/cfn-lint/pull/2462)) +- Fix an issue when use stdin to pass a template and cfn-lint with parameters giving `E0000` (pull #[2470](https://github.com/aws-cloudformation/cfn-lint/pull/2470)) + +### v0.70.1 +###### Features +- Add support for Python 3.11 (pull #[2463](https://github.com/aws-cloudformation/cfn-lint/pull/2463)) +###### Fixes +- Fix an issue with `--list-rules` failing (pull #[2466](https://github.com/aws-cloudformation/cfn-lint/pull/2466)) + +### v0.70.0 +###### Features +- Add rule [W8003](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W8003) to check if `Fn::Equals` will always be true or false (pull #[2426](https://github.com/aws-cloudformation/cfn-lint/pull/2426)) +- Allow you to configure how exit codes work (pull #[2436](https://github.com/aws-cloudformation/cfn-lint/pull/2436)) +###### CloudFormation Specifications +- Update CloudFormation specs to `95.0.0` (pull #[2440](https://github.com/aws-cloudformation/cfn-lint/pull/2440)) +- Remove check for string size of `Lambda::Function.Code.Zipfile` (pull #[2447](https://github.com/aws-cloudformation/cfn-lint/pull/2447)) +###### Fixes +- Update rule [E3012](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3012) to validate bad functions (pull #[2441](https://github.com/aws-cloudformation/cfn-lint/pull/2441)) +- Update rule [E3016](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3016) to make checks less restrictive (pull #[2453](https://github.com/aws-cloudformation/cfn-lint/pull/2453)) + +### v0.69.1 +###### CloudFormation Specifications +- Updated string max value to `Lambda::Function.Code.Zipfile` to 4MB (pull #[2444](https://github.com/aws-cloudformation/cfn-lint/pull/2444)) + +### v0.69.0 +###### Features +- Update decode of yaml/json to report on all duplicates (pull #[2428](https://github.com/aws-cloudformation/cfn-lint/pull/2428)) +###### CloudFormation Specifications +- Patch in `db.serverless` into `AWS::RDS::DBInstance.DBInstanceClass` (pull #[2430](https://github.com/aws-cloudformation/cfn-lint/pull/2430)) +- Added string max value to `Lambda::Function.Code.Zipfile` (pull #[2431](https://github.com/aws-cloudformation/cfn-lint/pull/2431)) +###### Fixes +- Don't replace location for resource `AWS::Serverless::Application` in SAM transform when its a string (pull #[2425](https://github.com/aws-cloudformation/cfn-lint/pull/2425)) + +### v0.68.1 +###### CloudFormation Specifications +- Patch in `db.serverless` into `AWS::RDS::DBInstance.DBInstanceClass` (pull #[2424](https://github.com/aws-cloudformation/cfn-lint/pull/2424)) +- Update CloudFormation specs to `94.0.0` (pull #[2420](https://github.com/aws-cloudformation/cfn-lint/pull/2420)) + +### v0.68.0 +###### Features +- Ability to override location of the finding (pull #[2410](https://github.com/aws-cloudformation/cfn-lint/pull/2410)) +###### CloudFormation Specifications +- Patch in `DBClusterResourceId` for as an Attribute of `AWS::RDS::DBCluster` (pull #[2407](https://github.com/aws-cloudformation/cfn-lint/pull/2407)) +- Update CloudFormation specs to `93.0.0` (pull #[2409](https://github.com/aws-cloudformation/cfn-lint/pull/2409)) +- Update `AllowedPatternRegex` for `AWS::CloudWatch::Alarm.MetricDataQuery.Id` (pull #[2414](https://github.com/aws-cloudformation/cfn-lint/pull/2414) +- Add GetAtt to AWS::KMS::ReplicaKey.Arn for KmsKey.Arn (pull #[2417](https://github.com/aws-cloudformation/cfn-lint/pull/2417)) + +### v0.67.0 +###### Features +- Support child rules allowing rules to add another rule in their match responses (pull #[2393](https://github.com/aws-cloudformation/cfn-lint/pull/2393)) +###### CloudFormation Specifications +- Update CloudFormation specs to `92.0.0` (pull #[2399](https://github.com/aws-cloudformation/cfn-lint/pull/2399)) + +### v0.66.1 +###### CloudFormation Specifications +- Update CloudFormation specs to `91.0.0` (pull #[2392](https://github.com/aws-cloudformation/cfn-lint/pull/2392)) +###### Fixes +- Update [E8003](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E8003), [E1018](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1018), [E1019](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1019) to allow `Fn::ToJsonString` inside `Equals`, `Split`, and `Sub` (pull #[2397](https://github.com/aws-cloudformation/cfn-lint/pull/2397)) +- Update [I3013](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I3013) to allow https and s3 (pull #[2394](https://github.com/aws-cloudformation/cfn-lint/pull/2394)) + +### v0.66.0 +###### Features +- Update [E3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3002) to provide a suggestion if the wrong value is close to a correct value (pull #[2387](https://github.com/aws-cloudformation/cfn-lint/pull/2387)) +###### CloudFormation Specifications +- Update CloudFormation specs to `90.0.0` (pull #[2376](https://github.com/aws-cloudformation/cfn-lint/pull/2376)) +- Add in allowed values for oracle cdb engine types to `AWS::RDS::DBInstance.Engine` (pull #[2381](https://github.com/aws-cloudformation/cfn-lint/pull/2381)) +- Add in allowd value `PredictiveScaling` to `AWS::AutoScaling::ScalingPolicy.PolicyType` (pull #[2378](https://github.com/aws-cloudformation/cfn-lint/pull/2378)) +###### Fixes +- Update [W3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W3002) to validate values aren't already S3 paths (pull #[2382](https://github.com/aws-cloudformation/cfn-lint/pull/2382)) +- Update [I3013](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I3013) to not regex check if a function (pull #[2386](https://github.com/aws-cloudformation/cfn-lint/pull/2386)) + +### v0.65.1 +###### CloudFormation Specifications +- Update CloudFormation specs to `89.0.0` (pull #[2366](https://github.com/aws-cloudformation/cfn-lint/pull/2366)) +- Add support for `custom` RDS `Engine` types on resource type `AWS::RDS::DBInstance` (pull #[2370](https://github.com/aws-cloudformation/cfn-lint/pull/2370)) +- Remove extra spacing in specs reducing overall size (pull #[2371](https://github.com/aws-cloudformation/cfn-lint/pull/2371)) +- Update `AllowedValues` for `RetentionInDays` on resource type `AWS::Logs::LogGroup` (pull #[2372](https://github.com/aws-cloudformation/cfn-lint/pull/2372)) + +### v0.65.0 +###### Features +- Add `--force` option on `--update-specs` so cache isn't used (pull #[2334](https://github.com/aws-cloudformation/cfn-lint/pull/2334)) +- Add support for Python 3.10 (pull #[2365](https://github.com/aws-cloudformation/cfn-lint/pull/2365)) +###### CloudFormation Specifications +- Update CloudFormation specs to `88.0.0` (pull #[2361](https://github.com/aws-cloudformation/cfn-lint/pull/2361)) +###### Fixes +- Add in `mypy` testing and do a bunch of cleanup based on the results (pull #[2328](https://github.com/aws-cloudformation/cfn-lint/pull/2328)) +- Update rule [I1022](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I1022) to not suggest `Fn::Sub` on complext `Fn::Join`s (pull #[2364](https://github.com/aws-cloudformation/cfn-lint/pull/2364)) + + +### v0.64.1 +###### Fixes +- Make `me-central-1` `ExtendedSpecs` a module (pull #[2359](https://github.com/aws-cloudformation/cfn-lint/pull/2359)) + +### v0.64.0 +###### Features +- Update `jsonschema` to be able to use version 3.0 and 4.0 (pull #[2336](https://github.com/aws-cloudformation/cfn-lint/pull/2336)) +- Remove support for python 3.6 and add python 3.9 (pull #[2347](https://github.com/aws-cloudformation/cfn-lint/pull/2347)) +###### CloudFormation Specifications +- Update CloudFormation specs to `87.0.0` (pull #[2353](https://github.com/aws-cloudformation/cfn-lint/pull/2353)) +- Add support for region `me-central-1` (pull #[2351](https://github.com/aws-cloudformation/cfn-lint/pull/2351)) +###### Fixes +- Disable the SAM validation checks when transforming a template (pull #[2350](https://github.com/aws-cloudformation/cfn-lint/pull/2350)) + +### v0.63.2 +###### CloudFormation Specifications +- Patch in attributes for `AWS::RDS::DBCluster` (pull #[2344](https://github.com/aws-cloudformation/cfn-lint/pull/2344)) + +### v0.63.1 +###### CloudFormation Specifications +- Update CloudFormation specs to `86.0.0` (pull #[2335](https://github.com/aws-cloudformation/cfn-lint/pull/2335)) + +### v0.63.0 +###### Features +- support for AWS::LanguageExtensions transform features including DeletionPolicy, UpdateReplacePolicy, Fn::Length and Fn::ToJsonString [docs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html) (pull #[2339](https://github.com/aws-cloudformation/cfn-lint/pull/2339)) +- Add rule [E1030](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1030) to validate Fn::Length is configured correctly (pull #[2339](https://github.com/aws-cloudformation/cfn-lint/pull/2339)) +- Add rule [E1031](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1030) to validate Fn::Length is configured correctly (pull #[2339](https://github.com/aws-cloudformation/cfn-lint/pull/2339)) + +### v0.62.0 +###### Features +- Create new API to allow for easier integration of using cfn-lint as a library [docs](https://github.com/aws-cloudformation/cfn-lint/blob/main/docs/getting_started/integration.md) (pull #[2285](https://github.com/aws-cloudformation/cfn-lint/pull/2285)) +###### CloudFormation Specifications +- Update CloudFormation specs to `85.0.0` (pull #[2324](https://github.com/aws-cloudformation/cfn-lint/pull/2324)) +- Update Lambda deprecation dates (pull #[2327](https://github.com/aws-cloudformation/cfn-lint/pull/2327)) +###### Fixes +- Fix an issue with `RulesCollection` in which configurations would carry over between templates (pull #[2331](https://github.com/aws-cloudformation/cfn-lint/pull/2331)) +- Add used rules into `RulesCollection` so we can print all the used rules in JUnit and Pretty formatting (pull #[2330](https://github.com/aws-cloudformation/cfn-lint/pull/2330)) +- Update error message on [E3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3002) (pull #[2059](https://github.com/aws-cloudformation/cfn-lint/pull/2059)) +- Update error description on [E1020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1020) (pull #[2329](https://github.com/aws-cloudformation/cfn-lint/pull/2329)) + +### v0.61.5 +###### CloudFormation Specifications +- Update CloudFormation specs to `83.0.0` (pull #[2316](https://github.com/aws-cloudformation/cfn-lint/pull/2316)) +###### Fixes +- Update rule [I3100](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I3100) have proper path to resource (pull #[2309](https://github.com/aws-cloudformation/cfn-lint/pull/2309)) +- Update rule [E2503](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2503) by removing `AllowedValues` for `AWS::ElasticLoadBalancingV2::LoadBalancer.LoadBalancerAttribute` (pull #[2184](https://github.com/aws-cloudformation/cfn-lint/pull/2184)) +- Update rule [E3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3002) to include `` (pull #[1571](https://github.com/aws-cloudformation/cfn-python-lint/pull/1571)) +- Update Transform logic to not update DefinitionUri to S3 when not using DefinitionUri originally (pull #[1576](https://github.com/aws-cloudformation/cfn-python-lint/pull/1576)) + +### v0.33.0 +###### Features +- Upgrade SAM Translator to v1.24.0 (pull #[1562](https://github.com/aws-cloudformation/cfn-python-lint/pull/1562)) +- Warning messages for Python 3.4 and 2.7 (pull #[1337](https://github.com/aws-cloudformation/cfn-python-lint/pull/1337)) +- Add `--output-file` parameter to output the results into a file (pull #[1511](https://github.com/aws-cloudformation/cfn-python-lint/pull/1511)) +- Remove usage of jsonpointer (pull #[1546](https://github.com/aws-cloudformation/cfn-python-lint/pull/1546)) +- Add rule [E3042](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3042) that checks AWS::ECS::TaskDefinition.ContainerDefinition has at least one essential container (pull #[1548](https://github.com/aws-cloudformation/cfn-python-lint/pull/1548)) +###### CloudFormation Specifications +- Update CloudFormation specs to 14.4.0 (pull #[1555](https://github.com/aws-cloudformation/cfn-python-lint/pull/1555)) +- Add allowed patterns and values for properties in `AWS::S3::Bucket.InventoryConfiguration` (pull #[1551](https://github.com/aws-cloudformation/cfn-python-lint/pull/1551)) +###### Fixes +- Update Transform logic to support local files for the state machine defintion (pull #[1562](https://github.com/aws-cloudformation/cfn-python-lint/pull/1562)) + +### v0.32.1 +###### Features +- Adding [`Hooks`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/blue-green.html) template section to rule [E1001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1001) (pull #[1543](https://github.com/aws-cloudformation/cfn-python-lint/pull/1543)) + +### v0.32.0 +###### Features +- New rule [E3041](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3041) to check if `HostedZoneName` is a super domain for `Name` (pull #[1483](https://github.com/aws-cloudformation/cfn-python-lint/pull/1483)) +- Update SAM Translator dependency to `1.23.0` (pull #[1536](https://github.com/aws-cloudformation/cfn-python-lint/pull/1536)) +- Move Template and Runner classes into their own files (pull #[1523](https://github.com/aws-cloudformation/cfn-python-lint/pull/1523)) +###### CloudFormation Specifications +- Update CloudFormation specs to 14.3.0 (pull #[1538](https://github.com/aws-cloudformation/cfn-python-lint/pull/1538)) +- Add instance type allowed values to ElastiCache, Elasticsearch, ElasticMapReduce, ManagedBlockchain, GameLift, and AppStream (pull #[1535](https://github.com/aws-cloudformation/cfn-python-lint/pull/1535) and #[1541](https://github.com/aws-cloudformation/cfn-python-lint/pull/1541)) + +### v0.31.1 +###### Fixes +- Exempting resource types [AWS::Serverless transform](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-aws-serverless.html) creates that violated rule [W3011](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W3011) (pull #[1529](https://github.com/aws-cloudformation/cfn-python-lint/pull/1529)) + +### v0.31.0 +###### Features +- Add support for `.cfnlintrc.yaml` and `.cfnlintrc.yml` (pull #[1504](https://github.com/aws-cloudformation/cfn-python-lint/pull/1504)) +- Add JUnit XML output format (pull #[1506](https://github.com/aws-cloudformation/cfn-python-lint/pull/1506)) +###### CloudFormation Specifications +- Update CloudFormation specs to 14.2.0 (pull #[1526](https://github.com/aws-cloudformation/cfn-python-lint/pull/1526)) +- Update `AWS::AutoScaling::LaunchConfiguration` `SecurityGroups` to support GroupID and Names (pull #[1505](https://github.com/aws-cloudformation/cfn-python-lint/pull/1505)) +- Add min max and allowed values for multiple WAFv2 rate rules `Limit` rules (pull #[1507](https://github.com/aws-cloudformation/cfn-python-lint/pull/1507)) + +### v0.30.1 +###### Features +- Add the ability to specify a config file using parameter `--config-file` (pull #[1462](https://github.com/aws-cloudformation/cfn-python-lint/pull/1462)) +- Speed up `--update-specs` to not download files if they haven't updated (pull #[1383](https://github.com/aws-cloudformation/cfn-python-lint/pull/1383)) +###### CloudFormation Specifications +- Add region `eu-south-1` (pull #[1496](https://github.com/aws-cloudformation/cfn-python-lint/pull/1496)) +- Add region `af-south-1` (pull #[1494](https://github.com/aws-cloudformation/cfn-python-lint/pull/1494)) +- Update CloudFormation specs to 14.0.0 (pull #[1494](https://github.com/aws-cloudformation/cfn-python-lint/pull/1494)) +- Add new Config supported types `AWS::SecretsManager::Secret` and `AWS::SNS::Topic` (pull #[1492](https://github.com/aws-cloudformation/cfn-python-lint/pull/1492)) +###### Fixes +- Update rule [E1029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1029) to have an exception for `RequestMappingTemplate` in AppSync (pull #[1488](https://github.com/aws-cloudformation/cfn-python-lint/pull/1488)) +- Update rule [E1029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1029) to have an exception for `ConnectionID` in API Gateway (pull #[1493](https://github.com/aws-cloudformation/cfn-python-lint/pull/1493)) + +### v0.29.6 +###### CloudFormation Specifications +- Update Lambda runtimes to support `dotnetcore3.1` (pull #[1469](https://github.com/aws-cloudformation/cfn-python-lint/pull/1469)) +- Update DMS Engine approved values with multiple items (pull #[1472](https://github.com/aws-cloudformation/cfn-python-lint/pull/1472)) +- Add description allowed value regex to `AWS::EC2::SecurityGroup` Ingress/Egress (pull #[1476](https://github.com/aws-cloudformation/cfn-python-lint/pull/1476)) +- Update CloudFormation specs to 13.0.0 (pull #[1480](https://github.com/aws-cloudformation/cfn-python-lint/pull/1480)) +###### Fixes +- Set `importlib_resources` to 1.4 for all Pythons except 3.4 (pull #[1479](https://github.com/aws-cloudformation/cfn-python-lint/pull/1479)) + +### v0.29.5 +###### CloudFormation Specifications +- Update CloudFormation specs to 12.3.0 (pull #[1464](https://github.com/aws-cloudformation/cfn-python-lint/pull/1464)) +###### Fixes +- Fix an issue when including `cfn-lint` and needing `networkx` (pull #[1458](https://github.com/aws-cloudformation/cfn-python-lint/issues/1458)) + +### v0.29.4 +###### Features +- Add `--build-graph` parameter to create a graph of dependencies (pull #[1411](https://github.com/aws-cloudformation/cfn-python-lint/pull/1411)) +###### CloudFormation Specifications +- Update CloudFormation specs to 12.1.0 (pull #[1455](https://github.com/aws-cloudformation/cfn-python-lint/pull/1455)) +###### Fixes +- Add `found unknown escape character` to start of err problem to determine when to use json parsing (pull #[1454](https://github.com/aws-cloudformation/cfn-python-lint/pull/1454)) + +### v0.29.3 +###### CloudFormation Specifications +- Update CloudFormation specs to 12.0.0 (pull #[1448](https://github.com/aws-cloudformation/cfn-python-lint/pull/1448)) +###### Fixes +- Add region `ca-central-1d` (pull #[1447](https://github.com/aws-cloudformation/cfn-python-lint/pull/1447)) + +### v0.29.2 +###### Fixes +- Update exceptions in rule [E1029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1029) to include `BuildSpec` (pull #[1444](https://github.com/aws-cloudformation/cfn-python-lint/pull/1444)) + +### v0.29.1 +###### Features +- Switch DB Instance Engine check from [E3030](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3030) to [E3040](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3040) so the comparison is case insensitive (pull #[1441](https://github.com/aws-cloudformation/cfn-python-lint/pull/1441)) +###### CloudFormation Specifications +- Update CloudFormation specs to 11.6.0 (pull #[1433](https://github.com/aws-cloudformation/cfn-python-lint/pull/1433)) +- Add `ruby2.7` to supported list of ruby runtimes (pull #[1436](https://github.com/aws-cloudformation/cfn-python-lint/pull/1436)) +###### Fixes +- Update regex in rule [E1029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1029) to be more optimal and not hang on large strings (pull #[1430](https://github.com/aws-cloudformation/cfn-python-lint/pull/1430)) + +### v0.29.0 +###### Features +- Update SAM Translator package to 1.21.0 (pull #[1406](https://github.com/aws-cloudformation/cfn-python-lint/pull/1406)) +- Update rule [E3027](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3027) to check that either Day of Month or Day of Week is a question mark (pull #[1405](https://github.com/aws-cloudformation/cfn-python-lint/pull/1405)) +- New rule [E3029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3029) to check `AWS::RDS::DBInstance` `Aurora` databases don't have certain properties (pull #[1409](https://github.com/aws-cloudformation/cfn-python-lint/pull/1409)) +- Build a resource graph for checking circular dependencies (pull #[1391](https://github.com/aws-cloudformation/cfn-python-lint/pull/1391)) +###### CloudFormation Specifications +- Update Exclusive and Only One specs to include additional rules around Security Group Rules (pull #[1407](https://github.com/aws-cloudformation/cfn-python-lint/pull/1407)) +- Update CloudFormation specs to 11.5.0 (pull #[1416](https://github.com/aws-cloudformation/cfn-python-lint/pull/1416)) +- Patch spec so that TTL is Long on Route53 Change Record Sets (pull #[1417](https://github.com/aws-cloudformation/cfn-python-lint/pull/1417)) + +### v0.28.4 +###### CloudFormation Specifications +- Update CloudFormation specs to 11.4.0 (pull #[1403](https://github.com/aws-cloudformation/cfn-python-lint/pull/1403)) +###### Fixes +- Properly display yaml parse errors when the error was a tab (pull #[1402](https://github.com/aws-cloudformation/cfn-python-lint/pull/1402)) + +### v0.28.3 +###### Features +- Define an initial Docker file (pull #[1361](https://github.com/aws-cloudformation/cfn-python-lint/pull/1361)) +###### CloudFormation Specifications +- Update CloudFormation specs to 11.2.0 (pull #[1390](https://github.com/aws-cloudformation/cfn-python-lint/pull/1390)) +- Add allowed values for `AWS::RDS::DBInstance` `Engine` (pull #[1398](https://github.com/aws-cloudformation/cfn-python-lint/pull/1398)) +###### Fixes +- Update rule [E3039](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3039) to properly filter down attributes before checking values (pull #[1392](https://github.com/aws-cloudformation/cfn-python-lint/pull/1392)) +- Update rule [E1019](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1019) to not join GetAtt if they aren't strings (pull #[1389](https://github.com/aws-cloudformation/cfn-python-lint/pull/1389)) +- Consolidate region and spec information into singular item (pull #[1357](https://github.com/aws-cloudformation/cfn-python-lint/pull/1357)) + +### v0.28.2 +###### CloudFormation Specifications +- Update CloudFormation specs to 11.1.0 (pull #[1380](https://github.com/aws-cloudformation/cfn-python-lint/pull/1380)) +- Patch specs from updated SSM and pricing data as of 2020.02.21 (pull #[1380](https://github.com/aws-cloudformation/cfn-python-lint/pull/1380)) +- Update AWS Config supported types to those active on 2020.02.20 (pull #[1378](https://github.com/aws-cloudformation/cfn-python-lint/pull/1378)) +###### Fixes +- Update condition logic to return dict_node instead of the standard dict node (pull #[1375](https://github.com/aws-cloudformation/cfn-python-lint/pull/1375)) +- Fix `--update-specs` on Windows to have the appropriate seperator (pull #[1371](https://github.com/aws-cloudformation/cfn-python-lint/pull/1371)) +- Update the documentation for `--update-documentation` (pull #[1374](https://github.com/aws-cloudformation/cfn-python-lint/pull/1374)) + +### v0.28.1 +###### Features +- Add option to disable [E1029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1029) using a regex pattern on the variable name (pull #[1362](https://github.com/aws-cloudformation/cfn-python-lint/pull/1362)) +###### Fixes +- Update decode node class to pass back an empty list when default is None and the key doesn't exist (pull #[1364](https://github.com/aws-cloudformation/cfn-python-lint/pull/1364)) + +### v0.28.0 +###### Features +- Add rule [E3028](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3028) to check that `ScalingConfiguration` is only specified with Aurora databases (pull #[1338](https://github.com/aws-cloudformation/cfn-python-lint/pull/1338)) +- Add rule [E3039](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3039) to check that `AttributeDefinitions` match `KeySchemas` (pull #[1284](https://github.com/aws-cloudformation/cfn-python-lint/pull/1284)) +###### CloudFormation Specifications +- Add `AFTER_7_DAYS` to `TransitionToIA` as accepted value (pull #[1352](https://github.com/aws-cloudformation/cfn-python-lint/pull/1352)) +- Update CloudFormation specs to 11.0.0 (pull #[1355](https://github.com/aws-cloudformation/cfn-python-lint/pull/1355)) +- Patch specs from updated SSM and pricing data as of 2020.02.15 (pull #[1356](https://github.com/aws-cloudformation/cfn-python-lint/pull/1356)) + +### v0.27.5 +###### Features +- Add scripts to build an offline installer (pull #[1307](https://github.com/aws-cloudformation/cfn-python-lint/pull/1307)) +###### CloudFormation Specifications +- Update CloudFormation specs to 10.5.0 (pull #[1347](https://github.com/aws-cloudformation/cfn-python-lint/pull/1347)) +- Patch specs from updated SSM and pricing data as of 2020.02.09 (pull #[1348](https://github.com/aws-cloudformation/cfn-python-lint/pull/1348)) + +### v0.27.4 +###### Features +- Add Python 3.8 support (pull #[1334](https://github.com/aws-cloudformation/cfn-python-lint/pull/1334)) +- Add more resources to rule [I3011](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I3011) (pull #[1331](https://github.com/aws-cloudformation/cfn-python-lint/pull/1331)) +###### CloudFormation Specifications +- Patch specs from updated SSM service data as of 2020.01.30 (pull #[1339](https://github.com/aws-cloudformation/cfn-python-lint/pull/1339)) +- Patch more wafv2 resources (pull #[1343](https://github.com/aws-cloudformation/cfn-python-lint/pull/1343)) +###### Fixes +- Pin version of jsonpatch for Python 3.4 (pull #[1336](https://github.com/aws-cloudformation/cfn-python-lint/pull/1336)) + +### v0.27.3 +###### CloudFormation Specifications +- Update CloudFormation specs to 10.4.0 (pull #[1330](https://github.com/aws-cloudformation/cfn-python-lint/pull/1330)) + +### v0.27.2 +###### Fixes +- Update rule [E3026](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3026) to better check for condition scenarios and not fail (pull #[1327](https://github.com/aws-cloudformation/cfn-python-lint/pull/1327)) + +### v0.27.1 +###### CloudFormation Specifications +- Update CloudFormation patches to include pricing and SSM data from 2020.01.20 (pull #[1322](https://github.com/aws-cloudformation/cfn-python-lint/pull/1322)) +###### Fixes +- Update rule [E6001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E6001) to allow `Fn::Transform` (pull #[1321](https://github.com/aws-cloudformation/cfn-python-lint/pull/1321)) + +### v0.27.0 +###### Features +- Add additional configuration checks to rule [E2001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2001) (pull #[1301](https://github.com/aws-cloudformation/cfn-python-lint/pull/1301)) +- Add additional configuration checks to rule [E6001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E6001) (pull #[1301](https://github.com/aws-cloudformation/cfn-python-lint/pull/1301)) +- Move `Export` `Name` required from `Outputs` in rule [E6002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E6002) to [E6001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E6001) (pull #[1301](https://github.com/aws-cloudformation/cfn-python-lint/pull/1301)) +- Move checking for list in `Outputs` `Value` in rule [E6003](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E6003) to [E6001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E6001) (pull #[1301](https://github.com/aws-cloudformation/cfn-python-lint/pull/1301)) +- Add rules [I1002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I1002), [I1003](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I1003), [I2010](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I2010), [I2011](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I2011), [I2012](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I2012), [I3010](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I3010), [I3011](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I3011), [I6010](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I6010), [I6011](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I6011), [I6012](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I6012), [I7010](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I7010), [I7011](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I7011), [I7012](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I7012) to alert when approaching limits (pull #[1271](https://github.com/aws-cloudformation/cfn-python-lint/pull/1271)) +###### CloudFormation Specifications +- Update CloudFormation specs to 10.3.0 (pull #[1317](https://github.com/aws-cloudformation/cfn-python-lint/pull/1317)) +- Patch wafV2 Resources in the CloudFormation spec (pull #[1313](https://github.com/aws-cloudformation/cfn-python-lint/pull/1313)) +###### Fixes +- Update rules [E6001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E6001), [E6002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E6002), [E6003](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E6003) to filter out unneeded columns when processing conditions (pull #[1316](https://github.com/aws-cloudformation/cfn-python-lint/pull/1316)) +- Update rule [E1029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1029) to allow for exlusions in `NotResource` (pull #[1315](https://github.com/aws-cloudformation/cfn-python-lint/pull/1315)) +- Update rule [E3020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3020) to check for string types before doing regex (pull #[1311](https://github.com/aws-cloudformation/cfn-python-lint/pull/1311)) + +### v0.26.3 +###### Features +- Add extra attributes to rules [E1024](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1024), [E3027](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3027), [E3020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3020) (pull #[1272](https://github.com/aws-cloudformation/cfn-python-lint/pull/1272)) +###### CloudFormation Specifications +- Move `AWS::S3::Bucket.RoutingRuleCondition` properties from OnlyOne to AtLeastOne (pull #[1283](https://github.com/aws-cloudformation/cfn-python-lint/pull/1283)) +- Add `AWS::SSM::Parameter.Value` to the `AWS::EC2::VPC.Id` type (pull #[1288](https://github.com/aws-cloudformation/cfn-python-lint/pull/1288)) +- Add `CNAME` as an allowed value to `ServiceDiscoveryDnsType` (pull #[1296](https://github.com/aws-cloudformation/cfn-python-lint/pull/1296)) +- Patch `AWS::WAFv2::RegexPatternSet.RegularExpressionList` removing extra layer (pull #[1300](https://github.com/aws-cloudformation/cfn-python-lint/pull/1300)) +- Add `LambdaProvisionedConcurrencyUtilization` as allowed value to Application Autoscaling Metric (pull #[1303](https://github.com/aws-cloudformation/cfn-python-lint/pull/1303)) +- Add some exclusive attributes to `AWS::CloudWatch::Alarm` for `Metrics` and `Threshold` (pull #[1306](https://github.com/aws-cloudformation/cfn-python-lint/pull/1306)) +###### Fixes +- pyyaml has ended support for Python 3.4. Pin pyyaml to version 5.2 for Python 3.4 (pull #[1290](https://github.com/aws-cloudformation/cfn-python-lint/pull/1290)) +- Convert from using imp to importlib for python 3.x (pull #[1292](https://github.com/aws-cloudformation/cfn-python-lint/pull/1292)) + +### v0.26.2 +###### Features +- Update `aws-sam-translator` to `1.19.1` (pull #[1275](https://github.com/aws-cloudformation/cfn-python-lint/pull/1275)) +###### CloudFormation Specifications +- Update CloudFormation specs to 10.2.0 (pull #[1273](https://github.com/aws-cloudformation/cfn-python-lint/pull/1273)) +- Update EOL dates for Python 2.7 (pull #[1270](https://github.com/aws-cloudformation/cfn-python-lint/pull/1270)) +###### Fixes +- Update rule [W3011](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W3011) /[I3011](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I3011) to include resource path in message (pull #[1266](https://github.com/aws-cloudformation/cfn-python-lint/pull/1266)) + +### v0.26.1 +###### Features +- New rule [I3011](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I3011) to check stateful resources have a set UpdateReplacePolicy/DeletionPolicy (pull #[1232](https://github.com/aws-cloudformation/cfn-python-lint/pull/1232)) +###### CloudFormation Specifications +- Update CloudFormation specs to 10.1.0 (pull #[1255](https://github.com/aws-cloudformation/cfn-python-lint/pull/1255)) +- Add `ALLOW_` values to `ExplicitAuthFlows` (pull #[1261](https://github.com/aws-cloudformation/cfn-python-lint/pull/1261)) +###### Fixes +- Update rule [W3011](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W3011) to ignore W3011 if explicit DeletionPolicy/UpdateReplacePolicy value is Delete (pull #[1253](https://github.com/aws-cloudformation/cfn-python-lint/pull/1253)) +- Update rule [E1029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1029) to not alert when looking at Parameters (pull #[1256](https://github.com/aws-cloudformation/cfn-python-lint/pull/1256)) +- Update rule [E2504](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2504) to allow for ephemeral(0-23) (pull #[1260](https://github.com/aws-cloudformation/cfn-python-lint/pull/1260)) + +### v0.26.0 +###### Features +- Created a new `mandatory-checks` parameter to require rules to be reported on and not ignored (pull #[1243](https://github.com/aws-cloudformation/cfn-python-lint/pull/1243)) +- Allow using modules when doing `append-rules` (pull #[1216](https://github.com/aws-cloudformation/cfn-python-lint/pull/1216)) +- Add support for the new zone `us-west-2-lax-1a` (pull #[1241](https://github.com/aws-cloudformation/cfn-python-lint/pull/1241)) +###### CloudFormation Specifications +- Update CloudFormation specs to 10.0.0 (pull #[1247](https://github.com/aws-cloudformation/cfn-python-lint/pull/1247)) +###### Fixes +- Update rule [E8001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E8001) to allow for `Condition` (pull #[1246](https://github.com/aws-cloudformation/cfn-python-lint/pull/1246)) + +### v0.25.7 +###### CloudFormation Specifications +- Update pricing and services from 2019.12.02 (pull #[1237](https://github.com/aws-cloudformation/cfn-python-lint/pull/1237)) +- Update to specs to 9.1.1 (pull #[1237](https://github.com/aws-cloudformation/cfn-python-lint/pull/1237)) +###### Fixes +- `EnableVersionUpgrade` added to the recognized values for `UpdatePolicy` (pull #[1231](https://github.com/aws-cloudformation/cfn-python-lint/pull/1231)) +- Include `pathlib2` in python 3.4 requirements (pull #[1236](https://github.com/aws-cloudformation/cfn-python-lint/pull/1236)) +- Look at the top level Condition operator (pull #[1235](https://github.com/aws-cloudformation/cfn-python-lint/pull/1235)) +- Include more testing for using cfn-lint as a module (pull #[1234](https://github.com/aws-cloudformation/cfn-python-lint/pull/1234)) + +### 0.25.5 +###### CloudFormation Specifications +- Update CloudFormation specs to 9.1.0 (pull #[1224](https://github.com/aws-cloudformation/cfn-python-lint/pull/1224)) +- Add Allowed Pattern to Bucket Names (pull #[1208](https://github.com/aws-cloudformation/cfn-python-lint/pull/1208)) +###### Fixes +- Update rule [E2001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2001) to look for required properties (pull #[1227](https://github.com/aws-cloudformation/cfn-python-lint/pull/1227)) +- Update rule [E2503](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2503) to allow `routing.http.drop_invalid_header_fields.enabled` for application load balancers (pull #[1220](https://github.com/aws-cloudformation/cfn-python-lint/pull/1220)) +- Update rule [E1028](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1028) to check that Fn::If value is a list of length 3 (pull #[1226](https://github.com/aws-cloudformation/cfn-python-lint/pull/1226)) + +### 0.25.3 +###### CloudFormation Specifications +- Change DocDB allowed EngineVersion value to 3.6.0 (pull #[1213](https://github.com/aws-cloudformation/cfn-python-lint/pull/1213)) +###### Fixes +- Update rule [E3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3002) to handle nested IFs when looking at lists (pull #[1212](https://github.com/aws-cloudformation/cfn-python-lint/pull/1212)) +- Update rule [W2501](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2501) to only look at a Resource Properties (pull #[1214](https://github.com/aws-cloudformation/cfn-python-lint/pull/1214)) + +### 0.25.2 +###### CloudFormation Specifications +- Add capacityOptimized to spot fleet allocation strategy (pull #[1200](https://github.com/aws-cloudformation/cfn-python-lint/pull/1200)) +- Update Lambda runtime options to be valid as of 2019.11.19 (pull #[1204](https://github.com/aws-cloudformation/cfn-python-lint/pull/1204)) + +### 0.25.1 +###### CloudFormation Specifications +- Update allowed values for AWS Config types (pull #[1197](https://github.com/aws-cloudformation/cfn-python-lint/pull/1197)) +- Update CloudFormation specs to 8.1.0 (pull #[1197](https://github.com/aws-cloudformation/cfn-python-lint/pull/1197)) + +### 0.25.0 +###### Features +- Add rule [I1022](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I1022) to recommend Sub over Join when join is using empty delimiter (pull #[1067](https://github.com/aws-cloudformation/cfn-python-lint/pull/1067)) +- Remove setuptools requirement (pull #[1188](https://github.com/aws-cloudformation/cfn-python-lint/pull/1188)) +###### CloudFormation Specifications +- Update Lambda runtime versions EOL date (pull #[1180](https://github.com/aws-cloudformation/cfn-python-lint/pull/1180)) +- Update CloudFormation specs to 8.0.0 (pull #[1187](https://github.com/aws-cloudformation/cfn-python-lint/pull/1187)) +- Update Pricing and SSM data to 2019.11.08 (pull #[1187](https://github.com/aws-cloudformation/cfn-python-lint/pull/1187)) +###### Fixes +- Update rule [W2501](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2501) to include more properties to validate security of a parameter (pull #[1181](https://github.com/aws-cloudformation/cfn-python-lint/pull/1181)) +- Fix YAML parsing to not fail on merging and aliases (pull #[1182](https://github.com/aws-cloudformation/cfn-python-lint/pull/1182)) +- Fix an issue with SAM when CORS is present in pre-transformed template (pull #[1185](https://github.com/aws-cloudformation/cfn-python-lint/pull/1185)) +- Update rule [W7001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W7001) to look at pre-transformed FindInMaps (pull #[1186](https://github.com/aws-cloudformation/cfn-python-lint/pull/1186)) + +### 0.24.8 +###### CloudFormation Specifications +- Update CloudFormation specs to 7.2.0 (pull #[1177](https://github.com/aws-cloudformation/cfn-python-lint/pull/1177)) +- Update Pricing and SSM data to 2019.11.01 (pull #[1177](https://github.com/aws-cloudformation/cfn-python-lint/pull/1177)) + +### 0.24.7 +###### CloudFormation Specifications +- Patch in Tags for SNS Topics (pull #[1174](https://github.com/aws-cloudformation/cfn-python-lint/pull/1174)) +- Update Pricing and SSM data to 2019.10.31 (pull #[1175](https://github.com/aws-cloudformation/cfn-python-lint/pull/1175)) +###### Fixes +- Consolidate PSEUDOPARAMS into cfnlint.helpers (pull #[1172](https://github.com/aws-cloudformation/cfn-python-lint/pull/1172)) + +### 0.24.6 +###### Features +- Update SAM Translator to 1.15.1 (pull #[1166](https://github.com/aws-cloudformation/cfn-python-lint/pull/1166)) + +### 0.24.5 +###### CloudFormation Specifications +- Update CloudFormation specs to 7.1.0 (pull #[1163](https://github.com/aws-cloudformation/cfn-python-lint/pull/1163)) +- Update Pricing and SSM data to 2019.10.21 (pull #[1163](https://github.com/aws-cloudformation/cfn-python-lint/pull/1163)) +###### Fixes +- Update rule [E2532](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2532) to support parameters inside a map type (pull #[1164](https://github.com/aws-cloudformation/cfn-python-lint/pull/1164)) +- Update rule [E2510](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2510) to allow SSM parameter types for CIDR blocks (pull #[1162](https://github.com/aws-cloudformation/cfn-python-lint/pull/1162)) + +### 0.24.4 +###### CloudFormation Specifications +- Update CloudFormation specs to 6.3.0 (pull #[1155](https://github.com/aws-cloudformation/cfn-python-lint/pull/1155)) +- Update Pricing and SSM data to 2019.10.05 (pull #[1155](https://github.com/aws-cloudformation/cfn-python-lint/pull/1155)) +- Update Update CloudWatch alarm comparison operators (pull #[1154](https://github.com/aws-cloudformation/cfn-python-lint/pull/1154)) +###### Fixes +- Update rule [E1022](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1022) to allow lists in custom resources (pull #[1151](https://github.com/aws-cloudformation/cfn-python-lint/pull/1151)) + +### 0.24.3 +###### Features +- Add link to updated IntelliJ integration (pull #[1138](https://github.com/aws-cloudformation/cfn-python-lint/pull/1138)) +- Add link to emacs integration (pull #[1118](https://github.com/aws-cloudformation/cfn-python-lint/pull/1118)) +###### CloudFormation Specifications +- Update CloudFormation specs to 6.2.0 (pull #[1145](https://github.com/aws-cloudformation/cfn-python-lint/pull/1145)) +- Update Pricing and SSM data to 2019.09.28 (pull #[1145](https://github.com/aws-cloudformation/cfn-python-lint/pull/1145)) +- Remove manual patches that are no longer needed (pull #[1146](https://github.com/aws-cloudformation/cfn-python-lint/pull/1146)) +- Update CloudFormation spec links for a few regions that using old links (pull #[1148](https://github.com/aws-cloudformation/cfn-python-lint/pull/1148)) +###### Fixes +- Update rule [E3001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3001) to allow `DeletionPolicy` and `UpdateReplacePolicy` to be allowed on all resources (pull #[1139](https://github.com/aws-cloudformation/cfn-python-lint/pull/1139)) +- Update rule [W2030](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2030) to not check Paramter default values when using a Resource Condition (pull #[1140](https://github.com/aws-cloudformation/cfn-python-lint/pull/1140)) +- Update rule [E2532](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2532) to allow new types in Step Functions (pull #[1143](https://github.com/aws-cloudformation/cfn-python-lint/pull/1143)) + +### 0.24.2 +###### CloudFormation Specifications +- Add missing values for LifecyclePolicy API (pull #[1128](https://github.com/aws-cloudformation/cfn-python-lint/pull/1128)) +- Update CloudFormation specs to 6.1.0 (pull #[1134](https://github.com/aws-cloudformation/cfn-python-lint/pull/1134)) +- Update Pricing and SSM data to 2019.09.20 (pull #[1134](https://github.com/aws-cloudformation/cfn-python-lint/pull/1134)) +###### Fixes +- Update [E1029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1029) +to include cognito-identity keys to list of excluded resourse when checking if Fn sub is needed (pull #[1136](https://github.com/aws-cloudformation/cfn-python-lint/pull/1136)) + +### 0.24.1 +###### CloudFormation Specifications +- Update CloudFormation specs to 6.0.0 (pull #[1126](https://github.com/aws-cloudformation/cfn-python-lint/pull/1126)) +###### Fixes +- Update AWS::SQS::Queue.ReceiveMessageWaitTimeSeconds to allow 0 value (pull #[1123](https://github.com/aws-cloudformation/cfn-python-lint/pull/1123)) +- AWS::EC2::SecurityGroup.Description StringMin and StringMax should be integers (pull #[1125](https://github.com/aws-cloudformation/cfn-python-lint/pull/1125)) +- AWS::ApiGateway::GatewayResponse.ResponseType typo (pull #[1126](https://github.com/aws-cloudformation/cfn-python-lint/pull/1126)) + +### 0.24.0 +###### Features +- Move rule classes from cfnlint into cfnlint.rules (pull #[1098](https://github.com/aws-cloudformation/cfn-python-lint/pull/1098)) +###### CloudFormation Specifications +- Update IAM policies as of 2019.09.03 (pull #[1120](https://github.com/aws-cloudformation/cfn-python-lint/pull/1120)) +- Update CloudFormation specs from pricing and SSM data as of 2019.09.03 (pull #[1120](https://github.com/aws-cloudformation/cfn-python-lint/pull/1120)) +- Add a lot of min/max values to the specs (pull #[1110](https://github.com/aws-cloudformation/cfn-python-lint/pull/1110) and pull #[1116](https://github.com/aws-cloudformation/cfn-python-lint/pull/1116)) +###### Fixes +- Add me-south-1 to supported regions (pull #[1113](https://github.com/aws-cloudformation/cfn-python-lint/pull/1113)) +- Fix an issue where the spec file was referencing instance profiles for Glue Resources (pull #[1114](https://github.com/aws-cloudformation/cfn-python-lint/pull/1114)) + +### 0.23.5 +###### CloudFormation Specifications +- Switch AWS Batch SpotIamFleetRole to Role Arn (pull #[1111](https://github.com/aws-cloudformation/cfn-python-lint/pull/1111)) + +### 0.23.4 +###### CloudFormation Specifications +- Update CloudFormatin specs to 5.3.0 (pull #[1108](https://github.com/aws-cloudformation/cfn-python-lint/pull/1108)) +- Update CloudFormatin specs from pricing and SSM data on 2019.08.22 (pull #[1104](https://github.com/aws-cloudformation/cfn-python-lint/pull/1104)) +- Add 416 to the CloudFront Error Codes (pull #[1100](https://github.com/aws-cloudformation/cfn-python-lint/pull/1100)) +- Move a lot of types into separate files (pull #[1074](https://github.com/aws-cloudformation/cfn-python-lint/pull/1074)) +###### Fixes +- Don't fail getting directives when resources are malformed (pull #[1099](https://github.com/aws-cloudformation/cfn-python-lint/pull/1099)) + +### 0.23.3 +###### CloudFormation Specifications +- Add me-east-1 CloudFormation spec (pull #[1095](https://github.com/aws-cloudformation/cfn-python-lint/pull/1095)) +- Update CloudFormatin specs to 5.1.0 (pull #[1093](https://github.com/aws-cloudformation/cfn-python-lint/pull/1093)) +- Update spec patching from SSM and pricing to 2019.08.13 (pull #[1093](https://github.com/aws-cloudformation/cfn-python-lint/pull/1093)) +###### Fixes +- Remove requests and switch to urllib(2) (pull #[1093](https://github.com/aws-cloudformation/cfn-python-lint/pull/1093)) +- Fix rule [E3003](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3003) to not fail when running into a basic property in the CloudFormation spec (pull #[1096](https://github.com/aws-cloudformation/cfn-python-lint/pull/1096)) + +### 0.23.2 +###### CloudFormation Specifications +- Update CloudFormation spec to version 5.0.0 (pull #[1087](https://github.com/aws-cloudformation/cfn-python-lint/pull/1087)) +- Remove Ref check from IAM Policy Name (pull #[1087](https://github.com/aws-cloudformation/cfn-python-lint/pull/1087)) + +### 0.23.1 +###### Fixes +- Fix an issue where anything piped into cfn-lint would result in ignoring the templates parameter (pull #[1081](https://github.com/aws-cloudformation/cfn-python-lint/pull/1081)) + +### 0.23.0 +###### Features +- Add support for regions cn-north-1 and cn-northwest-1 (pull #[1051](https://github.com/aws-cloudformation/cfn-python-lint/pull/1051)) +- Add rule [E3027](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3027) to validate the format of AWS Event ScheduleExpression (pull #[1028](https://github.com/aws-cloudformation/cfn-python-lint/pull/1028)) +- Update SAM Translator support to release 1.13.0 (pull #[1054](https://github.com/aws-cloudformation/cfn-python-lint/pull/1054)) +- Extend rule [W2509](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2509) and [E2004](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2004) to check for more types of CIDR properties (pull #[1058](https://github.com/aws-cloudformation/cfn-python-lint/pull/1058)) +- Add Availability Zones for me-south-1 region (pull #[1070](https://github.com/aws-cloudformation/cfn-python-lint/pull/1070)) +- Update README to document using cfn-lint with github actions (pull #[1072](https://github.com/aws-cloudformation/cfn-python-lint/pull/1072)) +###### CloudFormation Specifications +- Restructure some of the patching to make organization easier (pull #[1030](https://github.com/aws-cloudformation/cfn-python-lint/pull/1030)) +- Update specs from pricing and SSM data as of 2019.08.01 (pull #[1078](https://github.com/aws-cloudformation/cfn-python-lint/pull/1078)) +- Remove IAM::User Tags and move IAM::Role Tag support to regions where it works (pull #[1077](https://github.com/aws-cloudformation/cfn-python-lint/pull/1077)) +###### Fixes +- Apply SAM Transform when template Transforms are a list (pull #[1056](https://github.com/aws-cloudformation/cfn-python-lint/pull/1056)) +- Fix an issue where templates provided via stdin where not getting linted (pull #[1060](https://github.com/aws-cloudformation/cfn-python-lint/pull/1060)) +- Fix rule [E2015](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2015) to convert integers to string when testing min/max length (pull #[1063](https://github.com/aws-cloudformation/cfn-python-lint/pull/1063)) +- Update excludes for [E1029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1029) to include TopicRulePayload (pull #[1066](https://github.com/aws-cloudformation/cfn-python-lint/pull/1066)) + +### 0.22.4 +###### Features +- Add ALL_REGIONS option for -r flag (pull #[1026](https://github.com/aws-cloudformation/cfn-python-lint/pull/1026)) +###### CloudFormation Specifications +- Add SSM parameter type values to [E2510](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2510) (pull #[1036](https://github.com/aws-cloudformation/cfn-python-lint/pull/1036)) +- Add allowed values for AWS::IAM Resources (pull #[1027](https://github.com/aws-cloudformation/cfn-python-lint/pull/1027)) +- Update CloudFormation spec to version 4.3.0 (pull #[1048](https://github.com/aws-cloudformation/cfn-python-lint/pull/1048)) +- Update specs from pricing and SSM data as of 2019.07.25 +###### Fixes +- Removed duplicate from list of Availability Zones (pull #[1035](https://github.com/aws-cloudformation/cfn-python-lint/pull/1035)) +- Fixed example regex in CIDR rule (pull #[1029](https://github.com/aws-cloudformation/cfn-python-lint/pull/1029)) +- Support for Serverless transform when it's in a list of one Transforms (pull #[1042](https://github.com/aws-cloudformation/cfn-python-lint/pull/1042)) +- Don't fail rules that include a Transform (pull #[1041](https://github.com/aws-cloudformation/cfn-python-lint/pull/1041)) +- Don't fail when AWS::NoValue used when we're looking for a list (pull #[1039](https://github.com/aws-cloudformation/cfn-python-lint/pull/1039)) +- Fixed [E3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3002) to support AWS::NoValue (pull #[1038](https://github.com/aws-cloudformation/cfn-python-lint/pull/1038)) +- Added FindInMap as valid function within Fn::Cidr (pull #[1034](https://github.com/aws-cloudformation/cfn-python-lint/pull/1034)) + +### 0.22.3 +###### CloudFormation Specifications +- Patch in `AWS::SageMaker::CodeRepository` to the CloudFormation spec (issue #[1005](https://github.com/aws-cloudformation/cfn-python-lint/issues/1005)) +- Patch in Tags into IAM Roles and Users (issue #[1015](https://github.com/aws-cloudformation/cfn-python-lint/issues/1015)) +- Update CloudFormation spec to version 4.2.0 (pull #[1023](https://github.com/aws-cloudformation/cfn-python-lint/pull/1023)) +- Update specs from pricing and SSM data as of 2019.07.13 +###### Fixes +- Add more Availability Zones (pull #[1021](https://github.com/aws-cloudformation/cfn-python-lint/pull/1021)) + +### 0.22.2 +###### CloudFormation Specifications +- Patch in `AWS::Cognito::UserPool` resource information for `ap-south-1` and `ap-southeast-1` (issue #[1002](https://github.com/aws-cloudformation/cfn-python-lint/issues/1002)) +- Remove manual patching for `AWS::Backup::BackupPlan` resource information and fix a few spec issues (pull #[1006](https://github.com/aws-cloudformation/cfn-python-lint/pull/1006)) +- Fix a few spec regex patterns that were missing escapes of `-` inside `[]` (issue #[997](https://github.com/aws-cloudformation/cfn-python-lint/issues/997)) +- Update pricing script to include bare metal instance types (issue #[998](https://github.com/aws-cloudformation/cfn-python-lint/issues/998)) +- Create a regex pattern for IAM Policy Names (issue #[996](https://github.com/aws-cloudformation/cfn-python-lint/issues/996)) +- Patch CloudFormation specs from SSM data on 2019.07.10 +###### Fixes +- Fix a warning when loading resources using a `\` in the prefix (issue #[1009](https://github.com/aws-cloudformation/cfn-python-lint/issues/1009)) + +### 0.22.1 +###### CloudFormation Specifications +- Add `INSTANCE` to `DLMPolicyResourceType` allowed values (pull #[995](https://github.com/aws-cloudformation/cfn-python-lint/pull/995)) +- Update specs from weird 4.1.0 release (pull #[994](https://github.com/aws-cloudformation/cfn-python-lint/pull/994)) +- Update instance types and patches from SSM to date 2019.07.04 (pull #[1001](https://github.com/aws-cloudformation/cfn-python-lint/pull/1001)) +- Add all the allowed values of the AWS::EFS Resources (pull #[990](https://github.com/aws-cloudformation/cfn-python-lint/pull/990)) +###### Fixes +- Fix an issue where rules were being loaded twice (pull #[980](https://github.com/aws-cloudformation/cfn-python-lint/pull/980)) +- Fix an issue with rule [E1010](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1010) to split GetAtt strings into two values (issue #[986](https://github.com/aws-cloudformation/cfn-python-lint/issues/986)) +- Update rules [E8004](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E8004), [E8003](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E8003), [E8005](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E8005), and [E8006](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E8006) to not flag functions used in Service Catalog rules section (issue #[979](https://github.com/aws-cloudformation/cfn-python-lint/issues/979)) +- Patched testing for Lambda Runtime EOL and end dates to test as if a specific date (pull #[999](https://github.com/aws-cloudformation/cfn-python-lint/pull/999)) + +### 0.22.0 +###### CloudFormation Specifications +- Update specs to 4.1.0 +- Added LaunchTemplateId/LaunchTemplateName of the AutoScalingGroup to the OnlyOne +- Patch resource AWS::EC2::LaunchTemplate property TagSpecifications +- Add AWS::EC2::LaunchTemplate property to LaunchTemplateName min/max/pattern +- Add AWS::EC2::LaunchTemplate allowed values for the ResourceType property +- Remove/Add services to region tables based on SSM endpoints +###### Fixes +- Update JsonSchem to 3.0 to support the new version 1.12.0 of aws-sam-translator +- Update rule [E2503](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2503) to allow NLBs to use UDP +- Update rule [E3020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3020) to include many special characters for DNS records +- Sort filenames when getting a bunch of templates from a folder +- Fix typos in the integration documentation + +### 0.21.6 +###### Features +- Remove rule [W2507](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2507) and use rule [E3008](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3008) instead +- Remove rule [W2508](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2508) and use rule [E3008](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3008) instead +###### CloudFormation Specifications +- Update specs to 3.4.0 +- Add all the allowed values of the AWS::ECS Resources. +- Update CloudFormation Spec to include the Backup Resources +- Add Cognito RefreshTokenValidity number limits +###### Fixes +- Fix copy-paste typo in Not function check +- Don't fail when conditions are used with parameters and allowed values +- More IAM Resource exceptions for Sub Needed check + +### 0.21.5 +###### Features +- Update rule [E3001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3001) to validate that a Resource Condition is a string +###### CloudFormation Specifications +- Add all the allowed values of the AWS::EC2 CapacityReservation Resources +- Update Launch Configuration IamInstanceProfile to support Ref or GetAtt to an IAM Instance Profile +###### Fixes +- Fix `lessthan` type in a bunch of rules +- Update rule [E2507](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2507) to handle intrinsics when testing the values for `Effect` +- Fix rule [E8002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E8002) to not error when the Condition isn't a string + +### 0.21.4 +###### Features +- Include more resource types in [W3037](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W30307) +###### CloudFormation Specifications +- Add Resource Type `AWS::CDK::Metadata` +###### Fixes +- Uncap requests dependency in setup.py +- Check Join functions have lists in the correct sections +- Pass a parameter value for AutoPublishAlias when doing a Transform +- Show usage examples when displaying the help + +### 0.21.3 +###### Fixes +- Support dumping strings for datetime objects when doing a Transform + +### 0.21.2 +###### CloudFormation Specifications +- Update CloudFormation specs to 3.3.0 +- Update instance types from pricing API as of 2019.05.23 + +### 0.21.1 +###### Features +- Add `Info` logging capability and set the default logging to `NotSet` +###### Fixes +- Only do rule logging (start/stop/time) when the rule is going to be called +- Update rule [E1019](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1019) to allow `Fn::Transform` inside a `Fn::Sub` +- Update rule [W2001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2001) to not break when `Fn::Transform` inside a `Fn::Sub` +- Update rule [E2503](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2503) to allow conditions to be used and to not default to `network` load balancer when an object is used for the Load Balancer type + +### 0.21.0 +###### Features +- New rule [E3038](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3038) to check if a Serverless resource includes the appropriate Transform +- New rule [E2531](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2531) to validate a Lambda's runtime against the deprecated dates +- New rule [W2531](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2531) to validate a Lambda's runtime against the EOL dates +- Update rule [E2541](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2541) to include updates to Code Pipeline capabilities +- Update rule [E2503](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2503) to include checking of values for load balancer attributes +###### CloudFormation Specifications +- Update CloudFormation specs to 3.2.0 +- Update instance types from pricing API as of 2019.05.20 +###### Fixes +- Include setuptools in setup.py requires + +### 0.20.3 +###### CloudFormation Specifications +- Update instance types from pricing API as of 2019.05.16 +###### Fixes +- Update [E7001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E7001) to allow float/doubles for mapping values +- Update [W1020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W1020) to check pre-transformed Fn::Sub(s) to determine if a Sub is needed +- Pin requests to be below or equal to 2.21.0 to prevent issues with botocore + +### 0.20.2 +###### Features +- Add support for List Parameter types +###### CloudFormation Specifications +- Add allowed values for AWS::EC2 EIP, FlowLog, CustomerGateway, DHCPOptions, EC2Fleet +- Create new property type for Security Group IDs or Names +- Add new Lambda runtime environment for NodeJs 10.x +- Move AWS::ServiceDiscovery::Service Health checks from Only One to Exclusive +- Update Glue Crawler Role to take an ARN or a name +- Remove PrimitiveType from MaintenanceWindowTarget Targets +- Add Min/Max values for Load Balancer Ports to be between 1-65535 +###### Fixes +- Include License file in the pypi package to help with downstream projects +- Filter out dynamic references from rule [E3031](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3031) and [E3030](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3030) +- Convert Python linting and Code Coverage from Python 3.6 to 3.7 + +### 0.20.1 +###### Fixes +- Update rule [E8003](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E8003) to support more functions inside a Fn::Equals + +### 0.20.0 +###### Features +- Allow a rule's exception to be defined in a [resource's metadata](https://github.com/aws-cloudformation/cfn-python-lint/#resource-based-metadata) +- Add rule [configuration capabilities](https://github.com/aws-cloudformation/cfn-python-lint/#configure-rules) +- Update rule [E3012](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3012) to allow for non strict property checking +- Add rule [E8003](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E8003) to test Fn::Equals structure and syntax +- Add rule [E8004](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E8004) to test Fn::And structure and syntax +- Add rule [E8005](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E8005) to test Fn::Not structure and syntax +- Add rule [E8006](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E8006) to test Fn::Or structure and syntax +- Include Path to error in the JSON output +- Update documentation to describe how to install cfn-lint from brew +###### CloudFormation Specifications +- Update CloudFormation specs to version 3.0.0 +- Add new region ap-east-1 +- Add list min/max and string min/max for CloudWatch Alarm Actions +- Add allowed values for EC2::LaunchTemplate +- Add allowed values for EC2::Host +- Update allowed values for Amazon MQ to include 5.15.9 +- Add AWS::Greengrass::ResourceDefinition to GreenGrass supported regions +- Add AWS::EC2::VPCEndpointService to all regions +- Update AWS::ECS::TaskDefinition ExecutionRoleArn to be a IAM Role ARN +- Patch spec files for SSM MaintenanceWindow to look for Target and not Targets +- Update ManagedPolicyArns list size to be 20 which is the hard limit. 10 is the soft limit. +###### Fixes +- Fix rule [E3033](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3033) to check the string size when the string is inside a list +- Fix an issue in which AWS::NotificationARNs was not a list +- Add AWS::EC2::Volume to rule [W3010](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W3010) +- Fix an issue with [W2001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2001) where SAM translate would remove the Ref to a parameter causing this error to falsely trigger +- Fix rule [W3010](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W3010) to not error when the availability zone is 'all' + +### 0.19.1 +###### Fixes +- Fix core Condition processing to support direct Condition in another Condition +- Fix the W2030 to check numbers against string allowed values + +### 0.19.0 +###### Features +- Add NS and PTR Route53 record checking to rule [E3020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3020) +- New rule [E3050](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3050) to check if a Ref to IAM Role has a Role path of '/' +- New rule [E3037](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3037) to look for duplicates in a list that doesn't support duplicates +- New rule [I3037](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I3037) to look for duplicates in a list when duplicates are allowed +###### CloudFormation Specifications +- Add Min/Max values to AWS::ElasticLoadBalancingV2::TargetGroup HealthCheckTimeoutSeconds +- Add Max JSON size to AWS::IAM::ManagedPolicy PolicyDocument +- Add allowed values for AWS::EC2 SpotFleet, TransitGateway, NetworkAcl +NetworkInterface, PlacementGroup, and Volume +- Add Min/max values to AWS::Budgets::Budget.Notification Threshold +- Update RDS Instance types by database engine and license definitions using the pricing API +- Update AWS::CodeBuild::Project ServiceRole to support Role Name or ARN +- Update AWS::ECS::Service Role to support Role Name or ARN +###### Fixes +- Update [E3025](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3025) to support the new structure of data in the RDS instance type json +- Update [E2540](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2540) to remove all nested conditions from the object +- Update [E3030](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2540) to not do strict type checking +- Update [E3020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3020) to support conditions nested in the record sets +- Update [E3008](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3008) to better handle CloudFormation sub stacks with different GetAtt formats + +### 0.18.1 +###### CloudFormation Specifications +- Update CloudFormation Specs to 2.30.0 +- Fix IAM Regex Path to support more character types +- Update AWS::Batch::ComputeEnvironment.ComputeResources InstanceRole to reference an +InstanceProfile or GetAtt the InstanceProfile Arn +- Allow VPC IDs to Ref a Parameter of type String +###### Fixes +- Fix [E3502](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3502) to check the size of the property instead of the parent object + +### 0.18.0 +###### Features +- New rule [E3032](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3032) to check the size of lists +- New rule [E3502](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3502) to check JSON Object Size using definitions in the spec file +- New rule [E3033](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3033) to test the minimum and maximum length of a string +- New rule [E3034](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3034) to validate the min and max of a number +- Remove Ebs Iops check from [E2504](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2504) and use rule [E3034](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3034) instead +- Remove rule [E2509](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2509) and use rule [E3033](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3033) instead +- Remove rule [E2508](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2508) as it replaced by [E3032](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3032) and [E3502](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3502) +- Update rule [E2503](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2503) to check that there are at least two 2 Subnets or SubnetMappings for ALBs +- SAM requirement upped to minimal version of 1.10.0 +###### CloudFormation Specifications +- Extend specs to include: + - `ListMin` and `ListMax` for the minimum and maximum size of a list + - `JsonMax` to check the max size of a JSON Object + - `StringMin` and `StringMax` to check the minimum and maximum length of a String + - `NumberMin` and `NumberMax` to check the minimum and maximum value of a Number, Float, Long +- Update State and ExecutionRoleArn to be required on AWS::DLM::LifecyclePolicy +- Add AllowedValues for PerformanceInsightsRetentionPeriod for AWS::RDS::Instance +- Add AllowedValues for the AWS::GuardDuty Resources +- Add AllowedValues for AWS::EC2 VPC and VPN Resources +- Switch IAM Instance Profiles for certain resources to the type that only takes the name +- Add regex pattern for IAM Instance Profile when a name (not Arn) is used +- Add regex pattern for IAM Paths +- Add Regex pattern for IAM Role Arn +- Update OnlyOne spec to require require at least one of Subnets or SubnetMappings with ELB v2 +###### Fixes +- Fix serverless transform to use DefinitionBody when Auth is in the API definition +- Fix rule [W2030](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2030) to not error when checking SSM or List Parameters + +### 0.17.1 +###### Features +- Update rule [E2503](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2503) to make sure NLBs don't have a Security Group configured +###### CloudFormation Specifications +- Add all the allowed values of the `AWS::Glue` Resources +- Update OnlyOne check for `AWS::CloudWatch::Alarm` to only `MetricName` or `Metrics` +- Update Exclusive check for `AWS::CloudWatch::Alarm` for properties mixed with `Metrics` and `Statistic` +- Update CloudFormation specs to 2.29.0 +- Fix type with MariaDB in the AllowedValues +- Update pricing information for data available on 2018.3.29 +###### Fixes +- Fix rule [E1029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1029) to not look for a sub is needed when looking for iot strings in policies +- Fix rule [E2541](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2541) to allow for ActionId Versions of length 1-9 and meets regex `[0-9A-Za-z_-]+` +- Fix rule [E2532](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2532) to allow for `Parameters` inside a `Pass` action +- Fix an issue when getting the location of an error in which numbers are causing an attribute error + +### 0.17.0 +###### Features +- Add new rule [E3026](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3026) to validate Redis cluster settings including AutomaticFailoverEnabled and NumCacheClusters. Status: Released +- Add new rule [W3037](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W3037) to validate IAM resource policies. Status: Experimental +- Add new parameter `-e/--include-experimental` to allow for new rules in that aren't ready to be fully released +###### CloudFormation Specifications +- Update Spec files to 2.28.0 +- Add all the allowed values of the AWS::Redshift::* Resources +- Add all the allowed values of the AWS::Neptune::* Resources +- Patch spec to make AWS::CloudFront::Distribution.LambdaFunctionAssociation.LambdaFunctionARN required +- Patch spec to make AWS::DynamoDB::Table AttributeDefinitions required +###### Fixes +- Remove extra blank lines when there is no errors in the output +- Add exception to rule [E1029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1029) to have exceptions for EMR CloudWatchAlarmDefinition +- Update rule [E1029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1029) to allow for literals in a Sub +- Remove sub checks from rule [E3031](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3031) as it won't match in all cases of an allowed pattern regex check +- Correct typos for errors in rule [W1001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W1001) +- Switch from parsing a template as Yaml to Json when finding an escape character +- Fix an issue with SAM related to transforming templates with Serverless Application and Lambda Layers +- Fix an issue with rule [E2541](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2541) when non strings were used for Stage Names + +### 0.16.0 +###### Features +- Add rule [E3031](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3031) to look for regex patterns based on the patched spec file +- Remove regex checks from rule [E2509](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2509) +- Add parameter `ignore-templates` to allow the ignoring of templates when doing bulk linting +###### CloudFormation Specifications +- Update Spec files to 2.26.0 +- Add all the allowed values of the AWS::DirectoryService::* Resources +- Add all the allowed values of the AWS::DynamoDB::* Resources +- Added AWS::Route53Resolver resources to the Spec Patches of ap-southeast-2 +- Patch the spec file with regex patterns +- Add all the allowed values of the AWS::DocDb::* Resources +###### Fixes +- Update rule [E2504](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2504) to have '20000' as the max value +- Update rule [E1016](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1016) to not allow ImportValue inside of Conditions +- Update rule [E2508](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2508) to check conditions when providing limit checks on managed policies +- Convert unicode to strings when in Py 3.4/3.5 and updating specs +- Convert from `awslabs` to `aws-cloudformation` organization +- Remove suppression of logging that was removed from samtranslator >1.7.0 and incompatibility with +samtranslator 1.10.0 + +### 0.15.0 +###### Features +- Add scaffolding for arbitrary Match attributes, adding attributes for Type checks +- Add rule [E3024](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3024) to validate that ProvisionedThroughput is not specified with BillingMode PAY_PER_REQUEST +###### CloudFormation Specifications +- Update Spec files to 2.24.0 +- Update OnlyOne spec to have BlockDeviceMapping to include NoDevice with Ebs and VirtualName +- Add all the allowed values of the AWS::CloudFront::* Resources +- Add all the allowed values of the AWS::DAX::* Resources +###### Fixes +- Update config parsing to use the builtin Yaml decoder +- Add condition support for Inclusive [E2521](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2521), Exclusive [E2520](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2520), and AtLeastOne [E2522](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2522) rules +- Update rule [E1029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1029) to better check Resource strings inside IAM Policies +- Improve the line/column information of a Match with array support + +### 0.14.1 +###### CloudFormation Specifications +- Update CloudFormation Specs to version 2.23.0 +- Add allowed values for AWS::Config::* resources +- Add allowed values for AWS::ServiceDiscovery::* resources +- Fix allowed values for Apache MQ +###### Fixes +- Update rule [E3008](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3008) to not error when using a list from a custom resource +- Support simple types in the CloudFormation spec +- Add tests for the formatters + +### 0.14.0 +###### Features +- Add rule [E3035](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3035) to check the values of DeletionPolicy +- Add rule [E3036](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3036) to check the values of UpdateReplacePolicy +- Add rule [E2014](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2014) to check that there are no REFs in the Parameter section +- Update rule [E2503](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2503) to support TLS on NLBs +###### CloudFormation Specifications +- Update CloudFormation spec to version 2.22.0 +- Add allowed values for AWS::Cognito::* resources +###### Fixes +- Update rule [E3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3002) to allow GetAtts to Custom Resources under a Condition + +### 0.13.2 +###### Features +- Introducing the cfn-lint logo! +- Update SAM dependency version +###### Fixes +- Fix CloudWatchAlarmComparisonOperator allowed values. +- Fix typo resoruce_type_spec in several files +- Better support for nested And, Or, and Not when processing Conditions + +### 0.13.1 +###### CloudFormation Specifications +- Add allowed values for AWS::CloudTrail::Trail resources +- Patch spec to have AWS::CodePipeline::CustomActionType Version included +###### Fixes +- Fix conditions logic to use AllowedValues when REFing a Parameter that has AllowedValues specified + +### 0.13.0 +###### Features +- New rule [W1011](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W1011) to check if a FindInMap is using the correct map name and keys +- New rule [W1001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W1001) to check if a Ref/GetAtt to a resource that exists when Conditions are used +- Removed logic in [E1011](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1011) and moved it to [W1011](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W1011) for validating keys +- Add property relationships for AWS::ApplicationAutoScaling::ScalingPolicy into Inclusive, Exclusive, and AtLeastOne +- Update rule [E2505](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2505) to check the netmask bit +- Include the ability to update the CloudFormation Specs using the Pricing API +###### CloudFormation Specifications +- Update to version 2.21.0 +- Add allowed values for AWS::Budgets::Budget +- Add allowed values for AWS::CertificateManager resources +- Add allowed values for AWS::CodePipeline resources +- Add allowed values for AWS::CodeCommit resources +- Add allowed values for EC2 InstanceTypes from pricing API +- Add allowed values for RedShift InstanceTypes from pricing API +- Add allowed values for MQ InstanceTypes from pricing API +- Add allowed values for RDS InstanceTypes from pricing API +###### Fixes +- Fixed README indentation issue with .pre-commit-config.yaml +- Fixed rule [E2541](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2541) to allow for multiple inputs/outputs in a CodeBuild task +- Fixed rule [E3020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3020) to allow for a period or no period at the end of a ACM registration record +- Update rule [E3001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3001) to support UpdateReplacePolicy +- Fix a cli issue where `--template` wouldn't be used when a .cfnlintrc was in the same folder +- Update rule [E3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3002) and [E1024](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W3002) to support packaging of AWS::Lambda::LayerVersion content + +### 0.12.1 +###### CloudFormation Specifications +- Add AWS::WorkSpaces::Workspace.WorkspaceProperties ComputeTypeName, RunningMode allowed values +- Fix AWS::CloudWatch::Alarm to point Metrics at AWS::CloudWatch::Alarm.MetricDataQuery +###### Fixes +- Update rule [E1024](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1024) to support Fn::Sub inside Fn::Cidr + +### 0.12.0 +###### Features +- Update rule [E1019](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1019) to not allow for lists directly when doing a Ref or GetAtt to a list +- Move parameter checks from rule [E3030](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3030) to a new rule [W2030](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2030) +###### CloudFormation Specifications +- Updated to version 2.19.0 +- Add S3 Bucket Allowed Values +- Add Route53 Allowed Values +- Add CodeDeploy Allowed Values +- Add AWS::SecretsManager::SecretTargetAttachment TargetType Allowed Values +- Add AWS::SES::ReceiptRule.Rule TlsPolicy Allowed Values +- Add AWS::AutoScaling::AutoScalingGroup, AWS::Route53::RecordSetGroup, and AWS::AutoScaling::AutoScalingGroup to OnlyOne +###### Fixes +- Improve [W7001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W7001) error message + +### 0.11.1 +###### CloudFormation Specifications +- Support Ref to IAM::Role or IAM::InstanceProfile with values looking for an ARN +- AWS::Batch::ComputeEnvironment InstanceRole is an InstanceProfile not Role +###### Fixes +- Add debug options to print a stack trace for rule E0002 +- Update rule [E2015](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2015) to include a try/catch around AllowedPattern testing to catch errors caused by non Python supported regex + +### 0.11.0 +###### Features +- Add rule [E3030](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3030) to use the newly patched spec to check resource properties values. Update the following rules replaced by [E3030](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3030). + - Delete rule [W2512](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2512) + - Delete rule [E2531](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2531) + - Move allowed values check in rule [E2505](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2505) +- Add rule [E3008](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3008) to use the newly patched spec to check a resource properties Ref and GetAtt. Update the following rules replaced by [E3008](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3008). + - Delete rule [E2502](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2502) + - Delete rule [W2505](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2505) +- Improve rule [E3020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3020) to check MX records +###### CloudFormation Specifications +- Update CloudFormation specs to 2.18.1 +- Append the CloudFormation spec to include: + - AllowedValues for resource properties + - Allowed Ref/GetAtts for resource properties +- Add specs for regions `eu-north-1`, `us-gov-east-1`, `us-gov-west-1` +- Add `AWS::StepFunctions::StateMachine` in all supported regions +- Add `AWS::CloudWatch::Alarm.Metric`, `AWS::CloudWatch::Alarm.MetricDataQuery` and `AWS::CloudWatch::Alarm.MetricStat` in all supported regions +- Add `AWS::Lambda::LayerVersion`, `AWS::Lambda::LayerVersion.Content`, and `AWS::Lambda::LayerVersionPermission` in all supported regions +###### Fixes +- Fix description on rule [W2501](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2501) to be more informative +- Update rule [E2532](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2532) to allow `Parameters` in a `Task` in a Step Function +- Fix rule [E1010](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1010) to allow Refs in the GetAtt attribute section +- Add `AWS::CloudFormation::Init` as an exception for rule E1029 +- Add `Informational` error messages to JSON outputs +- Fix file searching `**/*` to recursively search in Python 3.5 and greater +- Update CopyRight from 2018 to 2019 + +### 0.10.2 +###### Features +- Code coverage testing integrated into the CI process +- Update CloudFormation specs to 2.18.0 +###### Fixes +- Fix rule [E2505](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2505) to allow for SSM parameters when checking Cidr and Tenancy parameters +- Fix rule [E1029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1029) to not error on API Gateway stageVariables + +### 0.10.1 +###### Features +- Support stdin for reading and testing templates +###### Fixes +- Remove dependency on regex package as it requires gcc +- Remove rule [E3507](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3507) because it depends on regex package + +### 0.10.0 +###### Features +- Update specs to version 2.16.0 +###### Fixes +- Require pathlib2 in Python versions earlier than 3.4.0 +- Update aws-sam-translator to v1.8.0 +- Update requests dependency to be at least version 2.15.0 +- Add Python 3.7 support for Lambda +- Provide valid Python runtimes in rule [E2531](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2531) error message +- Allow Fn::Sub inside a Fn::Sub for rule [E1019](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1019) +- Add hardcoded list check as invalid in rule [E6003](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E6003) +- Fix home expansion with when looking for .cfnlintrc in Python 3.4 +- Add testing in Travis for Py34, Py35, Py37 +- Prevent spaces after the comma in spec file +- Update allowed Lambda Runtimes to include provided and ruby + +### 0.9.2 +###### Features +- Update specs to version 2.15.0 +###### Fixes +- Fix rule [E3020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3020) to allow multiple text records of up to 255 characters +- Fix rule [E3016](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3016) to handle conditions in Update Policies +- Fix rule [E2532](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2532) to not fail when using a Fn::Sub and a number for a param + +### 0.9.1 +###### Features +- Add support for eu-west-3 and ap-northeast-3 +- Add Resource Type AWS::CloudFormation::Macro to CloudFormation Spec +###### Fixes +- Fix the error message for YAML null being off by 1 line and 1 column number +- Add Custom Error for when trying to access an attribute in the classes that make up the template +- Fix an issue with deepcopy not creating copies with start and end marks +- Fix 4 rules that would fail when trying to create the path of the error and running into an integer +- Fix rule [E2015](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2015) to force parameter default values to be a string when testing against the AllowedPattern regex pattern +- Fix a bug in the config engine in which append rules would have gone to override spec +- Remove exit calls from functions that are used in integrations preventing pre-mature failures +- Fix rule [E3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3002) [E3003](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3003) to support functions that may be able to support objects + +### 0.9.0 +###### Features +- Add rule [E8002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E8002) to validate if resource Conditions or Fn::If conditions are defined +- Improve rule [E3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3002) to validate custom resources when custom specs are addended to the resource spec using override-spec +- Allow for configuration of cfn-lint using configuration files in the project and home folder called .cfnlintrc +- Updated specs to versions release 2.12.0 +###### Fixes +- Fix rule [E3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3002) to not fail when looking for lists of objects and using a FindInMap or GetAtt to a custom resource as both could suppliy a list of objects +- Remove rule [E1025](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1025) which was duplicative to the more extensive rule E8002 +- Fix rule [E3020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3020) to allow for quotes when checking the length +- Add generic exception handling to SAM transforming functions +- Complete redo how we handle arguments to fix issues created when linting multiple files with cfn-lint configurations in the file +- New CloudFormation spec patch to not require CidrBlock on resource type AWS::EC2::NetworkAclEntry +- New updates to AtLeastOne.json definition to require CidrBlock or Ipv6CidrBlock on resource type AWS::EC2::NetworkAclEntry +- A few documentation improvements + +### 0.8.3 +###### Features +- Add rule [E3022](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3022) to validate that there is only one SubnetRouteTableAssociation per subnet +###### Fixes +- Fix rule [E2502](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2502) to check Arn and Name for AWS::EC2::LaunchTemplate resources +- Fix rule [E3016](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3016) to remove use of Path which may not be defined in certain scenarios +- Fix base rule Class so that resource_property_types and resource_sub_property_types is initialized from on every new rule and not copied from previous rules that were initialized +- Fix conversions of transformed templates in which keys stayed as str(s) instead of str_node(s) + +### 0.8.2 +###### Fixes +- Update rule [E2502](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2502) to allow GetAtt against a nested stack or custom resource +- Update rules [E2541](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2541) and [E2540](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2540) to support conditions inside the CodePipeline +- Fix types in rule [E2532](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2532) to now include InputPath and OutputPath +- Update rule [E1029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1029) to skip missing sub when looking at parameters in IAM policies +- Update rule [E2507](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2507) to allow for strings in the IAM policy +- Update rule [E2507](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2507) to allow the policy statement to be an object along with a list + +### 0.8.1 +###### Features +- Update Specs to the versions released October 19th, 2018 +###### Fixes +- Fix rule [E2541](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2541) to not fail on non-string values + +### 0.8.0 +###### Features +- Created a process to patch the CloudFormation Spec and patched a bunch of issues +- Support pre-commit hooks for linting templates +- Add rule [E3021](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3021) to that 5 or less targets are added to a CloudWatch Event +- Add rule [E1029](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1029) to look for Sub variables that aren't inside a Sub +- Add rule [I3011](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#I3011) to validate that DynamDB Tables have deletion policy specified as the default is to delete the database. +- Add support for `info` errors +###### Fixes +- Update search_deep_keys to look for items in the Global section which is lost in a Transformation +- Clean up failures when loading files that are not yaml or json + +### 0.7.4 +###### Features +- Support parsing multiple files from the command line +- New rule [E3016](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3016) to validate a resources UpdatePolicy configuration +###### Fixes +- Removes sub parameter check from rule [E1012](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1012). The same check is covered by +[E1019](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1019) +- Fix rule [E1010](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1010) when using a string not an array with Fn::Sub +- Fix rule [E3020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3020) ignore intrinsic functions when checking values + +### 0.7.3 +###### Features +- Update the custom objects for the template to directly allow the calling of getting items and checking items that is condition safe +- Update CloudFormation Specs to 2018-09-21 released specs +###### Fixes +- Fix rule [E2540](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2540) to not fail when the stage names aren't strings +- Fix rule [E3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3002) to not fail when processing Ref AWS::NoValue +- Core functionality updated to fail when extending rules directory doesn't exist +- Fix rule [E3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3002) metadata isn't supported as a resource property +- Fix rule [E2509](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2509) to not error when using a function for description + +### 0.7.2 +###### Fixes +- Fix rule [W2501](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2501) to support dashes in KMS Key name +- Fix rule [E2543](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2543) to not fail when the type of a step isn't known +- Fix rule [E2507](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2507) to have an exception for ECR Policies. Resource isn't required. +- Several Python cleanup items around initializing lists, how version is loaded, and dropping 'discover' in testing + +### 0.7.1 +###### Fixes +- Fix core decoding so the true error of a template parsing issue is visible to the user + +### 0.7.0 +###### Features +- New Rule [W1019](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W1019) to make sure any Sub variables are used in the string +- New Rule [E2532](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2532) to start basic validation of state machine syntax +- New Rule [W1020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W1020) to see if Sub is needed and variables are being used +- New Rule [E1028](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1028) validate that first element in a Fn::If array is a string +- New Rule [W3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W3002) to warn when templated templates are used +- Update Rule [E2507](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2507) to check resource base policies +- Add Rule [W2511](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2511) to warn when using an older version of IAM Policy Version +###### Fixes +- Update Rule [E3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3002) to allow for templated code +- Update Rule [E1024](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1024) to allow Cidr function to use GetAtt +- Fix core functionality to not error if the template is an array or string instead of an object + +### 0.6.1 +###### Fixes +- Fixes an issue where Template.get_values would return `Ref: AWS::NoValue`. This will no longer be returned as it is considered to be a Null value. + +### 0.6.0 +###### Features +- Update formatters to be similar from JSON and text outputs and modularize for easier growth later +- Don't raise an error with [E3020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3020) when doing ACM DNS validation registration +- Add rule [E7003](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E7003) to validate that mapping keys are strings. +- Add rule [E1027](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1027) to validate that dynamic reference secure strings are to supported properties +- Add rule [E1004](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1004) to validate that the Template Description is only a string +- Add rule [E6005](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E6005) to validate that an Output Description is only a string +- Add rule [E6012](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E6012) to validate that an Output Description is less than the maximum length +###### Fixes +- Fix core libraries to handle conditions around resource properties so that the resource and property checks still run +- Fix core libraries to handle the special property type `Tag` so that its checked when a rule is doing a Property Check + +### 0.5.2 +###### Fixes +- Support additional attributes in spec file for [E3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3003) +- Check custom resources as if they are 'AWS::CloudFormation::CustomResource' in rule [E3003](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3003) +- Fix [W6001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W6001) when an ImportValue is used to another function +- Fix [W2501](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W2501) to support the new dynamic reference feature + +### 0.5.1 +###### Features +- Update rule [E3020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3020) to support CAA and CNAME record checks +- Update specs to ones released on August 16, 2018 + +### 0.5.0 +###### Features +- Load all instances of CloudFormationLintRule in a file. Class doesn't need to match the filename anymore +- Allow load yaml to accept a string allowing people to use cfn-lint as a module +- Add rule [W6001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W6001) to test outputs that are just using an import value +- Update specs to ones released on August 10, 2018 +###### Fixes +- Update [E2507](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2507) to support conditions and using get_values to test all condition paths +- Update [E2521](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2521), [E2523](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2523) to support conditions and using get_values to test all condition paths +- Rewrite [E2503](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2503) to support intrinsic functions and conditions and lower case protocols +- Fix [E1018](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1018) to support Sub inside a Split function +- Fix [E3003](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3003) description messages to be more informative +- Fix [E3001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3001) to not require parameters when CreationPolicy is used +- Fix SAM region when no region is available from a local AWS profile or environment variable. + +### 0.4.2 +###### Features +- Update rule [E3020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3020) to support AAAA record checks +###### Fixes +- Fix many rules that would fail if a sub parameter had a space at the beginning or end +- Fix crashing issues when trying to get resources that aren't properly configured + +### 0.4.1 +###### Features +- Update CloudFormation Specs to July 20th, 2018 +###### Fixes +- Fix an issue with Exclusive resource properties and RDS with Snapshot and Password + +### 0.4.0 +###### Features +- Update CloudFormation specs to July 16th, 2018 +- Support comma lists for regions, append rules, and ignore check parameters +- Added documentation explaining Resource Specification based rules +###### Fixes +- Fix a bunch of typos across many different rules +- Support DeepCopy with Template and custom String classes used for marking up templates +- Fix Rule [E3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3002) to support CommaDelimitedList when looking for List Parameters +- Fix core engine to check that something is a Dict instead of assuming it is + +### 0.3.5 +###### Features +- Update CloudFormation Specs to July 12th, 2018 +- Rule [E7012](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E7012) added to check the limits of attributes in a Mapping +- Rule [E2012](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2012) added to check maximum size of a parameter value +- Rule [E1003](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1003) added to check the maximum length of the template Description +- Guide created to help new users write new rules +###### Fixes +- Catch KeyError when trying to discover the line and column number of an error +- Update Lambda rules to support dotnet core +- Fix rule [E1017](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1017) so we unpack first element of select as a dict +- Fix rule [E1024](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1024) to support ImportValue and appropriately checking number for the last element + +### 0.3.3 +###### Features +- Support for Yaml C Parser when available. +- Catch rule processing errors and raise a lint error in their place. +- Add rules for the limit on Parameter, Mapping, Resource and Output names +- Add Rule [W3005](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W3005) to warn for when DependsOn is specified but not needed +- Add Rule [E2509](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2509) to check if Security Group Descriptions are properly configured +- Add `source_url` to rules so rule reference documentation can be provided +###### Fixes +- Fixed issues when Conditions had lists for values +- Fixed issue where underscore was allowed for AlphaNumeric names + +### 0.3.2 +###### Features +- Try/Catch added to rule processing so code failures in rules won't crash cfn-lint +- Parse YAML files using C parser when available. Greatly speeds up YAML parsing. +###### Fixes +- Template class updated to handle conditions where lists are in the true/false values +- Fix regex for checking Resource, Output, etc. names to not include underscore + +### 0.3.1 +###### Features +- Update rule [E3020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3020) to validate A recordsets +###### Fixes +- Require "aws-sam-translator" dependency be at least 1.6.0 +- Add support for wildcards in rule [E3013](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3013) - Support conditions in Lists for rule [E3002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3002) - Include filename when we run into Null and Duplicate values when parsing yaml +- Rule W2510 now allows for AllowedValues instead of just Min/MaxValue for compliance of Lambda MemorySize +- Rule [E2530](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2530) updated to checked AllowedValues for compliance of Lambda MemorySize + +### 0.3.0 +###### Features +- Serverless Transforms now handled by SAM libraries +- Add Rule [E2508](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2508): Add checks for IAM + - Managed Policies attached to IAM user, group or role can't be more than 10 + - An IAM user can be a member of no more than 10 groups + - There can only be 1 role in an instance profile + - AssumeRolePolicyDocument size is less than <2048 characters +- Add Rule [E1002](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1002): Check overall template size to make sure its below +- Add Rule [E3013](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3013): CloudFront aliases should contain valid domain names +- Add Rule [E3020](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3020): Check if all RecordSets are correctly configured + - Strings end and start with double quotes + - Size is less than 256 characters + - Record Types are within the specification +- Short hand parameter switches and no longer need --template +###### Fixes +- Don't report a Condition not being used if it is used by another Condition + +### 0.2.2 +###### Fixes +- Fixed issues with Yaml and Json parsing for complex strings in Python 2.7 +- Added eu-central-1 Availability Zones to acceptable AZ list +- Added nodejs8.10 to supported Lambda +- Added Version as an attribute for a Custom Resource +- Parseable output is now colon(:) delimited + +### 0.2.1 +###### Features +- Added AllowedValues for Cidr parameter checking Rule W2509 +- Add Rule [E2004](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E2004) to check Allowed values for Cidr parameters are a valid Cidr range +- Disable mapping Name checks [W7001](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#W7001) if dynamic mapping names are used (Ref, FindInMap) +- New Rule [E1026](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1026) to make sure Ref's in 'Conditions' are to parameters and not resources +- Updated CloudFormation specs to June 5th, 2018 +###### Fixes +- Fixed an issue with Rule [E1019](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E1019) not giving errors when there was a bad pseudo parameter +- Fixed an issue where conditions with Refs were validated as strings instead of Refs +- Fix crash errors when an empty yaml file is provided +- Updated condition functions to return the full object (Ref isn't translated while looking for AWS::NoValue) +- Support Map Type properties when doing PrimitiveType check [E3012](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3012) - Fix an issue when boolean values not being checked when using check_value + +### 0.2.0 +###### Features +- Standard cfn-lint Errors ([E0000](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E0000)) for null, duplicate, and parse errors +- Add a new check for CloudFormation limits +- Add a new check for Parameter, Resource, Output, and Mapping names +- Update specs to those released on May 25th, 2018 +- Strong type checking for property values result in Errors ([E3012](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#E3012)) +###### Fixes +- Transform logic updated to not add a Role if one is specified for a serverless function +- Fixed logic around Fn::If when the result is an object +- Fix conditions when checking property value structure + +### 0.1.0 +###### Features +- Update CloudFormation specs to include recent releases +- Add checks for duplicate resource names +- Add checks for null values in templates +- Add support in Circular Dependency checks to go multiple levels deep +- Add check for unused mappings +- Add check for unused and not found conditions +- Convert Errors to Warnings that don't cause a failure when implementing a template +###### Fixes +- Fix check for cfn-lint configurations in templates +- Fix Sub Functions checks failing on sub stacks or custom resources +- Fix Serverless Transforms not failing when trying to create multiple RestApiIds +- Fix TOX encoding issues with certain JSON files +- Update Lambda Memory size to 3008 +- Fix FindInMap failing when the first parameter is also FindInMap +- Fix key search function to appropriately respond to nested finds (FindInMap inside a FindInMap) + +### 0.0.10 +###### Features +- Capability to merge and modify the CloudFormation spec with provided JSON + - Allows for changing what properties are required + - Can change what resource types are allowed +- Remove warnings that were in error checks to keep errors focused on issues preventing success +- Improve circular dependency checks to go multiple levels deep +- Check null and duplicate values in JSON and YAML templates +###### Fixes +- Some primitive type properties were not getting checked +- Include support for Long as a number based check +- Improve get condition values to support more complex scenarios + +### 0.0.8 +###### Features +- Added a rule to check for only one resource property in a set +- Added a rule for more than one of resource properties in a set +- Added a rule for mutually exclusive resource properties + +###### Fixes +- Support parsing JSON files that have tabs +- Better error handling for when a property is a list instead of an object +- Error handling for when files can't be read or don't exist + +### 0.0.7 +###### Features +- Fix for supporting more parameter types when checking REFs to parameters for Security Groups + +### 0.0.6 +###### Features +- Exit code non zero on errors or warnings + +### 0.0.5 +###### Features +- Testing CloudFormation resources against the Resource Spec +- Test Functions against supported included functions +- Test overall CloudFormation structure +- Test Regionalization of a template against the Resource Spec +- Ability to add additional rules on parameter +- In depth checks of values around AWS::EC2::VPC, AWS::EC2::Subnet, and AWS::EC2::SecurityGroup diff --git a/testbed/aws-cloudformation__cfn-lint/CODE_OF_CONDUCT.md b/testbed/aws-cloudformation__cfn-lint/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..5b627cfa60b5313da2c7df81aab2340225c2329f --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/CODE_OF_CONDUCT.md @@ -0,0 +1,4 @@ +## Code of Conduct +This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). +For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact +opensource-codeofconduct@amazon.com with any additional questions or comments. diff --git a/testbed/aws-cloudformation__cfn-lint/CONTRIBUTING.md b/testbed/aws-cloudformation__cfn-lint/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..c0e2682464244687bc07d8e12a2a43fdbaa9742d --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/CONTRIBUTING.md @@ -0,0 +1,104 @@ +# Contributing Guidelines + +Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional +documentation, we greatly value feedback and contributions from our community. + +Please read through this document before submitting any issues or pull requests to ensure we have all the necessary +information to effectively respond to your bug report or contribution. + + +## Reporting Bugs/Feature Requests + +We welcome you to use the GitHub issue tracker to report bugs or suggest features. + +When filing an issue, please check [existing open](https://github.com/aws-cloudformation/cfn-python-lint/issues), or [recently closed](https://github.com/aws-cloudformation/cfn-python-lint/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already +reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: + +* A reproducible test case or series of steps +* The version of our code being used +* Any modifications you've made relevant to the bug +* Anything unusual about your environment or deployment + +## Development Environment + +1. You will need Python 3 >= 3.5. Verify which version you have by running `python --version`. + + > If you don't have it installed, download it [here](https://www.python.org/downloads/). When you do this, `pip` should be installed automatically. + +1. Install `cfn-lint` from source by forking the repository and then doing a developer install: + + ```bash + # fork the repository + git clone https://github.com//cfn-python-lint.git + cd cfn-python-lint + pip3 install -e . + ``` + +1. Run `pip3 show cfn-lint`. The `Location` printed should be the folder from the step above. +1. You should now be able to modify the source code and see the changes immediately by running any of the `cfn-lint` commands. (Note: run `pip3 install -e .` again to re-install changes). + +## Running the tests + +The unit tests (and `pylint` for linting the Python code) are processed by [`tox`](https://tox.readthedocs.io/en/latest/). The configuration file is [tox.ini](/tox.ini). + +Make sure Tox is installed and then run Tox by just calling it: + +```bash +# Install Tox +$ pip install tox + +# Run all tests (This command is also used when validating a Pull Request) +$ tox + +# Run a specific test suite +$ tox -e py37 # Run all unit tests against Python 3.7 +``` +Tox test suites available: +* **py37**: Unit tests (Python 3.7) +* **py38**: Unit tests (Python 3.8) +* **py39**: Unit tests (Python 3.9) +* **py310**: Unit tests (Python 3.10) +* **py311**: Unit tests (Python 3.11) +* **py312**: Unit tests (Python 3.12) +* **py313**: Unit tests (Python 3.13) +* **style**: Python syntax check + +## Contributing via Pull Requests +Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: + +1. You are working against the latest source on the *main* branch. +2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. +3. You open an issue to discuss any significant work - we would hate for your time to be wasted. + +To send us a pull request, please: + +1. Fork the repository. +2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. +3. Ensure local tests pass. +4. Commit to your fork using clear commit messages. +5. Send us a pull request, answering any default questions in the pull request interface. +6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. + +GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and +[creating a pull request](https://help.github.com/articles/creating-a-pull-request/). + + +## Finding contributions to work on +Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/aws-cloudformation/cfn-python-lint/labels/help%20wanted) issues is a great place to start. + + +## Code of Conduct +This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). +For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact +opensource-codeofconduct@amazon.com with any additional questions or comments. + + +## Security issue notifications +If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public GitHub issue. + + +## Licensing + +See the [LICENSE](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. + +We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. diff --git a/testbed/aws-cloudformation__cfn-lint/Dockerfile b/testbed/aws-cloudformation__cfn-lint/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..80aed9c41f1cf2d106d09d593fe2f8f28e1db480 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/Dockerfile @@ -0,0 +1,7 @@ +FROM public.ecr.aws/docker/library/python:3.13-alpine3.20 + +RUN pip install cfn-lint[full] +RUN pip install pydot + +ENTRYPOINT ["cfn-lint"] +CMD ["--help"] diff --git a/testbed/aws-cloudformation__cfn-lint/LICENSE b/testbed/aws-cloudformation__cfn-lint/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..fc06cc4fe49b44e11bec7337390c85c509bfb4d7 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/LICENSE @@ -0,0 +1,14 @@ +MIT No Attribution + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/testbed/aws-cloudformation__cfn-lint/MANIFEST.in b/testbed/aws-cloudformation__cfn-lint/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..f170155820ba33360282b3d4ef7dc8acbaaf224c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/MANIFEST.in @@ -0,0 +1,2 @@ +include README.md LICENSE +recursive-include test * diff --git a/testbed/aws-cloudformation__cfn-lint/NOTICE b/testbed/aws-cloudformation__cfn-lint/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..7511ba9c6df2785abaa9ad656e8e01a7c178ef3e --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/NOTICE @@ -0,0 +1,2 @@ +cfn-flip +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. diff --git a/testbed/aws-cloudformation__cfn-lint/README.md b/testbed/aws-cloudformation__cfn-lint/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9a2b598cd2eda74fe61deff1a0f4937f0b227e10 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/README.md @@ -0,0 +1,364 @@ +# AWS CloudFormation Linter + +[cfn-lint logo] + +[![Testing](https://github.com/aws-cloudformation/cfn-python-lint/actions/workflows/test.yaml/badge.svg?branch=main)](https://github.com/aws-cloudformation/cfn-python-lint/actions/workflows/test.yaml) +[![PyPI version](https://badge.fury.io/py/cfn-lint.svg)](https://badge.fury.io/py/cfn-lint) +[![PyPI downloads](https://pepy.tech/badge/cfn-lint/week)](https://pypistats.org/packages/cfn-lint) +[![PyPI downloads](https://pepy.tech/badge/cfn-lint/month)](https://pypistats.org/packages/cfn-lint) +[![codecov](https://codecov.io/gh/aws-cloudformation/cfn-lint/branch/main/graph/badge.svg)](https://codecov.io/gh/aws-cloudformation/cfn-python-lint) +[![Discord Shield](https://img.shields.io/discord/981586120448020580?logo=discord)](https://discord.gg/KENDm6DHCv) + +Validate AWS CloudFormation yaml/json templates against the [AWS CloudFormation resource provider schemas](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-type-schemas.html) and additional checks. Includes checking valid values for resource properties and best practices. + +### Warning + +This is an attempt to provide validation for AWS CloudFormation templates properties and +their values. For values things can get pretty complicated (mappings, joins, splits, +conditions, and nesting those functions inside each other) so it's a best effort to +validate those values but the promise is to not fail if we can't understand or translate +all the things that could be going on. + +## Contribute + +We encourage you to contribute to `cfn-lint`! Please check out the [Contributing Guidelines](https://github.com/aws-cloudformation/cfn-lint/blob/main/CONTRIBUTING.md) for more information on how to proceed. + +## Community + +Join us on Discord! Connect & interact with CloudFormation developers & +experts, find channels to discuss and get help for cfn-lint, CloudFormation registry, StackSets, +Guard and more: + +[![Join our Discord](https://discordapp.com/api/guilds/981586120448020580/widget.png?style=banner3)](https://discord.gg/9zpd7TTRwq) + +#### Serverless Application Model + +The Serverless Application Model (SAM) is supported by the linter. The template is +transformed using [AWS SAM](https://github.com/awslabs/serverless-application-model) before the linter processes the template. + +_To get information about the [SAM Transformation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-aws-serverless.html), run the linter with `--info`_ + +## Install + +Python 3.8+ is supported. + +### Pip + +`pip install cfn-lint`. If pip is not available, run +`python setup.py clean --all` then `python setup.py install`. + +#### Optional dependencies + +`cfn-lint` has optional dependencies based on certain features you may need. + +* `pip install cfn-lint[full]` for installing all the optional dependencies. This will install all the dependencies for graph, junit, and sarif. +* `pip install cfn-lint[graph]` for installing `pydot` to draw and output template graphs +* `pip install cfn-lint[junit]` for installing the packages to output the `junit` format +* `pip install cfn-lint[sarif]` for installing the packages to output the `sarif` format + + +### Homebrew (macOS) + +`brew install cfn-lint` + +### Docker + +In `cfn-lint` source tree: + +```shell +docker build --tag cfn-lint:latest . +``` + +In repository to be linted: + +```shell +docker run --rm -v `pwd`:/data cfn-lint:latest /data/template.yaml +``` + +### Editor Plugins + +There are IDE plugins available to get direct linter feedback from you favorite editor: + +- [Atom](https://atom.io/packages/atom-cfn-lint) +- [Emacs](https://www.emacswiki.org/emacs/CfnLint) +- NeoVim 0.2.0+/Vim 8 + - [ALE](https://github.com/w0rp/ale#supported-languages) + - [Coc](https://github.com/joenye/coc-cfn-lint) + - [Syntastic](https://github.com/speshak/vim-cfn) +- [Sublime](https://packagecontrol.io/packages/SublimeLinter-contrib-cloudformation) +- [Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=kddejong.vscode-cfn-lint) +- [IntelliJ IDEA](https://plugins.jetbrains.com/plugin/10973-cfn-lint) + +### [GitHub Action](https://github.com/marketplace/actions/cfn-lint-action) + +### [Online demo](https://github.com/PatMyron/cfn-lint-online) + +## Basic Usage + +- `cfn-lint template.yaml` +- `cfn-lint -t template.yaml` + +Multiple files can be linted by either specifying multiple specific files: + +- `cfn-lint template1.yaml template2.yaml` +- `cfn-lint -t template1.yaml template2.yaml` + +or by using wildcards (globbing): + +Lint all `yaml` files in `path`: + +- `cfn-lint path/*.yaml` + +Lint all `yaml` files in `path` and all subdirectories (recursive): + +- `cfn-lint path/**/*.yaml` + +_Note_: If using sh/bash/zsh, you must enable globbing. +(`shopt -s globstar` for sh/bash, `setopt extended_glob` for zsh). + +##### Exit Codes + +`cfn-lint` will return a non zero exit if there are any issues with your template. The value is dependent on the severity of the issues found. For each level of discovered error `cfn-lint` will use bitwise OR to determine the final exit code. This will result in these possibilities. + +- 0 is no issue was found +- 2 is an error +- 4 is a warning +- 6 is an error and a warning +- 8 is an informational +- 10 is an error and informational +- 12 is an warning and informational +- 14 is an error and a warning and an informational + +###### Configuring Exit Codes + +`cfn-lint` allows you to configure exit codes. You can provide the parameter `--non-zero-exit-code` with a value of `informational`, `warning`, `error`, or `none`. `cfn-lint` will determine the exit code based on the match severity being the value of the parameter `--non-zero-exit-code` and higher. The exit codes will remain the same as above. + +The order of severity is as follows: + +1. `informational` _default_ +1. `warning` +1. `error` +1. `none` _Exit code will always be 0 unless there is a syntax error_ + +##### Specifying the template as an input stream + +The template to be linted can also be passed using standard input: + +- `cat path/template.yaml | cfn-lint -` + +##### Specifying the template with other parameters + +- `cfn-lint -r us-east-1 ap-south-1 -- template.yaml` +- `cfn-lint -r us-east-1 ap-south-1 -t template.yaml` + +## Configuration + +### Command Line + +From a command prompt run `cfn-lint ` to run standard linting of the template. + +### Config File + +It will look for a configuration file in the following locations (by order of preference): + +- `.cfnlintrc`, `.cfnlintrc.yaml` or `.cfnlintrc.yml` in the current working directory +- `~/.cfnlintrc` for the home directory + +In that file you can specify settings from the parameter section below. + +Example: + +```yaml +templates: + - test/fixtures/templates/good/**/*.yaml +ignore_templates: + - codebuild.yaml +include_checks: + - I +custom_rules: custom_rules.txt +``` + +### Parameters + +Optional parameters: + +| Command Line | Metadata | Options | Description | +| -------------------------- | -------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| -h, --help | | | Get description of cfn-lint | +| -z, --custom-rules | | filename | Text file containing user-defined custom rules. See [here](#Custom-Rules) for more information | +| -t, --template | | filename | Alternative way to specify Template file path to the file that needs to be tested by cfn-lint | +| -f, --format | format | quiet, parseable, json, junit, pretty, sarif | Output format | +| -l, --list-rules | | | List all the rules | +| -r, --regions | regions | [REGIONS [REGIONS ...]], ALL_REGIONS | Test the template against many regions. [Supported regions](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-type-schemas.html) | +| -b, --ignore-bad-template | ignore_bad_template | | Ignores bad template errors | +| --ignore-templates | | IGNORE_TEMPLATES [IGNORE_TEMPLATES ...] | Ignore templates from being scanned | +| -a, --append-rules | append_rules | [RULESPATH [RULESPATH ...]] | Specify one or more rules paths using one or more --append-rules arguments. Each path can be either a directory containing python files, or an import path to a module. | +| -i, --ignore-checks | ignore_checks | [IGNORE_CHECKS [IGNORE_CHECKS ...]] | Only check rules whose ID do not match or prefix these values. Examples:
- A value of `W` will disable all warnings
- `W2` disables all Warnings for Parameter rules.
- `W2001` will disable rule `W2001` | +| -e, --include-experimental | include_experimental | | Whether rules that still in an experimental state should be included in the checks | +| -c, --include-checks | | INCLUDE_CHECKS [INCLUDE_CHECKS ...] | Include rules whose id match these values | +| -m, --mandatory-checks | | | Rules to check regardless of ignore configuration | +| --non-zero-exit-code | | informational (default), warning, error, none] | Exit code will be non zero from the specified rule class and higher | +| -x, --configure-rule | | CONFIGURE_RULES [CONFIGURE_RULES ...] | Provide configuration for a rule. Format RuleId:key=value. Example: E3012:strict=true | +| -D, --debug | | | Specify to enable debug logging. Debug logging outputs detailed information about rules processing, useful for debugging rules. | +| -I, --info | | | Specify to enable logging. Outputs additional information about the template processing. | +| -u, --update-specs | | | Update the [CloudFormation resource provider schemas](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-type-schemas.html). You may need sudo to run this. You will need internet access when running this command | +| -o, --override-spec | | filename | Spec-style file containing custom definitions. Can be used to override CloudFormation specifications. More info [here](#customize-specifications) | +| -g, --build-graph | | | Creates a file in the same directory as the template that models the template's resources in [DOT format]() | +| -s, --registry-schemas | | | one or more directories of [CloudFormation Registry](https://aws.amazon.com/blogs/aws/cloudformation-update-cli-third-party-resource-support-registry/) [Resource Schemas](https://github.com/aws-cloudformation/aws-cloudformation-resource-schema/) | +| -v, --version | | | Version of cfn-lint | + +### Info Rules + +To maintain backwards compatibility `info` rules are not included by default. To include these rules you will need to include `-c I` or `--include-checks I` + +### Metadata + +#### Template Based Metadata + +Inside the root level Metadata key you can configure cfn-lint using the supported parameters. + +```yaml +Metadata: + cfn-lint: + config: + regions: + - us-east-1 + - us-east-2 + ignore_checks: + - E2530 +``` + +#### Resource Based Metadata + +Inside a resources Metadata key you can configure cfn-lint to ignore checks. This will filter out failures for the resource in which the Metadata belongs. Keep in mind that [`AWS::Serverless` resources may lose metadata during the Serverless transform](https://github.com/awslabs/serverless-application-model/issues/450#issuecomment-643420308) + +```yaml +Resources: + myInstance: + Type: AWS::EC2::Instance + Metadata: + cfn-lint: + config: + ignore_checks: + - E3030 + Properties: + InstanceType: nt.x4superlarge + ImageId: ami-abc1234 +``` + +### Precedence + +cfn-lint applies configurations from several sources. The rules at lower levels are overridden by those at higher levels. + +1. cfnlintrc configurations +2. Template Metadata configurations +3. CLI parameters + +### Configure Rules + +Certain rules support configuration properties. You can configure these rules by using `configure_rules` parameter. + +From the command line the format is `RuleId:key=value`, for example: `E3012:strict=true`. +From the cfnlintrc or Metadata section the format is + +```yaml +Metadata: + cfn-lint: + config: + configure_rules: + RuleId: + key: value +``` + +The configurable rules have a non-empty Config entry in the table [here](docs/rules.md#rules-1). + +### Getting Started Guides + +There are [getting started guides](/docs/getting_started) available in the documentation section to help with integrating `cfn-lint` or creating rules. + +## Rules + +This linter checks the AWS CloudFormation template by processing a collection of Rules, where every rule handles a specific function check or validation of the template. + +This collection of rules can be extended with custom rules using the `--append-rules` argument. + +More information describing how rules are set up and an overview of all the Rules that are applied by this linter are documented [here](docs/rules.md). + +## Custom Rules + +The linter supports the creation of custom one-line rules which compare any resource with a property using pre-defined operators. These custom rules take the following format: + +``` + [Error Level] [Custom Error Message] +``` + +### Example + +A separate custom rule text file must be created. + +The example below validates `example_template.yml` does not use any EC2 instances of size `m4.16xlarge` + +_custom_rule.txt_ + +``` +AWS::EC2::Instance InstanceType NOT_EQUALS "m4.16xlarge" WARN "This is an expensive instance type, don't use it" +``` + +_example_template.yml_ + +```yaml +AWSTemplateFormatVersion: "2010-09-09" +Resources: + myInstance: + Type: AWS::EC2::Instance + Properties: + InstanceType: m4.16xlarge + ImageId: ami-asdfef +``` + +The custom rule can be added to the [configuration file](#Config-File) or ran as a [command line argument](#Parameters) + +The linter will produce the following output, running `cfn-lint example_template.yml -z custom_rules.txt`: + +``` +W9001 This is an expensive instance type, don't use it +mqtemplate.yml:6:17 +``` + +More information describing how custom rules are setup and an overview of all operators available is documented [here](docs/custom_rules.md). + +## Customize specifications + +The linter follows the [AWS CloudFormation resource provider schemas](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-type-schemas.html) by default. However, for your use case specific requirements might exist. For example, within your organisation it might be mandatory to use [Tagging](https://aws.amazon.com/answers/account-management/aws-tagging-strategies/). + +The linter provides the possibility to implement these customized specifications using the `--override-spec` argument. + +More information about how this feature works is documented [here](docs/customize_specifications.md) + +## pre-commit + +If you'd like cfn-lint to be run automatically when making changes to files in your Git repository, you can install [pre-commit](https://pre-commit.com/) and add the following text to your repositories' `.pre-commit-config.yaml`: + +```yaml +repos: + - repo: https://github.com/aws-cloudformation/cfn-lint + rev: v1.19.0 # The version of cfn-lint to use + hooks: + - id: cfn-lint + files: path/to/cfn/dir/.*\.(json|yml|yaml)$ +``` + +If you are using a `.cfnlintrc` and specifying the `templates` or `ignore_templates` we would recommend using the `.cfnlintrc` exlusively to determine which files should be scanned and then using: + +```yaml +repos: + - repo: https://github.com/aws-cloudformation/cfn-lint + rev: v1.19.0 # The version of cfn-lint to use + hooks: + - id: cfn-lint-rc +``` + +_Note: When mixing .cfnlintrc ignore_templates and files option in your .pre-commit-config.yaml cfn-lint may return a file not found error_ + +- If you exclude the `files:` line above, every json/yml/yaml file will be checked. +- You can see available cfn-lint versions on the [releases page](https://github.com/aws-cloudformation/cfn-python-lint/releases). diff --git a/testbed/aws-cloudformation__cfn-lint/custom_rules.txt b/testbed/aws-cloudformation__cfn-lint/custom_rules.txt new file mode 100644 index 0000000000000000000000000000000000000000..a0983d6d75ceaf93dbc9cf24a588fcafee252940 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/custom_rules.txt @@ -0,0 +1,3 @@ +#Comments can be made with a '#' symbol at the start of the line +#Syntax: +#Example: AWS::EC2::Instance InstanceType EQUALS "p3.2xlarge" diff --git a/testbed/aws-cloudformation__cfn-lint/pyproject.toml b/testbed/aws-cloudformation__cfn-lint/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..32faba54428380be76a3e9b33ec08a84d348d1d0 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/pyproject.toml @@ -0,0 +1,211 @@ +[build-system] +requires = [ + "setuptools >= 65.5.1", +] +build-backend = "setuptools.build_meta" + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.setuptools.dynamic] +version = {attr = "cfnlint.version.__version__"} +readme = {file = ["README.md"], content-type = "text/markdown"} + +[project] +name = "cfn-lint" +description = "Checks CloudFormation templates for practices and behaviour that could potentially be improved" +requires-python = ">=3.8" +license = {text = "MIT no attribution"} +keywords = ["aws", "cloudformation", "lint"] +authors = [ + {email = "kddejong@amazon.com"}, + {name = "Kevin DeJong"}, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Natural Language :: English", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +dynamic = ["version", "readme"] +dependencies = [ + "pyyaml>5.4", + "aws-sam-translator>=1.91.0", + "jsonpatch", + "networkx>=2.4,<4", + "sympy>=1.0.0", + "regex", + "typing_extensions", +] + +[project.optional-dependencies] +graph = [ + "pydot" +] +junit = [ + "junit-xml~=1.9" +] +sarif = [ + "jschema_to_python~=1.2.3", + "sarif-om~=1.0.4", +] +full = [ + "junit-xml~=1.9", + "jschema_to_python~=1.2.3", + "sarif-om~=1.0.4", + "pydot" +] + +[project.scripts] +cfn-lint = "cfnlint.runner:main" + +[tool.setuptools.package-data] +cfnlint = ["data/**/*.json"] + +[project.urls] +Homepage = "https://github.com/aws-cloudformation/cfn-lint" +Documentation = "https://github.com/aws-cloudformation/cfn-lint" +Issues = "https://github.com/aws-cloudformation/cfn-lint/issues" +Changelog = "https://github.com/aws-cloudformation/cfn-lint/blob/main/CHANGELOG.md" +Source = "https://github.com/aws-cloudformation/cfn-lint" + +[tool.isort] +profile = "black" + +[tool.black] +skip-string-normalization = false +line-length = 88 + +[tool.bandit] +skips = ["B101", "B303", "B310", "B110", "B112", "B324", "B404", "B603", "B607"] +exclude_dirs = ["tests", "scripts"] + +[tool.ruff] +# Enable pycodestyle (`E`) and Pyflakes (`F`) codes by default. +lint.select = ["E", "F"] +lint.ignore = [] + +# Allow autofix for all enabled rules (when `--fix`) is provided. +lint.fixable = ["A", "B", "C", "D", "E", "F", "G", "I", "N", "Q", "S", "T", "W", "ANN", "ARG", "BLE", "COM", "DJ", "DTZ", "EM", "ERA", "EXE", "FBT", "ICN", "INP", "ISC", "NPY", "PD", "PGH", "PIE", "PL", "PT", "PTH", "PYI", "RET", "RSE", "RUF", "SIM", "SLF", "TCH", "TID", "TRY", "UP", "YTT"] +lint.unfixable = [] + +# Exclude a variety of commonly ignored directories. +exclude = [ + ".bzr", + ".direnv", + ".eggs", + ".git", + ".git-rewrite", + ".hg", + ".mypy_cache", + ".nox", + ".pants.d", + ".pytype", + ".ruff_cache", + ".svn", + ".tox", + ".venv", + "__pypackages__", + "_build", + "buck-out", + "build", + "dist", + "node_modules", + "venv", +] +# Same as Black. +line-length = 88 + +[tool.ruff.lint.per-file-ignores] +"__init__.py" = ["F401"] + +[tool.pytest.ini_options] +addopts = [ + "-m not data" +] +markers = [ + "data: marks tests as slow (deselect with '-m \"not data\"')", +] +testpaths = [ + "test", +] + +[tool.coverage.run] +branch = true +source = [ + "src/cfnlint" +] + +[tool.coverage.report] +skip_empty = true +skip_covered = true +show_missing = true +sort = "Cover" +exclude_lines = [ + "pragma: no cover", + "if TYPE_CHECKING:" +] + +[tool.mypy] +python_version = "3.10" +warn_return_any = true +warn_unused_configs = true +files = [ + "src/cfnlint/**/*.py" +] +exclude = [ + "src/cfnlint/data/" +] + +# Per-module options: +[[tool.mypy.overrides]] +module = "networkx.*" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "pydot.*" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "pygraphviz.*" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "importlib_resources.*" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "samtranslator.*" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "sarif_om.*" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "jschema_to_python.*" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "junit_xml.*" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "jsonpatch.*" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "urllib2.*" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "json.*" +ignore_missing_imports = true diff --git a/testbed/aws-cloudformation__cfn-lint/setup.cfg b/testbed/aws-cloudformation__cfn-lint/setup.cfg new file mode 100644 index 0000000000000000000000000000000000000000..08aedd7e61b9921f0a7844c3826bda5c611bc5e2 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/setup.cfg @@ -0,0 +1,2 @@ +[metadata] +description_file = README.md diff --git a/testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-instance.yaml b/testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-instance.yaml new file mode 100644 index 0000000000000000000000000000000000000000..da3af865ae3fbae0508524eef0efbd3bdbb64e95 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-instance.yaml @@ -0,0 +1,20 @@ +Resources: + NetworkInterface: + Type: AWS::EC2::NetworkInterface + Properties: + Description: foobar + SourceDestCheck: false + SubnetId: subnet-0abc1def2345a678b + Instance: + Type: AWS::EC2::Instance + Properties: + ImageId: ami-abcdefgh + InstanceType: t2.micro + NetworkInterfaces: + - AssociateCarrierIpAddress: true + AssociatePublicIpAddress: true + DeviceIndex: "0" + NetworkInterfaceId: !Ref NetworkInterface + Tags: + - Key: foo + Value: bar diff --git a/testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-launchtemplate.yaml b/testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-launchtemplate.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fcd488fc3cf45a11169e86db990c111a8a130b1d --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-launchtemplate.yaml @@ -0,0 +1,14 @@ +Resources: + LaunchTemplate: + Type: AWS::EC2::LaunchTemplate + Properties: + LaunchTemplateData: + ImageId: ami-abcdefgh + InstanceType: t2.micro + UserData: !Base64 "#!/bin/bash\necho 'Hello World' > /var/www/html/index.html" + NetworkInterfaces: + - AssociateCarrierIpAddress: true + AssociatePublicIpAddress: true + DeviceIndex: 0 + NetworkInterfaceId: !Ref NetworkInterface + LaunchTemplateName: MyLaunchTemplate diff --git a/testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-networkinterface.yaml b/testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-networkinterface.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c7f3faa3cb5ed117e459552e7f8caca8cbfe987e --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-networkinterface.yaml @@ -0,0 +1,17 @@ +Parameters: + SubnetId: + Type: AWS::EC2::Subnet::Id + SecurityGroupId: + Type: AWS::EC2::SecurityGroup::Id +Resources: + NetworkInterface: + Type: AWS::EC2::NetworkInterface + Properties: + Description: "a network interface" + GroupSet: + - !Ref SecurityGroupId + SourceDestCheck: false + SubnetId: !Ref SubnetId + Ipv6Addresses: + - Ipv6Address: abc + Ipv6AddressCount: 1 diff --git a/testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-subnet.yaml b/testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-subnet.yaml new file mode 100644 index 0000000000000000000000000000000000000000..612fd56e647f9741f8ae2e718d15eef6b5de3221 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-subnet.yaml @@ -0,0 +1,19 @@ +Parameters: + Vpc: + Type: AWS::EC2::VPC::Id +Resources: + Subnet1: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref Vpc + CidrBlock: 10.0.0.0/24 + Ipv4NetmaskLength: 10 + Subnet2: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref Vpc + Subnet3: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref Vpc + Ipv4IpamPoolId: test diff --git a/testbed/aws-cloudformation__cfn-lint/test/integration/jsonschema/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/integration/jsonschema/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-cloudformation__cfn-lint/test/integration/jsonschema/test_validator_cfn.py b/testbed/aws-cloudformation__cfn-lint/test/integration/jsonschema/test_validator_cfn.py new file mode 100644 index 0000000000000000000000000000000000000000..a89b43b8687e4402d8586b622cc29ee4e964ace1 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/integration/jsonschema/test_validator_cfn.py @@ -0,0 +1,366 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from __future__ import annotations + +import json +import unittest +from collections import deque +from typing import List + +import jsonpatch + +from cfnlint.decode import decode_str +from cfnlint.helpers import FUNCTIONS +from cfnlint.jsonschema import CfnTemplateValidator, ValidationError +from cfnlint.template import Template + + +def build_template(patch: jsonpatch.JsonPatch | None) -> Template: + """ + Build a template object from a dict + """ + template_obj = { + "AWSTemplateFormatVersion": "2010-09-09", + "Conditions": { + "IsUsEast1": {"Fn::Equals": ["true", {"Ref": "AWS::Region"}]}, + "IsNotUsEast1": {"Fn::Not": [{"Condition": "IsUsEast1"}]}, + }, + "Resources": { + "MyResource": { + "Type": "AWS::Test::Type", + "Properties": { + "Name": "Name", + "Tags": [ + {"Key": "Name", "Value": "Value"}, + ], + }, + } + }, + } + + if patch is not None: + jsonpatch.apply_patch(template_obj, patch, True) + + template, _ = decode_str(json.dumps(template_obj)) + if template: + return Template("", template, regions=["us-east-1"]) + + raise Exception("Template is invalid") + + +def build_schema(patch: jsonpatch.JsonPatch | None): + schema = { + "properties": { + "Name": { + "type": "string", + }, + "Tags": { + "type": "array", + "items": { + "type": "object", + "properties": { + "Key": {"type": "string"}, + "Value": {"type": "string"}, + }, + }, + }, + }, + "type": "object", + } + + if patch is not None: + jsonpatch.apply_patch(schema, patch, True) + + return schema + + +class TestValidatorCfnConditions(unittest.TestCase): + """ + Integration testing of the CfnTemplateValidator class + with a Template that allows us to exhaust scenario + """ + + def run_test( + self, + template_patches: jsonpatch.JsonPatch, + schema_patches: jsonpatch.JsonPatch, + expected_errs: List[ValidationError], + ): + """ + Run the test + """ + cfn = build_template(template_patches) + schema = build_schema(schema_patches) + + props = ( + cfn.template.get("Resources", {}) + .get("MyResource", {}) + .get("Properties", {}) + ) + + context = cfn.context.evolve(functions=FUNCTIONS) + validator = CfnTemplateValidator(schema=schema, cfn=cfn, context=context) + errs = list(validator.iter_errors(props)) + + self.assertEqual(len(errs), len(expected_errs), f"Received: {errs!r}") + for i, err in enumerate(errs): + self.assertEqual(expected_errs[i].message, err.message) + self.assertEqual(expected_errs[i].path, err.path) + self.assertEqual(expected_errs[i].validator, err.validator) + self.assertEqual(expected_errs[i].validator_value, err.validator_value) + + def test_required(self): + schema_patch = jsonpatch.JsonPatch( + patch=[{"op": "add", "path": "/required", "value": ["Name"]}], + ) + self.run_test( + template_patches=None, + schema_patches=schema_patch, + expected_errs=[], + ) + + self.run_test( + template_patches=jsonpatch.JsonPatch( + patch=[ + {"op": "remove", "path": "/Resources/MyResource/Properties/Name"} + ], + ), + schema_patches=schema_patch, + expected_errs=[ + ValidationError( + "'Name' is a required property", + validator="required", + validator_value=["Name"], + ), + ], + ) + + self.run_test( + template_patches=jsonpatch.JsonPatch( + patch=[ + { + "op": "replace", + "path": "/Resources/MyResource/Properties/Name", + "value": { + "Fn::If": [ + "IsUsEast1", + "Name", + {"Ref": "AWS::NoValue"}, + ] + }, + } + ], + ), + schema_patches=schema_patch, + expected_errs=[ + ValidationError( + "'Name' is a required property", + validator="required", + validator_value=["Name"], + ), + ], + ) + + def test_unique_items(self): + schema_patch = jsonpatch.JsonPatch( + [ + {"op": "add", "path": "/properties/Tags/uniqueItems", "value": True}, + ] + ) + self.run_test( + template_patches=None, + schema_patches=schema_patch, + expected_errs=[], + ) + + self.run_test( + template_patches=jsonpatch.JsonPatch( + [ + { + "op": "add", + "path": "/Resources/MyResource/Properties/Tags/-", + "value": {"Key": "Name", "Value": "Value"}, + }, + ] + ), + schema_patches=schema_patch, + expected_errs=[ + ValidationError( + message=( + "[{'Key': 'Name', 'Value': 'Value'}, " + "{'Key': 'Name', 'Value': 'Value'}] has " + "non-unique elements" + ), + path=deque(["Tags"]), + validator="uniqueItems", + validator_value=True, + ), + ], + ) + + self.run_test( + template_patches=jsonpatch.JsonPatch( + [ + { + "op": "add", + "path": "/Resources/MyResource/Properties/Tags/-", + "value": { + "Fn::If": [ + "IsUsEast1", + {"Key": "Name", "Value": "Value"}, + {"Key": "Foo", "Value": "Bar"}, + ] + }, + }, + ] + ), + schema_patches=schema_patch, + expected_errs=[ + ValidationError( + message=( + "[{'Key': 'Name', 'Value': 'Value'}, " + "{'Key': 'Name', 'Value': 'Value'}] has " + "non-unique elements" + ), + path=deque(["Tags"]), + validator="uniqueItems", + validator_value=True, + ), + ], + ) + + self.run_test( + template_patches=jsonpatch.JsonPatch( + [ + { + "op": "replace", + "path": "/Resources/MyResource/Properties/Tags", + "value": [ + { + "Fn::If": [ + "IsUsEast1", + {"Key": "Name", "Value": "Value"}, + {"Ref": "AWS::NoValue"}, + ], + }, + { + "Fn::If": [ + "IsUsEast1", + {"Ref": "AWS::NoValue"}, + {"Key": "Name", "Value": "Value"}, + ], + }, + ], + }, + ] + ), + schema_patches=schema_patch, + expected_errs=[], + ) + + self.run_test( + template_patches=jsonpatch.JsonPatch( + [ + { + "op": "replace", + "path": "/Resources/MyResource/Properties/Tags", + "value": [ + { + "Fn::If": [ + "IsUsEast1", + {"Key": "Name", "Value": "Value"}, + {"Ref": "AWS::NoValue"}, + ], + }, + { + "Fn::If": [ + "IsNotUsEast1", + {"Ref": "AWS::NoValue"}, + {"Key": "Name", "Value": "Value"}, + ], + }, + ], + }, + ] + ), + schema_patches=schema_patch, + expected_errs=[ + ValidationError( + message=( + "[{'Key': 'Name', 'Value': 'Value'}, " + "{'Key': 'Name', 'Value': 'Value'}] has " + "non-unique elements" + ), + path=deque(["Tags"]), + validator="uniqueItems", + validator_value=True, + ), + ], + ) + + def test_dependencies(self): + schema_patch = jsonpatch.JsonPatch( + [ + {"op": "add", "path": "/dependencies", "value": {"Name": ["Tags"]}}, + ] + ) + self.run_test( + template_patches=None, + schema_patches=schema_patch, + expected_errs=[], + ) + + self.run_test( + template_patches=jsonpatch.JsonPatch( + [ + {"op": "remove", "path": "/Resources/MyResource/Properties/Tags"}, + ] + ), + schema_patches=schema_patch, + expected_errs=[ + ValidationError( + message="'Tags' is a dependency of 'Name'", + path=deque([]), + validator="dependencies", + validator_value={"Name": ["Tags"]}, + ), + ], + ) + + self.run_test( + template_patches=jsonpatch.JsonPatch( + [ + { + "op": "replace", + "path": "/Resources/MyResource/Properties/Tags", + "value": { + "Fn::If": [ + "IsUsEast1", + {"Ref": "AWS::NoValue"}, + [ + { + "Fn::If": [ + "IsUsEast1", + {"Ref": "AWS::NoValue"}, + {"Key": "Name", "Value": "Value"}, + ] + }, + ], + ] + }, + }, + ] + ), + schema_patches=schema_patch, + expected_errs=[ + ValidationError( + message="'Tags' is a dependency of 'Name'", + path=deque([]), + validator="dependencies", + validator_value={"Name": ["Tags"]}, + ), + ], + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/integration/rules/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/integration/rules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-cloudformation__cfn-lint/test/integration/rules/test_rules.py b/testbed/aws-cloudformation__cfn-lint/test/integration/rules/test_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..935ce73f9dece914d08ba5a20d15d711edafd54d --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/integration/rules/test_rules.py @@ -0,0 +1,32 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from __future__ import annotations + +import pathlib + +from cfnlint.helpers import load_plugins + + +def test_rule_descriptions(): + root_dir = pathlib.Path(__file__).parent.parent.parent.parent / "src/cfnlint/rules" + rules = load_plugins( + str(root_dir), + ) + + descriptions = set() + shortdesc = set() + + for rule in rules: + if not rule.id: + continue + assert ( + rule.description not in descriptions + ), f"Duplicate description {rule.description!r}" + assert ( + rule.shortdesc not in shortdesc + ), f"Duplicate shortdesc {rule.shortdesc!r}" + descriptions.add(rule.description) + shortdesc.add(rule.shortdesc) diff --git a/testbed/aws-cloudformation__cfn-lint/test/integration/test_good_templates.py b/testbed/aws-cloudformation__cfn-lint/test/integration/test_good_templates.py new file mode 100644 index 0000000000000000000000000000000000000000..e799d5d8d13f0c9aad525b40cd8aa53644b7c480 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/integration/test_good_templates.py @@ -0,0 +1,228 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from pathlib import Path +from test.integration import BaseCliTestCase + +from cfnlint import ConfigMixIn + + +class TestQuickStartTemplates(BaseCliTestCase): + """Test QuickStart Templates Parsing""" + + # ruff: noqa: E501 + scenarios = [ + { + "filename": "test/fixtures/templates/good/generic.yaml", + "results": [], + "exit_code": 0, + }, + { + "filename": "test/fixtures/templates/good/minimal.yaml", + "results": [], + "exit_code": 0, + }, + { + "filename": "test/fixtures/templates/good/transform.yaml", + "results": [], + "exit_code": 0, + }, + { + "filename": "test/fixtures/templates/issues/sam_w_conditions.yaml", + "results": [], + "exit_code": 0, + }, + { + "filename": ( + "test/fixtures/templates/bad/transform_serverless_template.yaml" + ), + "results": [ + { + "Filename": "test/fixtures/templates/bad/transform_serverless_template.yaml", + "Id": "9e05773a-b0d0-f157-2955-596d9bd54749", + "Level": "Error", + "Location": { + "End": {"ColumnNumber": 2, "LineNumber": 1}, + "Path": None, + "Start": {"ColumnNumber": 1, "LineNumber": 1}, + }, + "Message": "Error transforming template: Resource with id [myFunctionMyTimer] is invalid. Missing required property 'Schedule'.", + "ParentId": None, + "Rule": { + "Description": "Errors found when performing transformation on the template", + "Id": "E0001", + "ShortDescription": "Error found when transforming the template", + "Source": "https://github.com/aws-cloudformation/cfn-lint", + }, + }, + { + "Filename": "test/fixtures/templates/bad/transform_serverless_template.yaml", + "Id": "fd751fa3-7d1f-e194-7108-eb08352814c8", + "Level": "Error", + "Location": { + "End": {"ColumnNumber": 2, "LineNumber": 1}, + "Path": None, + "Start": {"ColumnNumber": 1, "LineNumber": 1}, + }, + "Message": "Error transforming template: Resource with id [ExampleLayer] is invalid. Missing required property 'ContentUri'.", + "ParentId": None, + "Rule": { + "Description": "Errors found when performing transformation on the template", + "Id": "E0001", + "ShortDescription": "Error found when transforming the template", + "Source": "https://github.com/aws-cloudformation/cfn-lint", + }, + }, + { + "Filename": "test/fixtures/templates/bad/transform_serverless_template.yaml", + "Id": "74181426-e865-10eb-96fd-908dfd30a358", + "Level": "Error", + "Location": { + "End": {"ColumnNumber": 2, "LineNumber": 1}, + "Path": None, + "Start": {"ColumnNumber": 1, "LineNumber": 1}, + }, + "Message": "Error transforming template: Resource with id [AppName] is invalid. Resource is missing the required [Location] property.", + "ParentId": None, + "Rule": { + "Description": "Errors found when performing transformation on the template", + "Id": "E0001", + "ShortDescription": "Error found when transforming the template", + "Source": "https://github.com/aws-cloudformation/cfn-lint", + }, + }, + ], + "exit_code": 2, + }, + { + "filename": "test/fixtures/templates/good/conditions.yaml", + "results": [], + "exit_code": 0, + }, + { + "filename": "test/fixtures/templates/good/resources_codepipeline.yaml", + "results": [], + "exit_code": 0, + }, + { + "filename": "test/fixtures/templates/good/resources_cognito_userpool_tag_is_string_map.yaml", + "results": [], + "exit_code": 0, + }, + { + "filename": "test/fixtures/templates/bad/resources_cognito_userpool_tag_is_list.yaml", + "results": [ + { + "Filename": str( + Path( + "test/fixtures/templates/bad/resources_cognito_userpool_tag_is_list.yaml" + ) + ), + "Id": "3732b0a0-6d44-72af-860a-88e5f8ca790c", + "Level": "Error", + "Location": { + "Start": {"ColumnNumber": 7, "LineNumber": 16}, + "End": {"ColumnNumber": 19, "LineNumber": 16}, + "Path": [ + "Resources", + "MyCognitoUserPool", + "Properties", + "UserPoolTags", + ], + }, + "Message": ( + "[{'Key': 'Key1', 'Value': 'Value1'}, {'Key': 'Key2', 'Value':" + " 'Value2'}] is not of type 'object'" + ), + "ParentId": None, + "Rule": { + "Description": ( + "Checks resource property values with Primitive Types for" + " values that match those types." + ), + "Id": "E3012", + "ShortDescription": "Check resource properties values", + "Source": "https://github.com/aws-cloudformation/cfn-lint/blob/main/docs/cfn-schema-specification.md#type", + }, + } + ], + "exit_code": 2, + }, + { + "filename": "test/fixtures/templates/good/transform_serverless_api.yaml", + "results": [], + "exit_code": 0, + }, + { + "filename": ( + "test/fixtures/templates/good/transform_serverless_function.yaml" + ), + "results": [], + "exit_code": 0, + }, + { + "filename": ( + "test/fixtures/templates/good/transform_serverless_globals.yaml" + ), + "results": [ + { + "Filename": str( + Path( + "test/fixtures/templates/good/transform_serverless_globals.yaml" + ) + ), + "Id": "f0f6c586-81bc-9182-de02-659a3a1a5b2c", + "Level": "Error", + "Location": { + "End": {"ColumnNumber": 13, "LineNumber": 10}, + "Path": ["Resources", "myFunction", "Properties", "Runtime"], + "Start": {"ColumnNumber": 3, "LineNumber": 10}, + }, + "Message": "Runtime 'nodejs6.10' was deprecated on '2019-08-12'. Creation was disabled on '2019-08-12' and update on '2019-08-12'. Please consider updating to 'nodejs20.x'", + "ParentId": None, + "Rule": { + "Description": ( + "Check if an EOL Lambda Runtime is specified and you cannot update the function" + ), + "Id": "E2533", + "ShortDescription": ( + "Check if Lambda Function Runtimes are updatable" + ), + "Source": "https://docs.aws.amazon.com/lambda/latest/dg/runtime-support-policy.html", + }, + } + ], + "exit_code": 2, + }, + { + "filename": "test/fixtures/templates/good/transform/list_transform.yaml", + "results": [], + "exit_code": 0, + }, + { + "filename": ( + "test/fixtures/templates/good/transform/list_transform_many.yaml" + ), + "results": [], + "exit_code": 0, + }, + { + "filename": ( + "test/fixtures/templates/good/transform/list_transform_not_sam.yaml" + ), + "results": [], + "exit_code": 0, + }, + ] + + def test_templates(self): + """Test Successful JSON Parsing""" + self.run_scenarios() + + def test_module_integration(self): + """Test same templates using integration approach""" + self.run_module_integration_scenarios( + ConfigMixIn([], include_checks=["W", "E"]) + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/integration/test_integration_templates.py b/testbed/aws-cloudformation__cfn-lint/test/integration/test_integration_templates.py new file mode 100644 index 0000000000000000000000000000000000000000..4b92d0d4a14af33cbbffc94cbfa4dfb3aad02f8f --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/integration/test_integration_templates.py @@ -0,0 +1,104 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.integration import BaseCliTestCase + +from cfnlint import ConfigMixIn + + +class TestQuickStartTemplates(BaseCliTestCase): + """Test QuickStart Templates Parsing""" + + scenarios = [ + { + "filename": ( + "test/fixtures/templates/integration" + "/resources-cloudformation-init.yaml" + ), + "results_filename": ( + "test/fixtures/results/integration/" + "resources-cloudformation-init.json" + ), + "exit_code": 0, + }, + { + "filename": "test/fixtures/templates/integration/dynamic-references.yaml", + "results_filename": ( + "test/fixtures/results/integration" "/dynamic-references.json" + ), + "exit_code": 2, + }, + { + "filename": "test/fixtures/templates/integration/ref-no-value.yaml", + "results_filename": ("test/fixtures/results/integration/ref-no-value.json"), + "exit_code": 2, + }, + { + "filename": "test/fixtures/templates/integration/metdata.yaml", + "results_filename": ("test/fixtures/results/integration/metadata.json"), + "exit_code": 4, + }, + { + "filename": ("test/fixtures/templates/integration/availability-zones.yaml"), + "results_filename": ( + "test/fixtures/results/integration/availability-zones.json" + ), + "exit_code": 2, + }, + { + "filename": ("test/fixtures/templates/integration/getatt-types.yaml"), + "results_filename": ("test/fixtures/results/integration/getatt-types.json"), + "exit_code": 10, + }, + { + "filename": ( + "test/fixtures/templates/integration/aws-ec2-networkinterface.yaml" + ), + "results_filename": ( + "test/fixtures/results/integration/aws-ec2-networkinterface.json" + ), + "exit_code": 2, + }, + { + "filename": ("test/fixtures/templates/integration/aws-ec2-instance.yaml"), + "results_filename": ( + "test/fixtures/results/integration/aws-ec2-instance.json" + ), + "exit_code": 2, + }, + { + "filename": ( + "test/fixtures/templates/integration/aws-ec2-launchtemplate.yaml" + ), + "results_filename": ( + "test/fixtures/results/integration/aws-ec2-launchtemplate.json" + ), + "exit_code": 2, + }, + { + "filename": ("test/fixtures/templates/integration/aws-ec2-subnet.yaml"), + "results_filename": ( + "test/fixtures/results/integration/aws-ec2-subnet.json" + ), + "exit_code": 2, + }, + { + "filename": ("test/fixtures/templates/integration/aws-dynamodb-table.yaml"), + "results_filename": ( + "test/fixtures/results/integration/aws-dynamodb-table.json" + ), + "exit_code": 2, + }, + ] + + def test_templates(self): + """Test same templates using integration approach""" + self.run_module_integration_scenarios( + ConfigMixIn( + [], + include_checks=["I"], + include_experimental=True, + ) + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/integration/test_patches.py b/testbed/aws-cloudformation__cfn-lint/test/integration/test_patches.py new file mode 100644 index 0000000000000000000000000000000000000000..4c14f2ac9e19ab3345959d071d34e8a262bfe258 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/integration/test_patches.py @@ -0,0 +1,28 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import json +import os +from test.integration import BaseCliTestCase + +from jsonpatch import InvalidJsonPatch, JsonPatch + + +class TestPatches(BaseCliTestCase): + """Test Patches""" + + def test_patches(self): + """Test ignoring certain rules""" + for root, _, files in os.walk( + "src/cfnlint/data/ExtendedProviderSchemas", topdown=True + ): + for name in files: + if name.endswith(".json"): + with open(os.path.join(root, name)) as fh: + patches = json.load(fh) + try: + JsonPatch(patches) + except InvalidJsonPatch: + raise Exception(f"Invalid patch: {name}") diff --git a/testbed/aws-cloudformation__cfn-lint/test/integration/test_quickstart_templates_non_strict.py b/testbed/aws-cloudformation__cfn-lint/test/integration/test_quickstart_templates_non_strict.py new file mode 100644 index 0000000000000000000000000000000000000000..a01b45dd395837d7622089ce8be77a540acf9761 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/integration/test_quickstart_templates_non_strict.py @@ -0,0 +1,71 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.integration import BaseCliTestCase + +from cfnlint import ConfigMixIn + + +class TestQuickStartTemplates(BaseCliTestCase): + """Test QuickStart Templates Parsing""" + + scenarios = [ + { + "filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", + "results_filename": ( + "test/fixtures/results/quickstart/non_strict/nist_high_main.json" + ), + "exit_code": 14, + }, + { + "filename": "test/fixtures/templates/quickstart/nist_application.yaml", + "results_filename": ( + "test/fixtures/results/quickstart/non_strict/nist_application.json" + ), + "exit_code": 14, + }, + { + "filename": "test/fixtures/templates/quickstart/openshift.yaml", + "results_filename": ( + "test/fixtures/results/quickstart/non_strict/openshift.json" + ), + "exit_code": 12, + }, + { + "filename": "test/fixtures/templates/quickstart/cis_benchmark.yaml", + "results_filename": ( + "test/fixtures/results/quickstart/non_strict/cis_benchmark.json" + ), + "exit_code": 4, + }, + ] + + def test_templates(self): + """Test Successful JSON Parsing""" + self.maxDiff = None + self.run_scenarios( + [ + "--include-checks", + "I", + "--include-experimental", + "--configure-rule", + "E3012:strict=false", + ] + ) + + def test_module_integration(self): + """Test same templates using integration approach""" + self.run_module_integration_scenarios( + ConfigMixIn( + [], + include_checks=["I"], + configure_rules={ + "E3012": { + "strict": False, + } + }, + include_experimental=True, + ) + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/integration/test_schema_files.py b/testbed/aws-cloudformation__cfn-lint/test/integration/test_schema_files.py new file mode 100644 index 0000000000000000000000000000000000000000..57e14d3ddfa0f1ec3e9490cc24dcba76bfa58d57 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/integration/test_schema_files.py @@ -0,0 +1,282 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from __future__ import annotations + +import fnmatch +import json +import os +import pathlib +from typing import Any, List +from unittest import TestCase + +import pytest +import regex as re + +import cfnlint +from cfnlint.helpers import REGIONS, ensure_list, load_plugins, load_resource +from cfnlint.jsonschema import StandardValidator, ValidationError +from cfnlint.schema.resolver import RefResolutionError, RefResolver + + +@pytest.mark.data +class TestSchemaFiles(TestCase): + """Test schema files""" + + _found_keywords: List[str] = [ + "*", + "Conditions", + "Description", + "Mappings", + "Metadata", + "Metadata/AWS::CloudFormation::Interface", + "Metadata/cfn-lint", + "Outputs", + "Outputs/*", + "Outputs/*/Condition", + "Outputs/*/Export/Name", + "Outputs/*/Value", + "Parameters", + "Parameters/*", + "Resources", + "Resources/*", + "Resources/*/Condition", + "Resources/*/CreationPolicy", + "Resources/*/DeletionPolicy", + "Resources/*/DependsOn", + "Resources/*/DependsOn/*", + "Resources/*/Metadata", + "Resources/*/Metadata/AWS::CloudFormation::Init", + "Resources/*/Type", + "Resources/*/UpdatePolicy", + "Resources/*/UpdateReplacePolicy", + "Rules", + "Rules/*/Assertions/*/Assert", + "Rules/*/RuleCondition", + "Transform", + ] + + def setUp(self) -> None: + schema_path = os.path.join(os.path.dirname(cfnlint.__file__), "data", "schemas") + self.paths = { + "extensions": os.path.join(schema_path, "extensions"), + "providers": os.path.join(schema_path, "providers"), + "other": os.path.join(schema_path, "other"), + "fixtures": os.path.join( + os.path.dirname(__file__), + "..", + "fixtures", + "schemas", + "providers", + ), + } + filename = os.path.join( + self.paths["fixtures"], "..", "json_schema", "draft7.json" + ) + with open(filename, "r") as fh: + d = json.load(fh) + self.schema_draft7 = d + + super().setUp() + + def get_files(self, dir): + for dirpath, _, filenames in os.walk(dir): + for filename in fnmatch.filter(filenames, "*.json"): + yield dirpath, filename + + def pattern(self, validator, patrn, instance, schema): + try: + re.compile(patrn) + except Exception: + yield ValidationError(f"Pattern doesn't compile: {patrn}") + + def validate_basic_schema_details( + self, schema_resolver: RefResolver, filepath: str + ): + """ + Validate that readOnly, writeOnly, etc are valid + """ + sections = [ + "readOnlyProperties", + "writeOnlyProperties", + "conditionalCreateOnlyProperties", + "nonPublicProperties", + "nonPublicDefinitions", + "createOnlyProperties", + "deprecatedProperties", + "primaryIdentifier", + ] + for section in sections: + for prop in schema_resolver.referrer.get(section, []): + try: + self.assertIsNotNone(schema_resolver.resolve_cfn_pointer(prop)) + except RefResolutionError: + self.fail(f"Can't find prop {prop} for {section} in {filepath}") + + def _build_keywords(self, obj: Any, schema_resolver: RefResolver, refs: list[str]): + if not isinstance(obj, dict): + yield [] + return + + if "$ref" in obj: + ref = obj["$ref"] + if ref in refs: + yield [] + return + _, resolved_schema = schema_resolver.resolve(ref) + yield from self._build_keywords( + resolved_schema, schema_resolver, refs + [ref] + ) + + if "type" in obj: + if "object" in ensure_list(obj["type"]): + if "properties" in obj: + for k, v in obj["properties"].items(): + for item in self._build_keywords(v, schema_resolver, refs): + yield [k] + item + if "array" in ensure_list(obj["type"]): + if "items" in obj: + for item in self._build_keywords( + obj["items"], schema_resolver, refs + ): + yield ["*"] + item + + yield [] + + def build_keywords(self, schema_resolver): + self._found_keywords.append( + "/".join(["Resources", schema_resolver.referrer["typeName"], "Properties"]) + ) + for k, v in schema_resolver.referrer.get("properties").items(): + for item in self._build_keywords(v, schema_resolver, []): + self._found_keywords.append( + "/".join( + [ + "Resources", + schema_resolver.referrer["typeName"], + "Properties", + k, + ] + + item + ) + ) + + def test_data_module_specs(self): + """Test data file formats""" + + draft7_schema = load_resource( + "cfnlint.data.schemas.other.draft7", "schema.json" + ) + store = {"http://json-schema.org/draft-07/schema": draft7_schema} + dir = self.paths["fixtures"] + for dirpath, filename in self.get_files(dir): + with open(os.path.join(dirpath, filename), "r", encoding="utf8") as fh: + store[filename] = json.load(fh) + + resolver = RefResolver.from_schema( + store["provider.definition.schema.v1.json"], store=store + ) + + validator = ( + StandardValidator({}) + .extend( + validators={ + "cfnLint": self.cfn_lint, + "pattern": self.pattern, + }, + )(schema=store["provider.definition.schema.v1.json"]) + .evolve(resolver=resolver) + ) + + for region in REGIONS: + dir = os.path.join( + self.paths["providers"], + region.replace("-", "_"), + ) + + for dirpath, filename in self.get_files(dir): + with open(os.path.join(dirpath, filename), "r", encoding="utf8") as fh: + d = json.load(fh) + # not allowed but true with this resource + if filename == "aws-cloudformation-customresource.json": + d["additionalProperties"] = False + if filename == "module.json": + continue + errs = list(validator.iter_errors(d)) + self.assertListEqual( + errs, [], f"Error with {dirpath}/{filename}: {errs}" + ) + schema_resolver = RefResolver(d) + self.validate_basic_schema_details( + schema_resolver, f"{dirpath}/{filename}" + ) + + if region == "us-east-1": + self.build_keywords(schema_resolver) + + def cfn_lint(self, validator, _, keywords, schema): + keywords = ensure_list(keywords) + self._found_keywords.extend(keywords) + + def test_other_specs(self): + """Test data file formats""" + + draft7_schema = load_resource( + "cfnlint.data.schemas.other.draft7", "schema.json" + ) + store = {"http://json-schema.org/draft-07/schema": draft7_schema} + dir = self.paths["fixtures"] + for dirpath, filename in self.get_files(dir): + with open(os.path.join(dirpath, filename), "r", encoding="utf8") as fh: + store[filename] = json.load(fh) + + resolver = RefResolver.from_schema( + store["http://json-schema.org/draft-07/schema"], store=store + ) + + validator = ( + StandardValidator({}) + .extend( + validators={ + "cfnLint": self.cfn_lint, + "pattern": self.pattern, + }, + )(schema=store["http://json-schema.org/draft-07/schema"]) + .evolve(resolver=resolver) + ) + + for dir_name in ["extensions", "other"]: + dir = self.paths[dir_name] + + for dirpath, filename in self.get_files(dir): + with open(os.path.join(dirpath, filename), "r", encoding="utf8") as fh: + d = json.load(fh) + errs = list(validator.iter_errors(d)) + self.assertListEqual( + errs, [], f"Error with {dirpath}/{filename}: {errs}" + ) + schema_resolver = RefResolver(d) + self.validate_basic_schema_details( + schema_resolver, f"{dirpath}/{filename}" + ) + + def test_x_keywords(self): + root_dir = pathlib.Path(__file__).parent.parent.parent / "src/cfnlint/rules" + rules = load_plugins( + str(root_dir), + "CfnLintKeyword", + "cfnlint.rules.jsonschema.CfnLintKeyword", + ) + rules.extend( + load_plugins( + str(root_dir), + "CfnLintJsonSchema", + "cfnlint.rules.jsonschema.CfnLintJsonSchema", + ) + ) + + for rule in rules: + for keyword in rule.keywords: + self.assertIn(keyword, self._found_keywords, f"{keyword} not found") diff --git a/testbed/aws-cloudformation__cfn-lint/test/testlib/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/testlib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/testlib/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/testlib/testcase.py b/testbed/aws-cloudformation__cfn-lint/test/testlib/testcase.py new file mode 100644 index 0000000000000000000000000000000000000000..20108b1fceb56160efa233edf27abd9e8ff61766 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/testlib/testcase.py @@ -0,0 +1,33 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from unittest import TestCase + +import cfnlint.decode.cfn_yaml + + +class BaseTestCase(TestCase): + """ + All test cases should inherit from this class as any common + functionality that is added here will then be available to all + subclasses. This facilitates the ability to update in one spot + and allow all tests to get the update for easy maintenance. + """ + + def load_template(self, filename): + """Return template""" + return cfnlint.decode.cfn_yaml.load(filename) + + def assertEqualListOfDicts(self, a, b): + """Compare two lists of dicts""" + assert isinstance(a, list) + assert isinstance(b, list) + + def key_func(d): + """sort dict based on keys""" + items = ((k, v if v is not None else "") for k, v in d.items()) + return sorted(items) + + self.assertEqual(sorted(a, key=key_func), sorted(b, key=key_func)) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/cfn_json/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/cfn_json/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/cfn_json/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/cfn_json/test_cfn_json.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/cfn_json/test_cfn_json.py new file mode 100644 index 0000000000000000000000000000000000000000..2463c21e6c812bce0509d428ddaa23986b634b3e --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/cfn_json/test_cfn_json.py @@ -0,0 +1,109 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from io import StringIO +from test.testlib.testcase import BaseTestCase +from unittest.mock import patch + +import cfnlint.decode.cfn_json # pylint: disable=E0401 +from cfnlint import ConfigMixIn +from cfnlint.config import _DEFAULT_RULESDIR +from cfnlint.rules import Rules +from cfnlint.template.template import Template # pylint: disable=E0401 + + +class TestCfnJson(BaseTestCase): + """Test JSON Parsing""" + + def setUp(self): + """SetUp template object""" + self.rules = Rules.create_from_directory(_DEFAULT_RULESDIR) + self.config = ConfigMixIn( + include_experimental=True, + ) + + self.filenames = { + "config_rule": { + "filename": "test/fixtures/templates/quickstart/config-rules.json", + "failures": 5, + }, + "iam": { + "filename": "test/fixtures/templates/quickstart/iam.json", + "failures": 5, + }, + "nat_instance": { + "filename": "test/fixtures/templates/quickstart/nat-instance.json", + "failures": 4, + }, + "vpc_management": { + "filename": "test/fixtures/templates/quickstart/vpc-management.json", + "failures": 9, + }, + "vpc": { + "filename": "test/fixtures/templates/quickstart/vpc.json", + "failures": 5, + }, + "poller": { + "filename": "test/fixtures/templates/public/lambda-poller.json", + "failures": 1, + }, + } + + def test_success_parse(self): + """Test Successful JSON Parsing""" + for _, values in self.filenames.items(): + filename = values.get("filename") + failures = values.get("failures") + + template = cfnlint.decode.cfn_json.load(filename) + cfn = Template(filename, template, ["us-east-1"]) + + matches = list(self.rules.run(filename, cfn, self.config)) + assert ( + len(matches) == failures + ), "Expected {} failures, got {} on {}".format(failures, matches, filename) + + def test_success_escape_character(self): + """Test Successful JSON Parsing""" + failures = 1 + filename = "test/fixtures/templates/good/decode/parsing.json" + template = cfnlint.decode.cfn_json.load(filename) + cfn = Template(filename, template, ["us-east-1"]) + + matches = list(self.rules.run(filename, cfn, self.config)) + assert len(matches) == failures, "Expected {} failures, got {} on {}".format( + failures, matches, filename + ) + + def test_success_parse_stdin(self): + """Test Successful JSON Parsing through stdin""" + for _, values in self.filenames.items(): + filename = None + failures = values.get("failures") + with open(values.get("filename"), "r") as fp: + file_content = fp.read() + with patch("sys.stdin", StringIO(file_content)): + template = cfnlint.decode.cfn_json.load(filename) + cfn = Template(filename, template, ["us-east-1"]) + + matches = list(self.rules.run(filename, cfn, self.config)) + assert ( + len(matches) == failures + ), "Expected {} failures, got {} on {}".format( + failures, matches, values.get("filename") + ) + + def test_fail_run(self): + """Test failure run""" + + filename = "test/fixtures/templates/bad/json_parse.json" + + try: + cfnlint.decode.cfn_json.load(filename) + except cfnlint.decode.cfn_json.JSONDecodeError: + assert True + return + + assert False diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/cfn_yaml/test_yaml.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/cfn_yaml/test_yaml.py new file mode 100644 index 0000000000000000000000000000000000000000..4e5b5afc809ab5adbb80f32a74198a68e033e1f4 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/cfn_yaml/test_yaml.py @@ -0,0 +1,77 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from io import StringIO +from test.testlib.testcase import BaseTestCase +from unittest.mock import patch + +import cfnlint.decode.cfn_yaml # pylint: disable=E0401 +from cfnlint.config import _DEFAULT_RULESDIR, ConfigMixIn +from cfnlint.rules import Rules +from cfnlint.template.template import Template # pylint: disable=E0401 + + +class TestYamlParse(BaseTestCase): + """Test YAML Parsing""" + + def setUp(self): + """SetUp template object""" + self.rules = Rules.create_from_directory(_DEFAULT_RULESDIR) + + self.filenames = { + "config_rule": { + "filename": "test/fixtures/templates/public/lambda-poller.yaml", + "failures": 1, + }, + "generic_bad": { + "filename": "test/fixtures/templates/bad/generic.yaml", + "failures": 35, + }, + } + + def test_success_parse(self): + """Test Successful YAML Parsing""" + for _, values in self.filenames.items(): + filename = values.get("filename") + failures = values.get("failures") + template = cfnlint.decode.cfn_yaml.load(filename) + cfn = Template(filename, template, ["us-east-1"]) + + matches = list(self.rules.run(filename, cfn, ConfigMixIn({}))) + assert ( + len(matches) == failures + ), "Expected {} failures, got {} on {}".format( + failures, len(matches), filename + ) + + def test_success_parse_stdin(self): + """Test Successful YAML Parsing through stdin""" + for _, values in self.filenames.items(): + filename = None + failures = values.get("failures") + with open(values.get("filename"), "r") as fp: + file_content = fp.read() + + with patch("sys.stdin", StringIO(file_content)): + template = cfnlint.decode.cfn_yaml.load(filename) + cfn = Template(filename, template, ["us-east-1"]) + + matches = [] + matches.extend(self.rules.run(filename, cfn, ConfigMixIn({}))) + assert ( + len(matches) == failures + ), "Expected {} failures, got {} on {}".format( + failures, len(matches), values.get("filename") + ) + + def test_map_failure(self): + """Test a failure is passed on unhashable map""" + filename = "test/fixtures/templates/bad/core/parse_invalid_map.yaml" + + self.assertRaises( + cfnlint.decode.cfn_yaml.CfnParseError, + cfnlint.decode.cfn_yaml.load, + filename, + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_condition.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_condition.py new file mode 100644 index 0000000000000000000000000000000000000000..1cf5117e7c01b704fdc254c76d6ad671174ae0fd --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_condition.py @@ -0,0 +1,97 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from unittest import TestCase + +from cfnlint.conditions._condition import ( + ConditionAnd, + ConditionNot, + ConditionOr, + ConditionUnnammed, +) +from cfnlint.conditions._utils import get_hash + + +class TestCondition(TestCase): + """Test Condition""" + + def test_not_condition(self): + """Test not condition""" + + with self.assertRaises(ValueError): + ConditionNot( + [ + {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]}, + {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-west-2"]}, + ], + {}, + ) + + def test_unnamed_condition(self): + """Test unnamed condition""" + + with self.assertRaises(ValueError): + ConditionUnnammed( + "equals", # not a string + {}, + ) + + def test_not_a_list(self): + """Test condition failures""" + + with self.assertRaises(ValueError): + ConditionUnnammed({"Fn::And": {}}, {}) + + with self.assertRaises(ValueError): + ConditionUnnammed({"Condition": {}}, {}) + + with self.assertRaises(ValueError): + ConditionUnnammed({"BadKey": {}}, {}) + + def test_condition_test(self): + equals = {"Ref": "AWS::Region"} + h = get_hash(equals) + self.assertTrue( + ConditionNot( + [ + {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]}, + ], + {}, + )._test( + {h: "us-west-2"}, + ) + ) + self.assertFalse( + ConditionNot( + [ + {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]}, + ], + {}, + )._test( + {h: "us-east-1"}, + ) + ) + self.assertFalse( + ConditionAnd( + [ + {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]}, + {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-west-2"]}, + ], + {}, + )._test( + {h: "us-east-1"}, + ) + ) + self.assertTrue( + ConditionOr( + [ + {"Fn::Equals": ["us-east-1", {"Ref": "AWS::Region"}]}, + {"Fn::Equals": ["us-west-2", {"Ref": "AWS::Region"}]}, + ], + {}, + )._test( + {h: "us-east-1"}, + ) + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_conditions.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_conditions.py new file mode 100644 index 0000000000000000000000000000000000000000..d3d248652c61f70330e033d101ea1eef5e05c515 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_conditions.py @@ -0,0 +1,331 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import string +from unittest import TestCase + +from cfnlint.conditions import UnknownSatisfisfaction +from cfnlint.conditions._utils import get_hash +from cfnlint.decode import decode_str +from cfnlint.template import Template + + +class TestConditions(TestCase): + """Test Conditions""" + + def test_bad_condition_definition(self): + """Badly formatted condition statements will return no results""" + template = decode_str( + """ + Conditions: + IsProd: !Equals [!Ref Environment, "prod", "production"] + IsUsEast1: !Equals [!Ref "AWS::Region", "us-east-1"] + """ + )[0] + + cfn = Template("", template) + self.assertEqual( + len(cfn.conditions._conditions), 1 + ) # would be 2 but IsProd fails + # test coverage for KeyErrors in the following functions + self.assertTrue( + cfn.conditions.check_implies( + { + "Test": True, + }, + "IsUsEast1", + ) + ) + self.assertEqual( + list(cfn.conditions.build_scenarios({"IsProd": None, "IsUsEast1": None})), + [], + ) + + def test_run_away_scenarios(self): + """We cap runaway scenarios""" + template = { + "Parameters": {}, + "Conditions": {}, + } + condition_names = {} + for p in string.ascii_letters[0:10]: + template["Parameters"][f"{p}Parameter"] = { + "Type": "String", + } + template["Conditions"][f"{p}Condition"] = { + "Fn::Equals": [{"Ref": f"{p}Parameter"}, "{p}"] + } + condition_names[f"{p}Condition"] = None + + cfn = Template("", template) + self.assertEqual(len(cfn.conditions._conditions), 10) + self.assertEqual( + len(list(cfn.conditions.build_scenarios(condition_names))), + cfn.conditions._max_scenarios, + ) + + def test_check_implies(self): + """We properly validate implies scenarios""" + template = { + "Parameters": {}, + "Conditions": {}, + } + condition_names = [] + for p in string.ascii_letters[0:4]: + template["Parameters"][f"{p}Parameter"] = { + "Type": "String", + } + template["Conditions"][f"{p}Condition"] = { + "Fn::Equals": [{"Ref": f"{p}Parameter"}, "{p}"] + } + condition_names.append(f"{p}Condition") + + cfn = Template("", template) + self.assertFalse( + cfn.conditions.check_implies({"aCondition": False}, "aCondition") + ) + self.assertTrue( + cfn.conditions.check_implies({"aCondition": True}, "aCondition") + ) + self.assertTrue( + cfn.conditions.check_implies( + {"aCondition": True, "bCondition": False}, "aCondition" + ) + ) + + def test_check_always_true_or_false(self): + """We properly validate static equals""" + template = decode_str( + """ + Parameters: + FalseParameter: + Default: "false" + Type: String + Conditions: + IsTrue: !Equals ["true", "true"] + IsFalse: !Equals [!Ref FalseParameter, !Ref FalseParameter] + """ + )[0] + + cfn = Template("", template) + self.assertEqual(len(cfn.conditions._conditions), 2) + # test coverage for KeyErrors in the following functions + self.assertTrue(cfn.conditions.check_implies({"IsTrue": True}, "IsFalse")) + + def test_check_never_false(self): + """With allowed values two conditions can not both be false""" + template = decode_str( + """ + Parameters: + Environment: + Type: String + AllowedValues: ["prod", "dev"] + Conditions: + IsProd: !Equals [!Ref Environment, "prod"] + IsDev: !Equals [!Ref Environment, "dev"] + """ + )[0] + + cfn = Template("", template) + self.assertEqual(len(cfn.conditions._conditions), 2) + self.assertListEqual( + list(cfn.conditions.build_scenarios({"IsProd": None, "IsDev": None})), + [ + {"IsProd": True, "IsDev": False}, + {"IsProd": False, "IsDev": True}, + ], + ) + + def test_check_can_be_false(self): + """With allowed values two conditions can both be false""" + template = decode_str( + """ + Parameters: + Environment: + Type: String + AllowedValues: ["prod", "dev", "stage"] + Conditions: + IsProd: !Equals [!Ref Environment, "prod"] + IsDev: !Equals [!Ref Environment, "dev"] + """ + )[0] + + cfn = Template("", template) + self.assertEqual(len(cfn.conditions._conditions), 2) + self.assertListEqual( + list(cfn.conditions.build_scenarios({"IsProd": None, "IsDev": None})), + [ + {"IsProd": True, "IsDev": False}, + {"IsProd": False, "IsDev": True}, + {"IsProd": False, "IsDev": False}, + ], + ) + self.assertListEqual( + list(cfn.conditions.build_scenarios({"IsProd": {True}, "IsDev": None})), + [ + {"IsProd": True, "IsDev": False}, + ], + ) + self.assertListEqual( + list(cfn.conditions.build_scenarios({"IsProd": {False}, "IsDev": None})), + [ + {"IsProd": False, "IsDev": True}, + {"IsProd": False, "IsDev": False}, + ], + ) + + def test_check_can_be_good_when_condition_value(self): + """Some times a condition Equals doesn't match to allowed values""" + template = decode_str( + """ + Parameters: + Environment: + Type: String + AllowedValues: ["prod", "dev", "stage"] + Conditions: + IsGamma: !Equals [!Ref Environment, "gamma"] + IsBeta: !Equals ["beta", !Ref Environment] + """ + )[0] + + cfn = Template("", template) + self.assertEqual(len(cfn.conditions._conditions), 2) + self.assertListEqual( + list(cfn.conditions.build_scenarios({"IsGamma": None, "IsBeta": None})), + [ + {"IsBeta": False, "IsGamma": False}, + ], + ) + self.assertListEqual( + list(cfn.conditions.build_scenarios({"IsGamma": None})), + [ + {"IsGamma": False}, + ], + ) + + def test_check_condition_region(self): + """Regional based condition testing""" + template = decode_str( + """ + Parameters: + Environment: + Type: String + AllowedValues: ["prod", "dev", "stage"] + Conditions: + IsUsEast1: !Equals [!Ref AWS::Region, "us-east-1"] + IsUsWest2: !Equals ["us-west-2", !Ref AWS::Region] + IsProd: !Equals [!Ref Environment, "prod"] + """ + )[0] + + cfn = Template("", template) + self.assertEqual(len(cfn.conditions._conditions), 3) + self.assertListEqual( + cfn.conditions.build_scenerios_on_region("IsUsEast1", "us-east-1"), + [ + True, + ], + ) + self.assertListEqual( + cfn.conditions.build_scenerios_on_region("IsUsEast1", "us-west-2"), + [ + False, + ], + ) + self.assertListEqual( + cfn.conditions.build_scenerios_on_region("IsUsWest2", "us-west-2"), + [ + True, + ], + ) + self.assertListEqual( + cfn.conditions.build_scenerios_on_region("IsUsWest2", "us-east-1"), + [ + False, + ], + ) + self.assertListEqual( + cfn.conditions.build_scenerios_on_region("IsProd", "us-east-1"), + [ + True, + False, + ], + ) + self.assertListEqual( + cfn.conditions.build_scenerios_on_region("Foo", "us-east-1"), + [ + True, + False, + ], + ) + + def test_test_condition(self): + """Get condition and test""" + template = decode_str( + """ + Parameters: + Environment: + Type: String + AllowedValues: ["prod", "dev", "stage"] + Conditions: + IsUsEast1: !Equals [!Ref AWS::Region, "us-east-1"] + IsUsWest2: !Equals ["us-west-2", !Ref AWS::Region] + IsProd: !Equals [!Ref Environment, "prod"] + IsUsEast1AndProd: !And [!Condition IsUsEast1, !Condition IsProd] + """ + )[0] + + h_region = get_hash({"Ref": "AWS::Region"}) + h_environment = get_hash({"Ref": "Environment"}) + + cfn = Template("", template) + self.assertTrue(cfn.conditions.get("IsUsEast1").test({h_region: "us-east-1"})) + self.assertFalse(cfn.conditions.get("IsProd").test({h_environment: "dev"})) + self.assertTrue( + cfn.conditions.get("IsUsEast1AndProd").test( + {h_region: "us-east-1", h_environment: "prod"} + ) + ) + self.assertFalse( + cfn.conditions.get("IsUsEast1AndProd").test( + {h_region: "us-east-1", h_environment: "dev"} + ) + ) + + def test_build_scenerios_on_region_with_condition_dne(self): + """Get condition and test""" + template = decode_str( + """ + Conditions: + IsUsEast1: !Equals [!Ref AWS::Region, "us-east-1"] + """ + )[0] + + cfn = Template("", template) + self.assertListEqual( + list(cfn.conditions.build_scenerios_on_region("IsProd", "us-east-1")), + [True, False], + ) + + def test_satifaction(self): + """Get condition and test""" + template = decode_str( + """ + Parameters: + SecurityGroups: + Default: "" + Type: CommaDelimitedList + Conditions: + IsUsEast1: !Equals [!Ref AWS::Region, "us-east-1"] + HasSecurityGroups: !Not [ !Equals [ !Join [ '', !Ref SecurityGroups ], ''] ] + """ + )[0] + + cfn = Template("", template) + + with self.assertRaises(UnknownSatisfisfaction): + cfn.conditions.satisfiable( + {"HasSecurityGroups": True}, {"SecurityGroups": [""]} + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_equals.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_equals.py new file mode 100644 index 0000000000000000000000000000000000000000..29a5b9af15d24f6e00d3471aeb88a3e288063fe1 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_equals.py @@ -0,0 +1,74 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from unittest import TestCase + +from cfnlint.conditions._equals import Equal +from cfnlint.conditions._utils import get_hash + + +class TestEquals(TestCase): + """Test Equals""" + + def setUp(self) -> None: + self.equals = {"Ref": "AWS::Region"} + self.equals_h = get_hash(self.equals) + + self.parameter_region = {"Ref": "Region"} + self.parameter_region_h = get_hash(self.parameter_region) + + self.parameter_env = {"Ref": "Environment"} + self.parameter_env_h = get_hash(self.parameter_env) + + return super().setUp() + + def test_equals_error_test(self): + """Test equals scenarios condition""" + equal = Equal([self.equals, "us-east-1"]) + + with self.assertRaises(ValueError): + equal.test({"foo": "bar"}) + + def test_equals_left_test(self): + """Test equals scenarios condition""" + equal = Equal([self.equals, "us-east-1"]) + + self.assertTrue(equal.test({self.equals_h: "us-east-1"})) + self.assertFalse(equal.test({self.equals_h: "us-west-2"})) + + equal = Equal([self.equals, self.parameter_region]) + self.assertTrue( + equal.test( + { + self.equals_h: self.parameter_region_h, + self.parameter_region_h: self.equals_h, + } + ) + ) + self.assertFalse(equal.test({self.equals_h: self.parameter_env_h})) + + def test_equals_left_right(self): + """Test equals scenarios condition""" + equal = Equal(["us-east-1", self.equals]) + + self.assertTrue(equal.test({self.equals_h: "us-east-1"})) + self.assertFalse(equal.test({self.equals_h: "us-west-2"})) + + equal = Equal([self.parameter_region, self.equals]) + self.assertTrue( + equal.test( + { + self.equals_h: self.parameter_region_h, + self.parameter_region_h: self.equals_h, + } + ) + ) + self.assertFalse(equal.test({self.equals_h: self.parameter_env_h})) + + def test_equal_string_test(self): + """Test equals scenarios condition""" + equal = Equal(["us-west-2", "us-east-1"]) + + self.assertFalse(equal.test({"foo": "bar"})) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_rules.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..49f09be655f218f087c78e1ab7caf5f568dd7732 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_rules.py @@ -0,0 +1,524 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from unittest import TestCase + +from cfnlint.conditions._rule import _Assertion +from cfnlint.decode import decode_str +from cfnlint.template import Template + + +class TestConditionsWithRules(TestCase): + + def test_conditions_with_rules(self): + template = decode_str( + """ + Conditions: + IsProd: !Equals [!Ref Environment, "prod"] + IsUsEast1: !Equals [!Ref "AWS::Region", "us-east-1"] + Rules: + Rule1: + Assertions: + - Assert: + Fn::And: + - !Equals [!Ref Environment, "prod"] + - !Equals [!Ref "AWS::Region", "us-east-1"] + Rule2: + Assertions: + - Assert: + Fn::Or: + - !Equals [!Ref Environment, "prod"] + - !Equals [!Ref "AWS::Region", "us-east-1"] + """ + )[0] + + cfn = Template("", template) + self.assertEqual(len(cfn.conditions._conditions), 2) + self.assertEqual(len(cfn.conditions._rules), 2) + + self.assertListEqual( + [equal.hash for equal in cfn.conditions._rules[0].equals], + [ + "d0f5e92fc5233a6b011342df171f191838491056", + "362a2ca660fa34c91feeee4681e8433101d2a687", + ], + ) + + self.assertTrue( + cfn.conditions.satisfiable( + {"IsProd": True, "IsUsEast1": True}, + {"AWS::Region": "us-east-1", "Environment": "prod"}, + ) + ) + self.assertFalse( + cfn.conditions.satisfiable( + {"IsProd": True, "IsUsEast1": False}, + {"AWS::Region": "us-west-2", "Environment": "prod"}, + ) + ) + self.assertFalse( + cfn.conditions.satisfiable( + {"IsProd": False, "IsUsEast1": True}, + {"AWS::Region": "us-east-1", "Environment": "dev"}, + ) + ) + self.assertFalse( + cfn.conditions.satisfiable( + {"IsProd": False, "IsUsEast1": False}, + {"AWS::Region": "us-west-2", "Environment": "dev"}, + ) + ) + + def test_conditions_with_rules_implies(self): + template = decode_str( + """ + Conditions: + IsProd: !Equals [!Ref Environment, "prod"] + IsUsEast1: !Equals [!Ref "AWS::Region", "us-east-1"] + Rules: + Rule: + RuleCondition: !Equals [!Ref Environment, "prod"] + Assertions: + - Assert: !Equals [!Ref "AWS::Region", "us-east-1"] + + """ + )[0] + + cfn = Template("", template) + self.assertEqual(len(cfn.conditions._conditions), 2) + self.assertEqual(len(cfn.conditions._rules), 1) + + self.assertListEqual( + [equal.hash for equal in cfn.conditions._rules[0].equals], + [ + "d0f5e92fc5233a6b011342df171f191838491056", + "362a2ca660fa34c91feeee4681e8433101d2a687", + ], + ) + + self.assertTrue( + cfn.conditions.satisfiable( + {"IsProd": True, "IsUsEast1": True}, + {"AWS::Region": "us-east-1", "Environment": "prod"}, + ) + ) + self.assertFalse( + cfn.conditions.satisfiable( + {"IsProd": True, "IsUsEast1": False}, + {"AWS::Region": "us-west-2", "Environment": "prod"}, + ) + ) + self.assertTrue( + cfn.conditions.satisfiable( + {"IsProd": False, "IsUsEast1": True}, + {"AWS::Region": "us-east-1", "Environment": "dev"}, + ) + ) + self.assertTrue( + cfn.conditions.satisfiable( + {"IsProd": False, "IsUsEast1": False}, + {"AWS::Region": "us-west-2", "Environment": "dev"}, + ) + ) + + def test_conditions_with_multiple_rules(self): + template = decode_str( + """ + Parameters: + Environment: + Type: String + Default: dev + AllowedValues: + - dev + - stage + - prod + Conditions: + IsProd: !Equals [!Ref Environment, "prod"] + IsDev: !Equals [!Ref Environment, "dev"] + IsUsEast1: !Equals [!Ref "AWS::Region", "us-east-1"] + IsNotUsEast1: !Not [!Condition IsUsEast1] + Rules: + Rule1: + RuleCondition: !Equals [!Ref Environment, "prod"] + Assertions: + - Assert: !Equals [!Ref "AWS::Region", "us-east-1"] + Rule2: + RuleCondition: !Equals [!Ref Environment, "dev"] + Assertions: + - Assert: !Not [!Equals [!Ref "AWS::Region", "us-east-1"]] + """ + )[0] + + cfn = Template("", template) + self.assertEqual(len(cfn.conditions._conditions), 4) + self.assertEqual(len(cfn.conditions._rules), 2) + + self.assertListEqual( + [equal.hash for equal in cfn.conditions._rules[0].equals], + [ + "d0f5e92fc5233a6b011342df171f191838491056", + "362a2ca660fa34c91feeee4681e8433101d2a687", + ], + ) + self.assertListEqual( + [equal.hash for equal in cfn.conditions._rules[1].equals], + [ + "d2dab653475dd270354fe84c4f80b54883e958bb", + "362a2ca660fa34c91feeee4681e8433101d2a687", + ], + ) + + self.assertTrue( + cfn.conditions.satisfiable( + { + "IsProd": True, + "IsUsEast1": True, + "IsDev": False, + "IsNotUsEast1": False, + }, + {"AWS::Region": "us-east-1", "Environment": "prod"}, + ) + ) + self.assertFalse( + cfn.conditions.satisfiable( + { + "IsProd": True, + "IsUsEast1": False, + "IsDev": False, + "IsNotUsEast1": False, + }, + {"AWS::Region": "us-west-2", "Environment": "prod"}, + ) + ) + self.assertFalse( + cfn.conditions.satisfiable( + { + "IsProd": False, + "IsUsEast1": True, + "IsDev": True, + "IsNotUsEast1": False, + }, + {"AWS::Region": "us-east-1", "Environment": "dev"}, + ) + ) + self.assertTrue( + cfn.conditions.satisfiable( + { + "IsProd": False, + "IsUsEast1": False, + "IsDev": True, + "IsNotUsEast1": True, + }, + {"AWS::Region": "us-west-2", "Environment": "dev"}, + ) + ) + self.assertTrue( + cfn.conditions.satisfiable( + { + "IsProd": False, + "IsUsEast1": True, + "IsDev": False, + "IsNotUsEast1": False, + }, + {"AWS::Region": "us-east-1", "Environment": "stage"}, + ) + ) + self.assertTrue( + cfn.conditions.satisfiable( + { + "IsProd": False, + "IsUsEast1": False, + "IsDev": False, + "IsNotUsEast1": True, + }, + {"AWS::Region": "us-west-2", "Environment": "stage"}, + ) + ) + + def test_fn_equals_assertions_two(self): + template = decode_str( + """ + Rules: + Rule1: + Assertions: + - Assert: !Equals ["A", "B"] + Rule2: + Assertions: + - Assert: !Equals ["A", "A"] + """ + )[0] + + cfn = Template("", template) + self.assertEqual(len(cfn.conditions._conditions), 0) + self.assertEqual(len(cfn.conditions._rules), 2) + + self.assertListEqual( + [equal.hash for equal in cfn.conditions._rules[0].equals], + [ + "e7e68477799682e53ecb09f476128abaeba0bdae", + ], + ) + self.assertListEqual( + [equal.hash for equal in cfn.conditions._rules[1].equals], + [ + "da2a95009a205d5caacd42c3c11ebd4c151b3409", + ], + ) + + self.assertFalse( + cfn.conditions.satisfiable( + {}, + {}, + ) + ) + + def test_fn_equals_assertions_one(self): + template = decode_str( + """ + Rules: + Rule1: + Assertions: + - Assert: !Equals ["A", "A"] + """ + )[0] + + cfn = Template("", template) + self.assertEqual(len(cfn.conditions._conditions), 0) + self.assertEqual(len(cfn.conditions._rules), 1) + + self.assertListEqual( + [equal.hash for equal in cfn.conditions._rules[0].equals], + [ + "da2a95009a205d5caacd42c3c11ebd4c151b3409", + ], + ) + + self.assertTrue( + cfn.conditions.satisfiable( + {}, + {}, + ) + ) + + def test_fn_equals_assertions_ref_no_data(self): + template = decode_str( + """ + Parameters: + AccountId: + Type: String + Rules: + Rule1: + Assertions: + - Assert: !Equals [!Ref AccountId, !Ref AWS::AccountId] + """ + )[0] + + cfn = Template("", template) + self.assertEqual(len(cfn.conditions._conditions), 0) + self.assertEqual(len(cfn.conditions._rules), 1) + + self.assertListEqual( + [equal.hash for equal in cfn.conditions._rules[0].equals], + [ + "f36e61f3d5bf6cdc6ea2e7f01487af728094a439", + ], + ) + + self.assertTrue( + cfn.conditions.satisfiable( + {}, + {}, + ) + ) + + def test_fn_equals_assertions_ref_never_satisfiable(self): + template = decode_str( + """ + Parameters: + AccountId: + Type: String + Rules: + Rule1: + Assertions: + - Assert: !Equals [!Ref AccountId, !Ref AWS::AccountId] + - Assert: !Not [!Equals [!Ref AccountId, !Ref AWS::AccountId]] + """ + )[0] + + cfn = Template("", template) + self.assertEqual(len(cfn.conditions._conditions), 0) + self.assertEqual(len(cfn.conditions._rules), 1) + + self.assertListEqual( + [equal.hash for equal in cfn.conditions._rules[0].equals], + [ + "f36e61f3d5bf6cdc6ea2e7f01487af728094a439", + "f36e61f3d5bf6cdc6ea2e7f01487af728094a439", + ], + ) + + self.assertFalse( + cfn.conditions.satisfiable( + {}, + {}, + ) + ) + + def test_conditions_with_rules_and_parameters(self): + template = decode_str( + """ + Conditions: + DeployGateway: !Equals + - !Ref 'DeployGateway' + - 'true' + DeployVpc: !Equals + - !Ref 'DeployVpc' + - 'true' + Parameters: + DeployAnything: + AllowedValues: + - 'false' + - 'true' + Type: 'String' + DeployGateway: + AllowedValues: + - 'false' + - 'true' + Type: 'String' + DeployVpc: + AllowedValues: + - 'false' + - 'true' + Type: 'String' + Rules: + DeployGateway: + Assertions: + - Assert: !Or + - !Equals + - !Ref 'DeployAnything' + - 'true' + - !Equals + - !Ref 'DeployGateway' + - 'false' + DeployVpc: + Assertions: + - Assert: !Or + - !Equals + - !Ref 'DeployGateway' + - 'true' + - !Equals + - !Ref 'DeployVpc' + - 'false' + Resources: + InternetGateway: + Condition: 'DeployGateway' + Type: 'AWS::EC2::InternetGateway' + InternetGatewayAttachment: + Condition: 'DeployVpc' + Type: 'AWS::EC2::VPCGatewayAttachment' + Properties: + InternetGatewayId: !Ref 'InternetGateway' + VpcId: !Ref 'Vpc' + """ + )[0] + + cfn = Template("", template) + self.assertEqual(len(cfn.conditions._conditions), 2) + self.assertEqual(len(cfn.conditions._rules), 2) + + self.assertListEqual( + [equal.hash for equal in cfn.conditions._rules[0].equals], + [ + "d0d70a1e66dc83d7a0fce24c2eca396af1f34e53", + "bbf5c94c1a4b5a79c7a7863fe9463884cb422450", + ], + ) + + self.assertTrue( + cfn.conditions.satisfiable( + {}, + {}, + ) + ) + + self.assertTrue( + cfn.conditions.check_implies({"DeployVpc": True}, "DeployGateway") + ) + + self.assertFalse( + cfn.conditions.check_implies({"DeployVpc": False}, "DeployGateway") + ) + + self.assertFalse( + cfn.conditions.check_implies({"DeployGateway": False}, "DeployVpc") + ) + + +class TestAssertion(TestCase): + def test_assertion_errors(self): + with self.assertRaises(ValueError): + _Assertion({"A": "B", "C": "D"}, {}) + + with self.assertRaises(ValueError): + _Assertion({"Fn::Not": {"C": "D"}}, {}) + + with self.assertRaises(ValueError): + _Assertion({"Not": {"C": "D"}}, {}) + + with self.assertRaises(ValueError): + _Assertion({"Condition": {"C": "D"}}, {}) + + def test_init_rules_with_list(self): + template = decode_str( + """ + Conditions: + IsUsEast1: !Equals [!Ref "AWS::Region", "us-east-1"] + IsNotUsEast1: !Not [!Condition IsUsEast1] + Rules: [] + """ + )[0] + + cfn = Template("", template) + self.assertListEqual(cfn.conditions._rules, []) + + def test_init_rules_with_wrong_assertions_type(self): + template = decode_str( + """ + Conditions: + IsUsEast1: !Equals [!Ref "AWS::Region", "us-east-1"] + IsNotUsEast1: !Not [!Condition IsUsEast1] + Rules: + Rule1: + Assertions: {"Foo": "Bar"} + Rule2: + Assertions: + - Assert: !Equals [!Ref "AWS::Region", "us-east-1"] + """ + )[0] + + cfn = Template("", template) + self.assertEqual(len(cfn.conditions._rules), 1) + + def test_init_rules_with_no_keys(self): + template = decode_str( + """ + Conditions: + IsUsEast1: !Equals [!Ref "AWS::Region", "us-east-1"] + IsNotUsEast1: !Not [!Condition IsUsEast1] + Rules: + Rule1: + Foo: Bar + Rule2: + Assertions: + - Assert: + Fn::Or: + - !Not [!Equals [!Ref "AWS::Region", "us-east-1"]] + - !Equals [!Ref "AWS::Region", "us-east-1"] + Rule3: [] + """ + )[0] + + cfn = Template("", template) + self.assertEqual(len(cfn.conditions._rules), 1) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_cli_args.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_cli_args.py new file mode 100644 index 0000000000000000000000000000000000000000..7764bc2d7d4f5655b7a55409966d3634e9151ba5 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_cli_args.py @@ -0,0 +1,137 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import logging +import os +from test.testlib.testcase import BaseTestCase +from unittest.mock import patch + +import cfnlint.config # pylint: disable=E0401 + +LOGGER = logging.getLogger("cfnlint") + + +class TestArgsParser(BaseTestCase): + """Test Parser Arguments""" + + def tearDown(self): + """Setup""" + for handler in LOGGER.handlers: + LOGGER.removeHandler(handler) + + def test_create_parser(self): + """Test success run""" + + config = cfnlint.config.CliArgs( + ["-t", "test.yaml", "--ignore-bad-template", "--format", "quiet", "--debug"] + ) + self.assertEqual(config.cli_args.templates, []) + self.assertEqual(config.cli_args.template_alt, ["test.yaml"]) + self.assertEqual(config.cli_args.ignore_bad_template, True) + self.assertEqual(config.cli_args.format, "quiet") + self.assertEqual(config.cli_args.debug, True) + + def test_create_parser_default_param(self): + """Test success run""" + + config = cfnlint.config.CliArgs( + [ + "--regions", + "us-east-1", + "us-west-2", + "--", + "template1.yaml", + "template2.yaml", + ] + ) + self.assertEqual( + config.cli_args.templates, ["template1.yaml", "template2.yaml"] + ) + self.assertEqual(config.cli_args.template_alt, []) + self.assertEqual(config.cli_args.regions, ["us-east-1", "us-west-2"]) + + def test_stdout(self): + """Test success run""" + + config = cfnlint.config.CliArgs(["-t", "template1.yaml"]) + self.assertIsNone(config.cli_args.output_file) + + def test_output_file(self): + """Test success run""" + + config = cfnlint.config.CliArgs( + ["-t", "template1.yaml", "--output-file", "test_output.txt"] + ) + self.assertEqual(config.cli_args.output_file, "test_output.txt") + + def test_force_update_specs(self): + """Test success run""" + + config = cfnlint.config.CliArgs(["--update-specs", "--force"]) + self.assertEqual(config.cli_args.force, True) + self.assertEqual(config.cli_args.update_specs, True) + + def test_create_parser_exend(self): + """Test success run""" + + config = cfnlint.config.CliArgs( + ["-t", "template1.yaml", "-t", "template2.yaml"] + ) + self.assertEqual(config.cli_args.templates, []) + self.assertEqual( + config.cli_args.template_alt, ["template1.yaml", "template2.yaml"] + ) + + def test_create_parser_config_file_regions(self): + """Test success run""" + + config = cfnlint.config.CliArgs( + [ + "--regions", + "us-west-1", + "--include-checks", + "I1234", + "--", + "template1.yaml", + ] + ) + self.assertEqual(config.cli_args.templates, ["template1.yaml"]) + self.assertEqual(config.cli_args.include_checks, ["I1234"]) + self.assertEqual(config.cli_args.regions, ["us-west-1"]) + + def test_create_parser_config_file(self): + """Test success run""" + + config = cfnlint.config.CliArgs( + ["--mandatory-checks", "I1234", "--", "template1.yaml"] + ) + self.assertEqual(config.cli_args.templates, ["template1.yaml"]) + self.assertEqual(config.cli_args.mandatory_checks, ["I1234"]) + + def test_create_parser_rule_configuration(self): + """Test success run""" + + config = cfnlint.config.CliArgs( + ["-x", "E3012:strict=true", "-x", "E3012:key=value,E3001:key=value"] + ) + self.assertEqual( + config.cli_args.configure_rules, + {"E3012": {"key": "value", "strict": "true"}, "E3001": {"key": "value"}}, + ) + + def test_exit_code_parameter(self): + """Test values of exit code""" + + for param in ["informational", "warning", "error"]: + with self.subTest(): + config = cfnlint.config.CliArgs(["--non-zero-exit-code", param]) + self.assertEqual(config.cli_args.non_zero_exit_code, param) + + def test_exit_code_parameter_error(self): + """Test result when bad value provided""" + with open(os.devnull, "w") as devnull: + with patch("sys.stderr", devnull): + with self.assertRaises(SystemExit): + cfnlint.config.CliArgs(["--non-zero-exit-code", "bad"]) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_config_file_args.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_config_file_args.py new file mode 100644 index 0000000000000000000000000000000000000000..86144086c732d1d7ec9ffcf1b61f358e60b4c92d --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_config_file_args.py @@ -0,0 +1,137 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import logging +from pathlib import Path +from test.testlib.testcase import BaseTestCase +from unittest.mock import patch + +import cfnlint.config # pylint: disable=E0401 +from cfnlint.jsonschema import ValidationError + +LOGGER = logging.getLogger("cfnlint") + + +class TestConfigFileArgs(BaseTestCase): + """Test ConfigParser Arguments""" + + def tearDown(self): + """Setup""" + for handler in LOGGER.handlers: + LOGGER.removeHandler(handler) + + def test_config_parser_read_config(self): + """Testing one file successful""" + config = cfnlint.config.ConfigFileArgs( + config_file=Path("test/fixtures/configs/cfnlintrc_read.yaml") + ) + self.assertEqual( + config.file_args, + { + "templates": ["test/fixtures/templates/good/**/*.yaml"], + "include_checks": ["I"], + }, + ) + + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_parser_read_config_only_one_read(self, yaml_mock): + """Testing one file successful""" + # Should only have one read here + # We aren't going to search and find the possible locations of + # cfnlintrc + yaml_mock.side_effect = [ + {"regions": ["us-west-1"]}, + ] + config = cfnlint.config.ConfigFileArgs( + config_file=Path("test/fixtures/configs/cfnlintrc_read.yaml") + ) + self.assertEqual(config.file_args, {"regions": ["us-west-1"]}) + + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_parser_read(self, yaml_mock): + """Testing one file successful""" + yaml_mock.side_effect = [{"regions": ["us-west-1"]}, {}] + results = cfnlint.config.ConfigFileArgs() + self.assertEqual(results.file_args, {"regions": ["us-west-1"]}) + + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_parser_read_merge(self, yaml_mock): + """test the merge of config""" + + yaml_mock.side_effect = [{"regions": ["us-west-1"]}, {"regions": ["us-east-1"]}] + + results = cfnlint.config.ConfigFileArgs() + self.assertEqual(results.file_args, {"regions": ["us-east-1"]}) + + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_parser_fail_on_bad_config(self, yaml_mock): + """test the read call to the config parser is reading two files""" + + yaml_mock.side_effect = [{"regions": True}, {}] + + with self.assertRaises(ValidationError): + cfnlint.config.ConfigFileArgs() + + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_parser_fail_on_config_rules(self, yaml_mock): + """ + test the read call to the config parser is + parsing configure rules correctly + """ + + yaml_mock.side_effect = [{"configure_rules": {"E3012": {"strict": False}}}, {}] + + results = cfnlint.config.ConfigFileArgs() + self.assertEqual( + results.file_args, {"configure_rules": {"E3012": {"strict": False}}} + ) + + @patch("pathlib.Path.is_file", create=True) + def test_config_parser_is_file_both(self, is_file_mock): + calls = [ + True, + True, + False, + False, + ] + is_file_mock.side_effect = calls + my_config = cfnlint.config.ConfigFileArgs() + self.assertEqual(my_config._user_config_file.name, ".cfnlintrc") + self.assertEqual(my_config._project_config_file.name, ".cfnlintrc") + self.assertEqual(is_file_mock.call_count, len(calls)) + + @patch("pathlib.Path.is_file", create=True) + def test_config_parser_is_file_both_yaml(self, is_file_mock): + calls = [ + False, + True, + False, + True, + False, + False, + ] + is_file_mock.side_effect = calls + my_config = cfnlint.config.ConfigFileArgs() + self.assertEqual(my_config._user_config_file.name, ".cfnlintrc.yaml") + self.assertEqual(my_config._project_config_file.name, ".cfnlintrc.yaml") + self.assertEqual(is_file_mock.call_count, len(calls)) + + @patch("pathlib.Path.is_file", create=True) + def test_config_parser_is_file_both_yml(self, is_file_mock): + calls = [ + False, + False, + True, + False, + False, + True, + False, + False, + ] + is_file_mock.side_effect = calls + my_config = cfnlint.config.ConfigFileArgs() + self.assertEqual(my_config._user_config_file.name, ".cfnlintrc.yml") + self.assertEqual(my_config._project_config_file.name, ".cfnlintrc.yml") + self.assertEqual(is_file_mock.call_count, len(calls)) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_config_mixin.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_config_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..f6b5abc59426d8ccd0164725aacba865d512478e --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_config_mixin.py @@ -0,0 +1,265 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import logging +import os +from pathlib import Path +from test.testlib.testcase import BaseTestCase +from unittest.mock import patch + +import cfnlint.config # pylint: disable=E0401 +from cfnlint.helpers import REGIONS + +LOGGER = logging.getLogger("cfnlint") + + +class TestConfigMixIn(BaseTestCase): + """Test ConfigParser Arguments""" + + def tearDown(self): + """Setup""" + for handler in LOGGER.handlers: + LOGGER.removeHandler(handler) + + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_mix_in(self, yaml_mock): + """Test mix in""" + yaml_mock.side_effect = [ + {"include_checks": ["I", "I1111"], "regions": ["us-west-2"]}, + {}, + ] + + config = cfnlint.config.ConfigMixIn(["--regions", "us-west-1"]) + self.assertEqual(config.regions, ["us-west-1"]) + self.assertEqual(config.include_checks, ["W", "E", "I", "I1111"]) + + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_precedence(self, yaml_mock): + """Test precedence in""" + + yaml_mock.side_effect = [ + { + "include_checks": ["I"], + "ignore_checks": ["E3001"], + "regions": ["us-west-2"], + }, + {}, + ] + config = cfnlint.config.ConfigMixIn(["--include-checks", "I1234", "I4321"]) + config.template_args = { + "Metadata": { + "cfn-lint": { + "config": {"include_checks": ["I9876"], "ignore_checks": ["W3001"]} + } + } + } + # config files wins + self.assertEqual(config.regions, ["us-west-2"]) + # CLI should win + self.assertEqual(config.include_checks, ["W", "E", "I1234", "I4321"]) + # template file wins over config file + self.assertEqual(config.ignore_checks, ["W3001"]) + + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_file_output(self, yaml_mock): + """Test precedence in""" + + yaml_mock.side_effect = [{"output_file": "test_output.txt"}, {}] + config = cfnlint.config.ConfigMixIn([]) + + # Config file wins + self.assertEqual(config.output_file, "test_output.txt") + + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_file_output_mixin(self, yaml_mock): + """Test precedence in""" + + yaml_mock.side_effect = [{"output_file": "test_output.txt"}, {}] + config = cfnlint.config.ConfigMixIn(["--output-file", "test_output_2.txt"]) + + # CLI args win + self.assertEqual(config.output_file, "test_output_2.txt") + + @patch.dict( + os.environ, + { + "HOME": os.environ.get("HOME", ""), + "USERPROFILE": os.environ.get("USERPROFILE", ""), + "HOMEPATH": os.environ.get("HOMEPATH", ""), + "HOMEDRIVE": os.environ.get("HOMEDRIVE", ""), + }, + clear=True, + ) + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_default_region(self, yaml_mock): + """Test precedence in""" + + yaml_mock.side_effect = [{}, {}] + config = cfnlint.config.ConfigMixIn([]) + + # test defaults + self.assertEqual(config.regions, ["us-east-1"]) + + @patch.dict( + os.environ, + { + "AWS_REGION": "us-west-2", + "AWS_DEFAULT_REGION": "us-west-1", + "HOME": os.environ.get("HOME", ""), + "USERPROFILE": os.environ.get("USERPROFILE", ""), + "HOMEPATH": os.environ.get("HOMEPATH", ""), + "HOMEDRIVE": os.environ.get("HOMEDRIVE", ""), + }, + clear=True, + ) + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_region_from_AWS_REGION_envvar(self, yaml_mock): + """Test precedence in""" + + yaml_mock.side_effect = [{}, {}] + config = cfnlint.config.ConfigMixIn([]) + + # test defaults + self.assertEqual(config.regions, ["us-west-2"]) + + @patch.dict( + os.environ, + { + "AWS_DEFAULT_REGION": "us-west-1", + "HOME": os.environ.get("HOME", ""), + "USERPROFILE": os.environ.get("USERPROFILE", ""), + "HOMEPATH": os.environ.get("HOMEPATH", ""), + "HOMEDRIVE": os.environ.get("HOMEDRIVE", ""), + }, + clear=True, + ) + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_region_from_AWS_DEFAULT_REGION_envvar(self, yaml_mock): + """Test precedence in""" + + yaml_mock.side_effect = [{}, {}] + config = cfnlint.config.ConfigMixIn([]) + + # test defaults + self.assertEqual(config.regions, ["us-west-1"]) + + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_all_regions(self, yaml_mock): + """Test precedence in""" + + yaml_mock.side_effect = [{"regions": ["ALL_REGIONS"]}, {}] + config = cfnlint.config.ConfigMixIn([]) + + # test defaults + self.assertEqual(config.regions, REGIONS) + + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_force_with_update_specs(self, yaml_mock): + """Test precedence in""" + + yaml_mock.side_effect = [{}, {}] + config = cfnlint.config.ConfigMixIn(["--update-specs", "--force"]) + + # test defaults + self.assertEqual(config.force, True) + self.assertEqual(config.update_specs, True) + + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_expand_paths(self, yaml_mock): + """Test precedence in""" + + yaml_mock.side_effect = [ + {"templates": ["test/fixtures/templates/public/*.yaml"]}, + {}, + ] + config = cfnlint.config.ConfigMixIn([]) + + # test defaults + self.assertEqual( + config.templates, + [ + str( + Path( + "test/fixtures/templates/public" + + os.path.sep + + "lambda-poller.yaml" + ) + ), + str( + Path( + "test/fixtures/templates/public" + + os.path.sep + + "rds-cluster.yaml" + ) + ), + ], + ) + + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_expand_paths_nomatch(self, yaml_mock): + """Test precedence in""" + + filename = "test/fixtures/templates/nonexistant/*.yaml" + yaml_mock.side_effect = [ + {"templates": [filename]}, + {}, + ] + config = cfnlint.config.ConfigMixIn([]) + + # test defaults + self.assertEqual(config.templates, []) + + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_expand_ignore_templates(self, yaml_mock): + """Test ignore templates""" + + yaml_mock.side_effect = [ + { + "templates": ["test/fixtures/templates/bad/resources/iam/*.yaml"], + "ignore_templates": [ + "test/fixtures/templates/bad/resources/iam/resource_*.yaml" + ], + }, + {}, + ] + config = cfnlint.config.ConfigMixIn([]) + + # test defaults + self.assertNotIn( + str(Path("test/fixtures/templates/bad/resources/iam/resource_policy.yaml")), + config.templates, + ) + self.assertEqual(len(config.templates), 3) + + @patch("cfnlint.config.ConfigFileArgs._read_config", create=True) + def test_config_merge(self, yaml_mock): + """Test merging lists""" + + yaml_mock.side_effect = [ + { + "include_checks": ["I"], + "ignore_checks": ["E3001"], + "regions": ["us-west-2"], + }, + {}, + ] + config = cfnlint.config.ConfigMixIn( + ["--include-checks", "I1234", "I4321", "--merge-configs"] + ) + config.template_args = { + "Metadata": { + "cfn-lint": { + "config": {"include_checks": ["I9876"], "ignore_checks": ["W3001"]} + } + } + } + # config files wins + self.assertEqual(config.regions, ["us-west-2"]) + # CLI should win + self.assertEqual( + config.include_checks, ["W", "E", "I1234", "I4321", "I9876", "I"] + ) + # template file wins over config file + self.assertEqual(config.ignore_checks, ["W3001", "E3001"]) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_logging.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..5a327373271983bf6041124ed4479bab1368aadf --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_logging.py @@ -0,0 +1,41 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import logging +from test.testlib.testcase import BaseTestCase + +import cfnlint.config # pylint: disable=E0401 + +LOGGER = logging.getLogger("cfnlint") + + +class TestLogging(BaseTestCase): + """Test Logging Arguments""" + + def tearDown(self): + """Setup""" + for handler in LOGGER.handlers: + LOGGER.removeHandler(handler) + + def test_logging_info(self): + """Test success run""" + + cfnlint.config.configure_logging(False, True) + self.assertEqual(logging.INFO, LOGGER.level) + self.assertEqual(len(LOGGER.handlers), 1) + + def test_logging_debug(self): + """Test debug level""" + + cfnlint.config.configure_logging(True, False) + self.assertEqual(logging.DEBUG, LOGGER.level) + self.assertEqual(len(LOGGER.handlers), 1) + + def test_no_logging(self): + """Test no logging level""" + + cfnlint.config.configure_logging(False, False) + self.assertEqual(logging.WARNING, LOGGER.level) + self.assertEqual(len(LOGGER.handlers), 1) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_template_args.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_template_args.py new file mode 100644 index 0000000000000000000000000000000000000000..08781e6b6b2d099ef23800aa71e287fd4992d095 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_template_args.py @@ -0,0 +1,105 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import logging +from test.testlib.testcase import BaseTestCase + +import cfnlint.config # pylint: disable=E0401 + +LOGGER = logging.getLogger("cfnlint") + + +class TestTempalteArgs(BaseTestCase): + """Test ConfigParser Arguments""" + + def tearDown(self): + """Setup""" + for handler in LOGGER.handlers: + LOGGER.removeHandler(handler) + + def test_template_args(self): + """test template args""" + config = cfnlint.config.TemplateArgs( + { + "Metadata": { + "cfn-lint": { + "config": { + "regions": ["us-east-1", "us-east-2"], + "ignore_checks": ["E2530"], + "configure_rules": {"E3012": {"strict": "false"}}, + } + } + } + } + ) + + self.assertEqual(config.template_args["regions"], ["us-east-1", "us-east-2"]) + self.assertEqual( + config.template_args["configure_rules"], {"E3012": {"strict": "false"}} + ) + + def test_template_args_failure_bad_format(self): + """test template args""" + config = cfnlint.config.TemplateArgs( + { + "Metadata": { + "cfn-lint": { + "config": {"configure_rules": [{"E3012": {"strict": "false"}}]} + } + } + } + ) + + self.assertEqual(config.template_args.get("configure_rules"), None) + + def test_template_args_failure_bad_value(self): + """test template args""" + config = cfnlint.config.TemplateArgs( + { + "Metadata": { + "cfn-lint": { + "config": { + "configure_rules": [{"E3012": {"bad_value": "false"}}] + } + } + } + } + ) + + self.assertEqual(config.template_args.get("configure_rules"), None) + + def test_template_args_failure_good_and_bad_value(self): + """test template args""" + config = cfnlint.config.TemplateArgs( + { + "Metadata": { + "cfn-lint": { + "config": { + "configure_rules": [ + { + "A1": {"strict": "false"}, + "E3012": {"strict": "false"}, + "Z1": {"strict": "false"}, + } + ] + } + } + } + } + ) + + self.assertEqual(config.template_args.get("configure_rules"), None) + + def test_bad_template_structure(self): + """test template args""" + config = cfnlint.config.TemplateArgs([]) + + self.assertEqual(config._template_args, {}) + + def test_bad_config_structure(self): + """test template args""" + config = cfnlint.config.TemplateArgs({"Metadata": {"cfn-lint": {"config": []}}}) + + self.assertEqual(config._template_args, {}) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/conditions/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/conditions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/conditions/test_conditions.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/conditions/test_conditions.py new file mode 100644 index 0000000000000000000000000000000000000000..a5e44e04829c6060df04a419082099a38713ba3c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/conditions/test_conditions.py @@ -0,0 +1,299 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import pytest + +from cfnlint.context import create_context_for_template +from cfnlint.context.conditions._conditions import Conditions +from cfnlint.context.conditions.exceptions import Unsatisfiable +from cfnlint.template import Template + + +def template(): + return { + "AWSTemplateFormatVersion": "2010-09-09", + "Parameters": { + "Environment": { + "Type": "String", + "Default": "dev", + "AllowedValues": ["dev", "prod"], + }, + "Name": { + "Type": "String", + "Default": "bi", + "AllowedValues": ["bi", "ai"], + }, + "AmiId": { + "Type": "String", + "Default": "", + }, + }, + "Conditions": { + "IsUsEast1": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]}, + "IsNotUsEast1": {"Fn::Not": [{"Condition": "IsUsEast1"}]}, + "IsUsWest2": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-west-2"]}, + "IsProd": {"Fn::Equals": [{"Ref": "Environment"}, "prod"]}, + "IsDev": {"Fn::Equals": [{"Ref": "Environment"}, "dev"]}, + "IsAmiProvided": {"Fn::Not": [{"Fn::Equals": [{"Ref": "AmiId"}, ""]}]}, + "IsAi": {"Fn::Equals": [{"Ref": "Name"}, "ai"]}, + "IsBi": {"Fn::Equals": [{"Ref": "Name"}, "bi"]}, + "IsUsEast1OrUsWest2": { + "Fn::Or": [ + {"Condition": "IsUsEast1"}, + {"Condition": "IsUsWest2"}, + ] + }, + "IsUsEast1AndProd": { + "Fn::And": [ + {"Condition": "IsUsEast1"}, + {"Condition": "IsProd"}, + ] + }, + "IsStaticTrue": {"Fn::Equals": [1, "1"]}, + "IsStaticFalse": {"Fn::Equals": [1, "2"]}, + "TwoObjects": { + "Fn::Equals": [ + {"Ref": "Environment"}, + {"Ref": "AWS::Region"}, + ] + }, + "TwoObjectsSameHash": { + "Fn::Equals": [ + {"Ref": "AWS::Region"}, + {"Ref": "Environment"}, + ] + }, + "BadAwsFn": {"Ref": "Foo"}, + "BadFn": {"Key": "Foo"}, + "BadNotList": {"Fn::And": "Foo"}, + "UseBadFn": {"Condition": "BadFn"}, + "UseBadCondition": {"Condition": []}, + "EqualsTooLong": {"Fn::Equals": ["a", "b", "c"]}, + "EqualsWrongTypes": {"Fn::Equals": ["a", []]}, + "NotWithTwoItems": { + "Fn::Not": [ + {"Condition": "IsAi"}, + {"Condition": "IsBi"}, + ] + }, + }, + } + + +def test_conditions(): + cfn = Template(None, template(), regions=["us-east-1"]) + context = create_context_for_template(cfn) + + assert len(context.conditions.conditions) == 22 + assert context.conditions.conditions["IsStaticTrue"].fn_equals.is_static is True + assert context.conditions.conditions["IsStaticFalse"].fn_equals.is_static is False + assert ( + context.conditions.conditions["TwoObjects"].fn_equals.hash + == context.conditions.conditions["TwoObjectsSameHash"].fn_equals.hash + ) + assert context.conditions.conditions["TwoObjects"].fn_equals.is_static is None + + for k in [ + "IsUsEast1", + "IsNotUsEast1", + "IsUsWest2", + "IsUsEast1OrUsWest2", + "IsUsEast1AndProd", + ]: + assert context.conditions.conditions[k].is_region is True + + for k in ["IsAmiProvided", "IsProd", "IsDev", "IsAi", "IsBi"]: + assert context.conditions.conditions[k].is_region is False + + for k in [ + "BadAwsFn", + "BadFn", + "BadNotList", + "UseBadCondition", + "EqualsTooLong", + "EqualsWrongTypes", + "NotWithTwoItems", + ]: + assert context.conditions.conditions[k].fn_equals.left.instance is None + assert context.conditions.conditions[k].fn_equals.right.instance is None + assert context.conditions.conditions[k].fn_equals.is_static is None + assert context.conditions.conditions[k].is_region is False + + assert ( + context.conditions.conditions["UseBadFn"].condition.fn_equals.left.instance + is None + ) + assert ( + context.conditions.conditions["UseBadFn"].condition.fn_equals.right.instance + is None + ) + assert ( + context.conditions.conditions["UseBadFn"].condition.fn_equals.is_static is None + ) + + +@pytest.mark.parametrize( + "current_status,new_status,expected", + [ + ({}, {}, {}), + ({"IsUsEast1": True}, {}, {"IsUsEast1": True}), + ( + {"IsUsEast1": True}, + {"IsUsEast1": False}, + Unsatisfiable( + new_status={"IsUsEast1": False}, current_status={"IsUsEast1": True} + ), + ), + ( + {"IsUsEast1": True}, + {"IsNotUsEast1": True}, + Unsatisfiable( + new_status={"IsNotUsEast1": True}, + current_status={"IsUsEast1": True}, + ), + ), + ( + {"IsUsEast1": False, "IsUsWest2": False}, + {"IsUsEast1OrUsWest2": True}, + Unsatisfiable( + new_status={"IsUsEast1OrUsWest2": True}, + current_status={"IsUsEast1": True}, + ), + ), + ( + {"IsDev": False}, + {"IsProd": False}, + Unsatisfiable(new_status={"IsProd": False}, current_status={"IsDev": True}), + ), + ({}, {"BadFn": True}, {"BadFn": True}), + ({}, {"BadFn": False}, {"BadFn": False}), + ], +) +def test_condition_status(current_status, new_status, expected): + cfn = Template(None, template(), regions=["us-east-1"]) + context = create_context_for_template(cfn) + + context = context.evolve(conditions=context.conditions.evolve(current_status)) + + if isinstance(expected, Exception): + with pytest.raises(ValueError): + context.conditions.evolve(new_status) + else: + context = context.evolve(conditions=context.conditions.evolve(new_status)) + assert context.conditions.status == expected + + +@pytest.mark.parametrize( + "current_status,instance,expected", + [ + ({}, {"Foo": "Bar"}, [({"Foo": "Bar"}, {})]), + ( + {}, + {"Fn::If": ["IsUsEast1", {"Foo": "Foo"}, {"Bar": "Bar"}]}, + [ + ({"Foo": "Foo"}, {"IsUsEast1": True}), + ({"Bar": "Bar"}, {"IsUsEast1": False}), + ], + ), + ( + { + "IsUsEast1": True, + }, + {"Fn::If": ["IsUsEast1", {"Foo": "Foo"}, {"Bar": "Bar"}]}, + [ + ({"Foo": "Foo"}, {"IsUsEast1": True}), + ], + ), + ( + { + "IsUsEast1": False, + }, + {"Fn::If": ["IsUsEast1", {"Foo": "Foo"}, {"Bar": "Bar"}]}, + [ + ({"Bar": "Bar"}, {"IsUsEast1": False}), + ], + ), + ( + {}, + {"Ref": "AWS::NoValue"}, + [ + (None, {}), + ], + ), + ( + {}, + [{"Foo": {"Fn::If": ["IsUsEast1", "Foo", "Bar"]}}], + [ + ([{"Foo": {"Fn::If": ["IsUsEast1", "Foo", "Bar"]}}], {}), + ], + ), + ( + {}, + [{"Fn::If": ["IsUsEast1", {"Foo": "Bar"}, {"Ref": "AWS::NoValue"}]}], + [ + ([{"Foo": "Bar"}], {"IsUsEast1": True}), + ([], {"IsUsEast1": False}), + ], + ), + ( + {"IsUsEast1": True, "IsProd": True}, + { + "A": {"Fn::If": ["IsUsEast1AndProd", 1, 2]}, + "B": {"Fn::If": ["IsAi", 10, 11]}, + }, + [ + ( + {"A": 1, "B": 10}, + { + "IsUsEast1": True, + "IsProd": True, + "IsUsEast1AndProd": True, + "IsAi": True, + }, + ), + ( + {"A": 1, "B": 11}, + { + "IsUsEast1": True, + "IsProd": True, + "IsUsEast1AndProd": True, + "IsAi": False, + }, + ), + ], + ), + ( + {}, + { + "A": {"Fn::If": ["IsUsEast1AndProd", 1]}, + }, + [ + ( + {"A": {"Fn::If": ["IsUsEast1AndProd", 1]}}, + {}, + ), + ], + ), + ], +) +def test_evolve_from_instance(current_status, instance, expected): + cfn = Template(None, template(), regions=["us-east-1"]) + context = create_context_for_template(cfn) + + context = context.evolve( + conditions=context.conditions.evolve(current_status), + functions=["Fn::If", "Ref"], + ) + + results = list(context.conditions.evolve_from_instance(instance, context)) + assert len(results) == len(expected) + for result, expected_result in zip(results, expected): + assert result[0] == expected_result[0] + assert result[1].status == expected_result[1] + + +def test_condition_failures(): + with pytest.raises(ValueError): + Conditions.create_from_instance([], {}, {}) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/conditions/test_equals_sort.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/conditions/test_equals_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..38eb72a5362918495863df2940252507594ee697 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/conditions/test_equals_sort.py @@ -0,0 +1,105 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import pytest + +from cfnlint.context.conditions._equals import _equals_cmp_key + + +@pytest.mark.parametrize( + "name,instance,expected", + [ + ( + "Valid", + [ + "A", + "B", + {"Ref": "A"}, + {"Ref": "B"}, + {"Key": "Value"}, + {"Fn::FindInMap": ["A", "B", "C"]}, + {"Fn::FindInMap": ["X", "Y", "Z"]}, + ], + [ + "A", + "B", + {"Fn::FindInMap": ["X", "Y", "Z"]}, + {"Fn::FindInMap": ["A", "B", "C"]}, + {"Ref": "A"}, + {"Ref": "B"}, + {"Key": "Value"}, + ], + ), + ( + "Different order same results", + [ + {"Fn::FindInMap": ["A", "B", "C"]}, + {"Fn::FindInMap": ["X", "Y", "Z"]}, + {"Ref": "B"}, + {"Ref": "A"}, + {"Key": "Value"}, + "B", + "A", + ], + [ + "A", + "B", + {"Fn::FindInMap": ["X", "Y", "Z"]}, + {"Fn::FindInMap": ["A", "B", "C"]}, + {"Ref": "A"}, + {"Ref": "B"}, + {"Key": "Value"}, + ], + ), + ( + "Two Refs", + [ + {"Ref": "B"}, + {"Ref": "A"}, + ], + [ + {"Ref": "A"}, + {"Ref": "B"}, + ], + ), + ( + "Ref with non mapping", + [ + {"Ref": "A"}, + {"Key": "Value"}, + ], + [ + {"Ref": "A"}, + {"Key": "Value"}, + ], + ), + ( + "Ref with non mapping backwards", + [ + {"Key": "Value"}, + {"Ref": "A"}, + ], + [ + {"Ref": "A"}, + {"Key": "Value"}, + ], + ), + ( + "None functions", + [ + {"Key": "Foo"}, + {"Key": "Bar"}, + ], + [ + {"Key": "Foo"}, + {"Key": "Bar"}, + ], + ), + ], +) +def test_sorted(name, instance, expected): + assert expected == sorted( + instance, key=_equals_cmp_key + ), f"{name} got {sorted(instance, key=_equals_cmp_key)}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_context.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_context.py new file mode 100644 index 0000000000000000000000000000000000000000..557be9b341fec2ccf1e7ac011bd8533cbc234d23 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_context.py @@ -0,0 +1,108 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import unittest +from collections import deque + +from cfnlint.context import Context, Path +from cfnlint.context.conditions._conditions import Condition, Conditions + + +class TestCfnContext(unittest.TestCase): + def test_class(self): + context = Context( + conditions=Conditions.create_from_instance( + conditions={ + "Foo": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]}, + "Bar": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-west-2"]}, + }, + rules={}, + parameters={}, + ), + ) + self.assertEqual(context.regions, ["us-east-1"]) + self.assertEqual( + context.conditions, + Conditions( + { + "Foo": Condition.create_from_instance( + {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]}, {} + ), + "Bar": Condition.create_from_instance( + {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-west-2"]}, {} + ), + }, + ), + ) + self.assertEqual(context.path, Path()) + + # Test evolve + evolved = context.evolve( + regions=["us-west-2"], + conditions=context.conditions.evolve( + {"Foo": False}, + ), + path=Path(path=deque([1])), + ) + self.assertListEqual(evolved.regions, ["us-west-2"]) + self.assertDictEqual( + evolved.conditions.status, + { + "Foo": False, + }, + ) + self.assertEqual(evolved.path.path, deque([1])) + + evolved_again = evolved.evolve( + path=evolved.path.descend(path=2), + conditions=evolved.conditions.evolve( + {"Bar": True}, + ), + ) + self.assertListEqual(evolved_again.regions, ["us-west-2"]) + self.assertDictEqual( + evolved_again.conditions.status, {"Foo": False, "Bar": True} + ) + self.assertEqual(evolved_again.path.path, deque([1, 2])) + # no changes to the original + self.assertListEqual(context.regions, ["us-east-1"]) + self.assertEqual( + context.conditions, + Conditions( + { + "Foo": Condition.create_from_instance( + {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]}, {} + ), + "Bar": Condition.create_from_instance( + {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-west-2"]}, {} + ), + } + ), + ) + self.assertEqual(context.path.path, deque()) + + no_path = context.evolve(regions=["us-east-2"]) + self.assertListEqual(no_path.regions, ["us-east-2"]) + self.assertEqual( + no_path.conditions, + Conditions( + { + "Foo": Condition.create_from_instance( + {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]}, {} + ), + "Bar": Condition.create_from_instance( + {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-west-2"]}, {} + ), + } + ), + ) + self.assertEqual(no_path.path.path, deque()) + + with self.assertRaises(ValueError): + evolved_again.evolve( + conditions=evolved_again.conditions.evolve( + {"Foo": True}, + ), + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_create_context.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_create_context.py new file mode 100644 index 0000000000000000000000000000000000000000..4b798b997f9b0a53079eb4170eae74d1caa9b331 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_create_context.py @@ -0,0 +1,115 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import namedtuple + +import pytest + +from cfnlint import Template +from cfnlint.context.context import create_context_for_template + +_Counts = namedtuple("_Counts", ["resources", "parameters", "conditions", "mappings"]) + + +@pytest.mark.parametrize( + "name,instance,counts", + [ + ( + "Valid template", + { + "Parameters": { + "Env": { + "Type": "String", + } + }, + "Conditions": { + "IsUsEast1": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]} + }, + "Mappings": {"Map": {"us-east-1": {"foo": "bar"}}}, + "Resources": { + "Bucket": { + "Type": "AWS::S3::Bucket", + }, + }, + }, + _Counts(resources=1, parameters=1, conditions=1, mappings=1), + ), + ( + "Bad types in template", + { + "Parameters": [], + "Conditions": [], + "Mappings": [], + "Resources": [], + }, + _Counts(resources=0, parameters=0, conditions=0, mappings=0), + ), + ( + "Invalid type configurations", + { + "Parameters": { + "BusinessUnit": [], + "Env": { + "Type": "String", + }, + }, + "Mappings": {"AnotherMap": [], "Map": {"us-east-1": {"foo": "bar"}}}, + "Resources": { + "Instance": [], + "Bucket": { + "Type": "AWS::S3::Bucket", + }, + }, + }, + _Counts(resources=1, parameters=1, conditions=0, mappings=2), + ), + ( + "Invalid mapping second key", + { + "Mappings": { + "BadKey": { + "Foo": [], + }, + "Map": {"us-east-1": {"foo": "bar"}}, + }, + }, + _Counts(resources=0, parameters=0, conditions=0, mappings=2), + ), + ( + "Invalid mapping third key", + { + "Mappings": { + "BadKey": { + "Foo": { + "Bar": {}, + }, + }, + "Map": {"us-east-1": {"foo": "bar"}}, + }, + }, + _Counts(resources=0, parameters=0, conditions=0, mappings=2), + ), + ], +) +def test_create_context(name, instance, counts): + cfn = Template("", instance, ["us-east-1"]) + context = create_context_for_template(cfn) + + for i in counts._fields: + if i == "conditions": + assert len(context.conditions.conditions) == getattr(counts, i), ( + f"Test {name} has {i} {len(getattr(context, i))} " + f"and expected {getattr(counts, i)}" + ) + elif i == "mappings": + assert len(context.mappings.maps) == getattr(counts, i), ( + f"Test {name} has {i} {len(context.mappings.maps)} " + f"and expected {getattr(counts, i)}" + ) + else: + assert len(getattr(context, i)) == getattr(counts, i), ( + f"Test {name} has {i} {len(getattr(context, i))} " + f"and expected {getattr(counts, i)}" + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_mappings.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_mappings.py new file mode 100644 index 0000000000000000000000000000000000000000..510eaada9a24e2079b1eb4872acc96d68ef5e0de --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_mappings.py @@ -0,0 +1,103 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import pytest + +from cfnlint.context._mappings import Map, Mappings, _MappingSecondaryKey + + +@pytest.mark.parametrize( + "name,get_key_1,get_key_2,expected", + [ + ("Valid get", "A", "B", ["C"]), + ("Invalid first key", "B", "B", KeyError()), + ("Invalid second key", "A", "C", KeyError()), + ], +) +def test_mapping_value(name, get_key_1, get_key_2, expected): + mapping = Map.create_from_dict({"A": {"B": "C"}}) + + if isinstance(expected, Exception): + with pytest.raises(type(expected)): + list(mapping.find_in_map(get_key_1, get_key_2)) + else: + assert list(mapping.find_in_map(get_key_1, get_key_2)) == expected + + +def test_transforms(): + mapping = Map.create_from_dict({"A": {"Fn::Transform": "C"}}) + + assert mapping.keys.get("A").is_transform is True + + mapping = Map.create_from_dict({"Fn::Transform": {"B": "C"}}) + + assert mapping.is_transform is True + + mapping = Mappings.create_from_dict({"Fn::Transform": {"B": {"C": "D"}}}) + + assert mapping.is_transform is True + + +@pytest.mark.parametrize( + "name,mappings,expected", + [ + ( + "Valid mappings", + { + "A": {"B": {"C": "D"}}, + "1": {"2": {"3": "4"}}, + "Z": [], + "9": {"8": []}, + "M": {"N": {"O": {"P": "Q"}}}, + }, + Mappings( + { + "A": Map({"B": _MappingSecondaryKey({"C": "D"})}), + "1": Map({"2": _MappingSecondaryKey({"3": "4"})}), + "Z": Map({}), + "9": Map({"8": _MappingSecondaryKey({})}), + "M": Map({"N": _MappingSecondaryKey({})}), + } + ), + ), + ( + "Valid mappings with transforms", + { + "A": {"Fn::Transform": "MyTransform"}, + "1": {"2": {"Fn::Transform": "MyTransform"}}, + }, + Mappings( + { + "A": Map({}, True), + "1": Map({"2": _MappingSecondaryKey({}, True)}), + } + ), + ), + ( + "Valid mappings with transforms for mappings", + { + "Fn::Transform": "MyTransform", + }, + Mappings({}, True), + ), + ( + "Invalid mappings with wrong types", + { + "A": {True: {"C": "foo"}}, + "1": {"2": {False: "foo"}}, + }, + Mappings( + { + "A": Map({}, False), + "1": Map({"2": _MappingSecondaryKey({}, False)}), + } + ), + ), + ], +) +def test_mapping_creation(name, mappings, expected): + results = Mappings.create_from_dict(mappings) + + assert results == expected, f"{name!r} failed got {results!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_parameter.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_parameter.py new file mode 100644 index 0000000000000000000000000000000000000000..e081f418e928d30c486375bac275e2c66024099b --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_parameter.py @@ -0,0 +1,137 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.context import Context +from cfnlint.context.context import Parameter, _init_parameters + + +@pytest.mark.parametrize( + "name,instance,expected_type,expected_ref", + [ + ("Valid string parameter", {"Type": "string"}, "string", []), + ( + "Valid parameter with default and allowed values", + { + "Type": "String", + "Default": "foo", + "AllowedValues": [ + "foo", + "bar", + ], + }, + "String", + [ + ("foo", deque(["AllowedValues", 0])), + ("bar", deque(["AllowedValues", 1])), + ], + ), + ( + "Valid parameter with a CommaDelimitedList", + { + "Type": "CommaDelimitedList", + "Default": "foo", + }, + "CommaDelimitedList", + [ + (["foo"], deque(["Default"])), + ], + ), + ( + "Valid parameter with a List of Numbers", + { + "Type": "List", + "Default": "10,20", + }, + "List", + [(["10", "20"], deque(["Default"]))], + ), + ( + "Valid parameter with a List of numbers for allowed values", + { + "Type": "List", + "AllowedValues": ["10,20"], + }, + "List", + [(["10", "20"], deque(["AllowedValues", 0]))], + ), + ( + "Valid parameter with a SSM Parameter", + { + "Type": "AWS::SSM::Parameter::Value", + "Default": "foo", + }, + "AWS::SSM::Parameter::Value", + [], + ), + ( + "Valid parameter with a MinValue and MaxValue", + {"Type": "Number", "MinValue": "10", "MaxValue": "20"}, + "Number", + [("10", deque(["MinValue"])), ("20", deque(["MaxValue"]))], + ), + ( + "Valid list parameter with an integer value", + {"Type": "List", "Default": 10}, + "List", + [(["10"], deque(["Default"]))], + ), + ( + "Valid list parameter with an integer value", + {"Type": "List", "AllowedValues": [10]}, + "List", + [(["10"], deque(["AllowedValues", 0]))], + ), + ], +) +def test_parameter(name, instance, expected_type, expected_ref): + context = Context(["us-east-1"]) + parameter = Parameter(instance) + + assert expected_type == parameter.type + assert expected_ref == list( + parameter.ref(context) + ), f"{name!r} test got {list(parameter.ref(context))}" + + +@pytest.mark.parametrize( + "name,instance,expected", + [ + ("Valid string parameter", {"Type": "string"}, False), + ( + "Valid string parameter with no echo string", + {"Type": "string", "NoEcho": "true"}, + True, + ), + ( + "Valid string parameter with no echo boolean", + {"Type": "string", "NoEcho": True}, + True, + ), + ], +) +def test_no_echo(name, instance, expected): + parameter = Parameter(instance) + + assert expected == parameter.no_echo, f"{name} failed got {parameter.no_echo}" + + +@pytest.mark.parametrize( + "name,instance", + [ + ("Invalid Type", {"Type": {}}), + ], +) +def test_errors(name, instance): + with pytest.raises(ValueError): + Parameter(instance) + + +def test_parameters(): + with pytest.raises(ValueError): + _init_parameters([]) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_path.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_path.py new file mode 100644 index 0000000000000000000000000000000000000000..fd8b7c463f5be14f87b0a15c928398667d30636f --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_path.py @@ -0,0 +1,54 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.context.context import Path + + +@pytest.mark.parametrize( + "name,params,expected", + [ + ( + "Proper descend", + { + "path": "Property", + "cfn_path": "Property", + "value_path": "Property", + }, + Path( + path=deque(["Property"]), + cfn_path=deque(["Property"]), + value_path=deque(["Property"]), + ), + ), + ( + "Exception on using function", + { + "path": "Foo", + "cfn_path": "Fn::If", + }, + ValueError(), + ), + ( + "Exception on using int", + { + "path": "Foo", + "cfn_path": 1, + }, + ValueError(), + ), + ], +) +def test_path_descend(name, params, expected): + path = Path() + if isinstance(expected, Exception): + with pytest.raises(type(expected)): + path.descend(**params) + else: + path = path.descend(**params) + assert path == expected diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_resource.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_resource.py new file mode 100644 index 0000000000000000000000000000000000000000..582b054e434d3350f981c7d054705948d82054a5 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_resource.py @@ -0,0 +1,40 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import pytest + +from cfnlint.context import Context +from cfnlint.context.context import Resource, _init_resources + + +@pytest.mark.parametrize( + "name,instance,expected_ref", + [ + ("Valid resource", {"Type": "AWS::S3::Bucket"}, []), + ], +) +def test_resource(name, instance, expected_ref): + context = Context(["us-east-1"]) + parameter = Resource(instance) + + assert expected_ref == list( + parameter.ref(context) + ), f"{name!r} test got {list(parameter.ref(context))}" + + +@pytest.mark.parametrize( + "name,instance", + [ + ("Invalid Type", {"Type": {}}), + ], +) +def test_errors(name, instance): + with pytest.raises(ValueError): + Resource(instance) + + +def test_resources(): + with pytest.raises(ValueError): + _init_resources([]) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_transforms.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..451e9c85665717ab9f7b4dfd686fc948a816d649 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_transforms.py @@ -0,0 +1,29 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import pytest + +from cfnlint.context.context import Transforms + + +@pytest.mark.parametrize( + "name,instance,expected", + [ + ("Valid transforms", "AWS::LanguageExtensions", True), + ( + "Valid transforms lists", + ["AWS::LanguageExtensions", {"Name": "Include"}], + True, + ), + ("Valid transforms lists", None, False), + ("Valid transforms lists", "", False), + ], +) +def test_transforms(name, instance, expected): + transforms = Transforms(instance) + + assert ( + expected == transforms.has_language_extensions_transform() + ), f"{name!r} test got {transforms.has_language_extensions_transform()}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/custom_rules/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/custom_rules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/custom_rules/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/custom_rules/test_custom_rules.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/custom_rules/test_custom_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..4a863a9bd42c8c2e89152bfee2f1c97966fbc23b --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/custom_rules/test_custom_rules.py @@ -0,0 +1,146 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase + +import cfnlint.decode.cfn_yaml # pylint: disable=E0401 +from cfnlint import ConfigMixIn +from cfnlint.config import _DEFAULT_RULESDIR +from cfnlint.rules import Rules +from cfnlint.runner import TemplateRunner + + +class TestCustomRuleParsing(BaseTestCase): + """Test Node Objects""" + + def setUp(self): + """SetUp template object""" + self.rules = Rules() + rulesdirs = [_DEFAULT_RULESDIR] + for rulesdir in rulesdirs: + self.rules.create_from_directory(rulesdir) + + self.filenames = { + "generic_good": {"filename": "test/fixtures/templates/good/generic.yaml"} + } + + self.perfect_rule = "test/fixtures/custom_rules/good/custom_rule_perfect.txt" + self.valid_boolean = "test/fixtures/custom_rules/good/custom_rule_boolean.txt" + self.invalid_boolean = ( + "test/fixtures/custom_rules/bad/custom_rule_invalid_boolean.txt" + ) + self.invalid_op = "test/fixtures/custom_rules/bad/custom_rule_invalid_op.txt" + self.invalid_prop = ( + "test/fixtures/custom_rules/bad/custom_rule_invalid_prop.txt" + ) + self.invalid_propkey = ( + "test/fixtures/custom_rules/bad/custom_rule_invalid_propkey.txt" + ) + self.invalid_rt = "test/fixtures/custom_rules/bad/custom_rule_invalid_rt.txt" + self.invalid_equal = ( + "test/fixtures/custom_rules/bad/custom_rule_invalid_equal.txt" + ) + self.invalid_not_equal = ( + "test/fixtures/custom_rules/bad/custom_rule_invalid_not_equal.txt" + ) + self.invalid_set = "test/fixtures/custom_rules/bad/custom_rule_invalid_set.txt" + self.invalid_not_set = ( + "test/fixtures/custom_rules/bad/custom_rule_invalid_not_set.txt" + ) + self.invalid_greater_than = ( + "test/fixtures/custom_rules/bad/custom_rule_invalid_greater_than.txt" + ) + self.invalid_less_than = ( + "test/fixtures/custom_rules/bad/custom_rule_invalid_less_than.txt" + ) + self.invalid_regex = ( + "test/fixtures/custom_rules/bad/custom_rule_invalid_regex.txt" + ) + + def test_perfect_parse(self): + """Test Successful Custom_Rule Parsing""" + assert self.run_tests(self.perfect_rule) == [] + + def test_invalid_op(self): + """Test Successful Custom_Rule Parsing""" + assert self.run_tests(self.invalid_op)[0].message.find("not in supported") > -1 + + def test_invalid_set(self): + """Test Successful Custom_Rule Parsing""" + assert self.run_tests(self.invalid_set)[0].message.find("In set check") > -1 + + def test_invalid_not_set(self): + """Test Successful Custom_Rule Parsing""" + assert self.run_tests(self.invalid_not_set)[0].message.find("Not in set") > -1 + + def test_invalid_equal(self): + """Test Successful Custom_Rule Parsing""" + assert ( + self.run_tests(self.invalid_equal)[0].message.find("Must equal check") > -1 + ) + + def test_invalid_not_equal(self): + """Test Successful Custom_Rule Parsing""" + assert ( + self.run_tests(self.invalid_not_equal)[0].message.find("Must not equal") + > -1 + ) + + def test_invalid_greater_than(self): + """Test Successful Custom_Rule Parsing""" + assert ( + self.run_tests(self.invalid_greater_than)[0].message.find( + "Greater than check" + ) + > -1 + ) + + def test_invalid_less_than(self): + """Test Successful Custom_Rule Parsing""" + assert ( + self.run_tests(self.invalid_less_than)[0].message.find("Lesser than check") + > -1 + ) + + def test_invalid_regex(self): + """Test Successful Custom_Rule Parsing""" + assert ( + self.run_tests(self.invalid_regex)[0].message.find("Regex does not match") + > -1 + ) + + def test_valid_boolean_value(self): + """Test Boolean values""" + assert self.run_tests(self.valid_boolean) == [] + + def test_invalid_boolean_value(self): + """Test Boolean values""" + assert ( + self.run_tests(self.invalid_boolean)[0].message.find( + "Must equal check failed" + ) + > -1 + ) + + def test_invalid_prop(self): + """Test Successful Custom_Rule Parsing""" + assert self.run_tests(self.invalid_prop) == [] + + def test_invalid_propKey(self): + """Test Successful Custom_Rule Parsing""" + assert self.run_tests(self.invalid_propkey) == [] + + def test_invalid_resource_type(self): + """Test Successful Custom_Rule Parsing""" + assert self.run_tests(self.invalid_rt) == [] + + def run_tests(self, rulename): + for _, values in self.filenames.items(): + filename = values.get("filename") + template = cfnlint.decode.cfn_yaml.load(filename) + rules = Rules() + rules.update(rules.create_from_custom_rules_file(rulename)) + runner = TemplateRunner(filename, template, ConfigMixIn({}), rules) + return list(runner.run()) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/decode/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/decode/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/decode/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/decode/test_convert_dict.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/decode/test_convert_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..1c0fec059b381ef6b58735bc963298d21db55d75 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/decode/test_convert_dict.py @@ -0,0 +1,25 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase + +from cfnlint.decode import convert_dict +from cfnlint.decode.node import dict_node, list_node, str_node + + +class TestConvertDict(BaseTestCase): + """Test Converting regular dicts into CFN Dicts""" + + def test_success_run(self): + """Test success run""" + obj = {"Key": {"SubKey": "Value"}, "List": [{"SubKey": "AnotherValue"}]} + + results = convert_dict(obj) + self.assertTrue(isinstance(results, dict_node)) + self.assertTrue(isinstance(results.get("Key"), dict_node)) + self.assertTrue(isinstance(results.get("List")[0], dict_node)) + self.assertTrue(isinstance(results.get("List"), list_node)) + for k, _ in results.items(): + self.assertTrue(isinstance(k, str_node)) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/decode/test_decode.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/decode/test_decode.py new file mode 100644 index 0000000000000000000000000000000000000000..c00d6475034348de0c098c370bc5a0336df0bfbe --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/decode/test_decode.py @@ -0,0 +1,144 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import json +import logging +from test.testlib.testcase import BaseTestCase +from unittest.mock import patch + +import yaml +from yaml.scanner import ScannerError + +import cfnlint.decode.cfn_json +import cfnlint.decode.cfn_yaml +import cfnlint.decode.decode + + +class TestDecode(BaseTestCase): + def tearDown(self) -> None: + super().tearDown() + logger = logging.getLogger("cfnlint.decode.decode") + logger.disabled = False + + def setUp(self): + """Setup""" + logger = logging.getLogger("cfnlint.decode.decode") + logger.disabled = True + + @patch("cfnlint.decode.cfn_yaml.load") + def test_decode_permission_error(self, mock_cfn_yaml): + mock_cfn_yaml.side_effect = OSError(13, "Permission denied") + _, matches = cfnlint.decode.decode(filename="test") + self.assertEqual(len(matches), 1) + self.assertEqual(matches[0].rule.id, "E0000") + + @patch("cfnlint.decode.cfn_yaml.load") + def test_decode_unicode_error(self, mock_cfn_yaml): + mock_cfn_yaml.side_effect = UnicodeDecodeError("", b"\x00\x00", 0, 0, "reason") + _, matches = cfnlint.decode.decode(filename="test") + self.assertEqual(len(matches), 1) + self.assertEqual(matches[0].rule.id, "E0000") + + @patch("cfnlint.decode.cfn_yaml.load") + def test_decode_scanner_error_other(self, mock_cfn_yaml): + mock_cfn_yaml.side_effect = ScannerError( + problem="foo", problem_mark=yaml.Mark("test", 0, 0, 0, "", 0) + ) + _, matches = cfnlint.decode.decode(filename="test") + self.assertEqual(len(matches), 1) + self.assertEqual(matches[0].rule.id, "E0000") + self.assertEqual(matches[0].message, "foo") + + @patch("cfnlint.decode.cfn_yaml.load") + @patch("cfnlint.decode.cfn_json.load") + def test_decode_scanner_error_tab(self, mock_cfn_json, mock_cfn_yaml): + mock_cfn_json.return_value = {} + mock_cfn_yaml.side_effect = ScannerError( + problem="found character '\\t' that cannot start any token" + ) + _, matches = cfnlint.decode.decode("test") + self.assertListEqual(matches, []) + mock_cfn_json.assert_called_once() + + @patch("cfnlint.decode.cfn_yaml.load") + @patch("cfnlint.decode.cfn_json.load") + def test_decode_json_decoder_no_json_error(self, mock_cfn_json, mock_cfn_yaml): + mock_cfn_json.side_effect = json.JSONDecodeError( + "No JSON object could be decoded", "", 0 + ) + mock_cfn_yaml.side_effect = ScannerError( + problem="found character '\\t' that cannot start any token", + problem_mark=yaml.Mark("test", 0, 0, 0, "", 0), + ) + _, matches = cfnlint.decode.decode("test") + self.assertEqual(len(matches), 1) + self.assertEqual(matches[0].rule.id, "E0000") + + @patch("cfnlint.decode.cfn_yaml.load") + @patch("cfnlint.decode.cfn_json.load") + def test_decode_json_decoder_exception_error(self, mock_cfn_json, mock_cfn_yaml): + mock_cfn_json.side_effect = Exception("foo") + mock_cfn_yaml.side_effect = ScannerError( + problem="found character '\\t' that cannot start any token", + problem_mark=yaml.Mark("test", 0, 0, 0, "", 0), + ) + _, matches = cfnlint.decode.decode("test") + self.assertEqual(len(matches), 1) + self.assertEqual(matches[0].rule.id, "E0000") + self.assertEqual( + matches[0].message, "Tried to parse test as JSON but got error: foo" + ) + + @patch("cfnlint.decode.cfn_yaml.load") + @patch("cfnlint.decode.cfn_json.load") + def test_decode_json_decoder_expecting_value_error( + self, mock_cfn_json, mock_cfn_yaml + ): + mock_cfn_json.side_effect = json.JSONDecodeError("Expecting value", "", 0) + mock_cfn_yaml.side_effect = ScannerError( + problem="found character '\\t' that cannot start any token", + problem_mark=yaml.Mark("test", 0, 99, 0, "", 0), + ) + _, matches = cfnlint.decode.decode("test") + self.assertEqual(len(matches), 1) + self.assertEqual(matches[0].rule.id, "E0000") + self.assertEqual(matches[0].linenumber, 100) + + @patch("cfnlint.decode.cfn_yaml.load") + @patch("cfnlint.decode.cfn_json.load") + def test_decode_json_decoder_error(self, mock_cfn_json, mock_cfn_yaml): + err_msg = "Foo" + mock_cfn_json.side_effect = json.JSONDecodeError(err_msg, "", 0) + mock_cfn_yaml.side_effect = ScannerError( + problem="found character '\\t' that cannot start any token" + ) + _, matches = cfnlint.decode.decode("test") + self.assertEqual(len(matches), 1) + self.assertEqual(matches[0].rule.id, "E0000") + self.assertEqual(matches[0].message, "Foo") + + @patch("cfnlint.decode.cfn_yaml.load") + def test_decode_yaml_error(self, mock_cfn_yaml): + err_msg = "Foo" + mock_cfn_yaml.side_effect = yaml.YAMLError(err_msg) + _, matches = cfnlint.decode.decode("test") + self.assertEqual(len(matches), 1) + self.assertEqual(matches[0].rule.id, "E0000") + self.assertEqual(matches[0].message, err_msg) + + def test_decode_yaml_null_key(self): + err_msg = "Null key 'null' not supported (line 3)" + with self.assertRaises(cfnlint.decode.cfn_yaml.CfnParseError) as e: + cfnlint.decode.cfn_yaml.loads( + """ + Parameters: + null: test + """ + ) + self.assertEqual(str(e.exception), err_msg) + + def test_decode_yaml_empty(self): + template = cfnlint.decode.cfn_yaml.loads("") + self.assertEqual(template, {}) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/formatters/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/formatters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/formatters/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/formatters/test_formatters.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/formatters/test_formatters.py new file mode 100644 index 0000000000000000000000000000000000000000..6e89b495790e3f8f592e83985c75fe41d7b3663a --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/formatters/test_formatters.py @@ -0,0 +1,332 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import json +import sys +from pathlib import Path +from test.testlib.testcase import BaseTestCase + +import defusedxml.ElementTree as ET + +import cfnlint.config +import cfnlint.formatters +import cfnlint.helpers +from cfnlint import ConfigMixIn +from cfnlint.formatters import ( + Formatter, + JsonFormatter, + JUnitFormatter, + ParseableFormatter, + PrettyFormatter, + QuietFormatter, + SARIFFormatter, +) +from cfnlint.jsonschema import StandardValidator +from cfnlint.rules import Match, Rules +from cfnlint.rules.functions.SubUnneeded import SubUnneeded +from cfnlint.rules.resources.properties.Type import Type +from cfnlint.rules.resources.UpdateReplacePolicyDeletionPolicyOnStatefulResourceTypes import ( + UpdateReplacePolicyDeletionPolicyOnStatefulResourceTypes, +) + + +class TestFormatters(BaseTestCase): + """Test Formatters""" + + def setUp(self) -> None: + super().setUp() + self.rules = Rules.create_from_directory(cfnlint.config._DEFAULT_RULESDIR) + self.filename = str(Path("test/fixtures/templates/bad/formatters.yaml")) + self.sarif_schema = str(Path("test/fixtures/schemas/sarif/schema-2.1.0.json")) + self.config = ConfigMixIn( + cli_args=[ + "--include-checks", + "I", + "--ignore-checks", + "E1029", + "--", + self.filename, + ] + ) + + self.results = [ + Match( + linenumber=6, + columnnumber=3, + linenumberend=6, + columnnumberend=10, + filename=self.filename, + rule=UpdateReplacePolicyDeletionPolicyOnStatefulResourceTypes(), + message=( + "The default action when replacing/removing a resource is to delete" + " it. Set explicit values for UpdateReplacePolicy / DeletionPolicy" + " on potentially stateful resource: Resources/myTable" + ), + ), + Match( + linenumber=9, + columnnumber=7, + linenumberend=9, + columnnumberend=16, + filename=self.filename, + rule=SubUnneeded(), + message=( + "Fn::Sub isn't needed because there are no variables at" + " Resources/myTable/Properties/TableName/Fn::Sub" + ), + ), + Match( + linenumber=18, + columnnumber=9, + linenumberend=18, + columnnumberend=27, + filename=self.filename, + rule=Type(), + message="'5' is not of type 'integer'", + ), + ] + + def test_base_formatter(self): + """Test base formatter""" + formatter = Formatter() + a_results = formatter.print_matches( + self.results, self.rules, self.config + ).splitlines() + + # Check the errors + self.assertEqual( + a_results[0], f"{self.results[0].rule.id} {self.results[0].message}" + ) + self.assertEqual( + a_results[1], + f"{self.results[0].filename}:{self.results[0].linenumber}:{self.results[0].columnnumber}", + ) + self.assertEqual(a_results[2], "") + self.assertEqual( + a_results[3], f"{self.results[1].rule.id} {self.results[1].message}" + ) + self.assertEqual( + a_results[4], + f"{self.results[1].filename}:{self.results[1].linenumber}:{self.results[1].columnnumber}", + ) + self.assertEqual(a_results[5], "") + self.assertEqual( + a_results[6], f"{self.results[2].rule.id} {self.results[2].message}" + ) + self.assertEqual( + a_results[7], + f"{self.results[2].filename}:{self.results[2].linenumber}:{self.results[2].columnnumber}", + ) + + def test_quiet_formatter(self): + """Test quiet formatter""" + + formatter = QuietFormatter() + a_results = formatter.print_matches( + self.results, self.rules, self.config + ).splitlines() + + for i in range(3): + # Check the errors + # ruff: noqa: E501 + self.assertEqual( + a_results[i], + ( + f"{self.results[i].rule.id}:" + f" {self.results[i].rule.shortdesc} {self.results[i].filename}:{self.results[i].linenumber}" + ), + ) + + def test_parseable_formatter(self): + """Test Parseable formatter""" + formatter = ParseableFormatter() + results = formatter.print_matches( + self.results, self.rules, self.config + ).splitlines() + + for i in range(3): + # Check the errors + self.assertEqual( + results[i], + f"{self.results[i].filename}:{self.results[i].linenumber}:{self.results[i].columnnumber}:{self.results[i].linenumberend}:{self.results[i].columnnumberend}:{self.results[i].rule.id}:{self.results[i].message}", + ) + + def test_pretty_formatter(self): + """Test pretty formatter""" + formatter = PrettyFormatter() + results = formatter.print_matches( + self.results, rules=self.rules, config=self.config + ).splitlines() + + if sys.stdout.isatty(): + # Check the errors + self.assertEqual(results[0], f"\x1b[4m{self.filename}\x1b[0m") + self.assertEqual( + results[1], + ( + f"\x1b[0m{self.results[2].linenumber}:{self.results[2].columnnumber}:" + f" \x1b[0m\x1b[31m{self.results[2].rule.id} " + f" \x1b[0m{self.results[2].message}" + ), + ) + self.assertEqual( + results[2], + ( + f"\x1b[0m{self.results[1].linenumber}:{self.results[1].columnnumber}:" + f" \x1b[0m\x1b[33m{self.results[1].rule.id} " + f" \x1b[0m{self.results[1].message}" + ), + ) + self.assertEqual( + results[3], + ( + f"\x1b[0m{self.results[0].linenumber}:{self.results[0].columnnumber}:" + f" \x1b[0m\x1b[34m{self.results[0].rule.id} " + f" \x1b[0m{self.results[0].message}" + ), + ) + else: + # Check the errors + self.assertEqual(results[0], self.filename) + self.assertEqual( + results[1], + ( + f"{self.results[2].linenumber}:{self.results[2].columnnumber}: " + f" {self.results[2].rule.id} {self.results[2].message}" + ), + ) + self.assertEqual( + results[2], + ( + f"{self.results[1].linenumber}:{self.results[1].columnnumber}: " + f" {self.results[1].rule.id} " + f" {self.results[1].message}" + ), + ) + self.assertEqual( + results[3], + ( + f"{self.results[0].linenumber}:{self.results[0].columnnumber}: " + f" {self.results[0].rule.id} " + f" {self.results[0].message}" + ), + ) + + def test_pretty_formatter_pipe(self): + """Test pretty formatter""" + formatter = PrettyFormatter() + self.config.cli_args.templates = None + results = formatter.print_matches( + self.results, rules=self.rules, config=self.config + ).splitlines() + + if sys.stdout.isatty(): + self.assertIn("Cfn-lint scanned 1 templates", results[5]) + else: + # Check the errors + self.assertIn("Cfn-lint scanned 1 templates", results[5]) + + def test_json_formatter(self): + """Test JSON formatter""" + formatter = JsonFormatter() + + # Get the JSON output + json_results = json.loads( + formatter.print_matches(self.results, self.rules, self.config) + ) + + # Check the 3 errors again + self.assertEqual(len(json_results), 3) + + # Check the errors level description + for i in range(3): + self.assertEqual(json_results[i]["Rule"]["Id"], self.results[i].rule.id) + self.assertEqual(json_results[i]["Message"], self.results[i].message) + + def test_junit_returns_none(self): + """Test JUnut Formatter returns None if no rules are passed in""" + formatter = JUnitFormatter() + + # The actual test + self.assertIsNone(formatter.print_matches([], [], self.config)) + + def test_junit_formatter(self): + """Test JUnit Formatter""" + formatter = JUnitFormatter() + + self.rules._used_rules = { + "I3011": self.rules["I3011"], + "E3012": self.rules["E3012"], + "W1020": self.rules["W1020"], + } + s = formatter.print_matches(self.results, self.rules, self.config) + root = ET.fromstring(s) + + self.assertEqual(root.tag, "testsuites") + self.assertEqual(root[0].tag, "testsuite") + + found_i3011 = False + found_w1020 = False + found_e3012 = False + name_i3011 = "{0} {1}".format( + self.results[0].rule.id, self.results[0].rule.shortdesc + ) + name_w1020 = "{0} {1}".format( + self.results[1].rule.id, self.results[1].rule.shortdesc + ) + name_e3012 = "{0} {1}".format( + self.results[2].rule.id, self.results[2].rule.shortdesc + ) + name_e1029 = "E1029 Sub is required if a variable is used in a string" + for child in root[0]: + self.assertEqual(child.tag, "testcase") + + if child.attrib["name"] in [name_i3011, name_w1020, name_e3012]: + self.assertEqual(child[0].tag, "failure") + + if child.attrib["name"] == name_i3011: + found_i3011 = True + if child.attrib["name"] == name_w1020: + found_w1020 = True + if child.attrib["name"] == name_e3012: + found_e3012 = True + + if child.attrib["name"] == name_e1029: + self.assertEqual(child[0].tag, "skipped") + self.assertEqual(child[0].attrib["type"], "skipped") + + self.assertTrue(found_i3011) + self.assertTrue(found_w1020) + self.assertTrue(found_e3012) + + def test_sarif_formatter(self): + """Test the SARIF formatter""" + formatter = SARIFFormatter() + + # Get the SARIF JSON output + sarif = json.loads( + formatter.print_matches(self.results, self.rules, self.config) + ) + + with open(self.sarif_schema, encoding="utf-8") as f: + schema = json.load(f) + # Fetch the SARIF schema + # schema = json.loads(cfnlint.helpers.get_url_content(sarif["$schema"], False)) + validator = StandardValidator(schema=schema) + validator.validate(sarif) + + sarif_results = sarif["runs"][0]["results"] + # Check the 3 errors again + self.assertEqual(len(sarif_results), 3) + + # Sanity check the errors + self.assertEqual(sarif_results[0]["level"], "note") + self.assertEqual(sarif_results[0]["ruleId"], "I3011") + # IMPORTANT: 'warning' is the default level in SARIF (when kind is + # absent) and is stripped by serialization + self.assertNotIn("level", sarif_results[1].keys()) + self.assertEqual(sarif_results[1]["ruleId"], "W1020") + self.assertEqual(sarif_results[2]["level"], "error") + self.assertEqual(sarif_results[2]["ruleId"], "E3012") diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_create_rules.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_create_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..2c62b354092dec05fcc08b7d50a0c44006b3c1ba --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_create_rules.py @@ -0,0 +1,20 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase + +from cfnlint.helpers import create_rules +from cfnlint.rules import CloudFormationLintRule + + +class TestCreateRules(BaseTestCase): + """Test creating rules from a module.""" + + def testBase(self): + from cfnlint.rules.jsonschema import JsonSchema + + rules = create_rules(JsonSchema) + self.assertTrue(all(isinstance(r, CloudFormationLintRule) for r in rules)) + self.assertTrue("E1001" in (r.id for r in rules)) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_downloads_metadata.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_downloads_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..9b30a33f8000b8476827b495326d33e416036e52 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_downloads_metadata.py @@ -0,0 +1,67 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import json +from test.testlib.testcase import BaseTestCase +from unittest.mock import mock_open, patch + +import cfnlint.helpers + + +class TestDownloadsMetadata(BaseTestCase): + """Test Downloads Metadata""" + + @patch("cfnlint.helpers.os.path.exists") + def test_no_file(self, mock_path_exists): + """Test success run""" + + mock_path_exists.return_value = False + + filename = "foo.bar" + + result = cfnlint.helpers.load_metadata(filename) + + self.assertEqual(result, {}) + + @patch("cfnlint.helpers.os.path.exists") + def test_load_metadata(self, mock_path_exists): + """Test success run""" + + mock_path_exists.return_value = True + + filename = "foo.bar" + file_contents = {"etag": "foo"} + + builtin_module_name = "builtins" + + mo = mock_open(read_data=json.dumps(file_contents)) + with patch("{}.open".format(builtin_module_name), mo): + result = cfnlint.helpers.load_metadata(filename) + + self.assertEqual(result, file_contents) + + @patch("cfnlint.helpers.os.path.exists") + @patch("cfnlint.helpers.os.path.dirname") + @patch("cfnlint.helpers.os.mkdir") + @patch("cfnlint.helpers.json.dump") + def test_save_download_metadata( + self, mock_json_dump, mock_mkdir, mock_dirname, mock_path_exists + ): + """Test success run""" + + filename = "foo.bar" + filedir = "foobardir" + file_contents = {"etag": "foo"} + + mock_path_exists.return_value = False + mock_dirname.return_value = filedir + + builtin_module_name = "builtins" + + mo = mock_open() + with patch("{}.open".format(builtin_module_name), mo): + cfnlint.helpers.save_metadata(file_contents, filename) + mock_mkdir.assert_called_with(filedir) + mock_json_dump.assert_called_once diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_format_json.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_format_json.py new file mode 100644 index 0000000000000000000000000000000000000000..f3a437372aabcc88b393c1f0584fad24b3f79f83 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_format_json.py @@ -0,0 +1,33 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import datetime +from test.testlib.testcase import BaseTestCase + +from cfnlint.helpers import format_json_string + + +class TestFormatJson(BaseTestCase): + """Test Dumping JSON objects""" + + def test_success_run(self): + """Test success run""" + obj = { + "Key": {"SubKey": "Value", "Date": datetime.datetime(2010, 9, 9)}, + "List": [{"SubKey": "AnotherValue"}], + } + success = """{ + "Key": { + "Date": "2010-09-09 00:00:00", + "SubKey": "Value" + }, + "List": [ + { + "SubKey": "AnotherValue" + } + ] +}""" + results = format_json_string(obj) + self.assertEqual(success, results) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_get_url_content.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_get_url_content.py new file mode 100644 index 0000000000000000000000000000000000000000..50a3b6f772aa3a0bdeb089814e6f0e276e931ca1 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_get_url_content.py @@ -0,0 +1,122 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import gzip +from test.testlib.testcase import BaseTestCase +from unittest.mock import MagicMock, patch + +import cfnlint.helpers + + +class TestGetUrlContent(BaseTestCase): + """Test Get URL Content""" + + @patch("cfnlint.helpers.urlopen") + def test_get_url_content_unzipped(self, mocked_urlopen): + """Test success run""" + + input_buffer = '{"key": "value"}' + + cm = MagicMock() + cm.getcode.return_value = 200 + cm.read.return_value = input_buffer.encode("utf-8") + cm.__enter__.return_value = cm + mocked_urlopen.return_value = cm + + url = "http://foo.com" + result = cfnlint.helpers.get_url_content(url) + mocked_urlopen.assert_called_with(url) + self.assertEqual(result, '{"key": "value"}') + + @patch("cfnlint.helpers.urlopen") + def test_get_url_content_zipped(self, mocked_urlopen): + """Test success run""" + input_buffer = '{"key": "value"}' + cm = MagicMock() + cm.getcode.return_value = 200 + cm.read.return_value = gzip.compress(input_buffer.encode("utf-8")) + + cm.info.return_value = {"Content-Encoding": "gzip"} + cm.__enter__.return_value = cm + mocked_urlopen.return_value = cm + + url = "http://foo.com" + result = cfnlint.helpers.get_url_content(url) + mocked_urlopen.assert_called_with(url) + self.assertEqual(result, '{"key": "value"}') + + @patch("cfnlint.helpers.urlopen") + @patch("cfnlint.helpers.load_metadata") + @patch("cfnlint.helpers.save_metadata") + def test_get_url_content_zipped_cache_update( + self, mock_save_metadata, mock_load_metadata, mocked_urlopen + ): + """Test success run""" + input_buffer = '{"key": "value"}' + etag = "ETAG_ONE" + url = "http://foo.com" + + mock_load_metadata.return_value = {} + + cm = MagicMock() + cm.getcode.return_value = 200 + cm.info.return_value = {"Content-Encoding": "gzip", "ETag": etag} + + cm.read.return_value = gzip.compress(input_buffer.encode("utf-8")) + + cm.__enter__.return_value = cm + mocked_urlopen.return_value = cm + + result = cfnlint.helpers.get_url_content(url, caching=True) + mocked_urlopen.assert_called_with(url) + mock_load_metadata.assert_called_once() + mock_save_metadata.assert_called_once() + + self.assertEqual(result, '{"key": "value"}') + + @patch("cfnlint.helpers.urlopen") + @patch("cfnlint.helpers.load_metadata") + def test_url_has_newer_version_affirmative( + self, mock_load_metadata, mocked_urlopen + ): + """Test success run""" + + etag = "ETAG_ONE" + url = "http://foo.com" + + mock_load_metadata.return_value = {"etag": etag} + + cm = MagicMock() + cm.getcode.return_value = 200 + cm.info.return_value = {"Content-Encoding": "gzip", "ETag": etag} + + cm.__enter__.return_value = cm + mocked_urlopen.return_value = cm + + result = cfnlint.helpers.url_has_newer_version(url) + + # Python2 does not support caching, so will always return true + self.assertFalse(result) + + @patch("cfnlint.helpers.urlopen") + @patch("cfnlint.helpers.load_metadata") + def test_url_has_newer_version_negative(self, mock_load_metadata, mocked_urlopen): + """Test success run""" + + # Generate a random ETag to test with + etag = "ETAG_ONE" + etag2 = "ETAG_TWO" + + url = "http://foo.com" + mock_load_metadata.return_value = {"etag": etag} + + cm = MagicMock() + cm.getcode.return_value = 200 + cm.info.return_value = {"Content-Encoding": "gzip", "ETag": etag2} + cm.__enter__.return_value = cm + mocked_urlopen.return_value = cm + + result = cfnlint.helpers.url_has_newer_version(url) + self.assertTrue(result) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_get_url_retrieve.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_get_url_retrieve.py new file mode 100644 index 0000000000000000000000000000000000000000..64c5180060899ba8d9567ac6edb19e6e8073edef --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_get_url_retrieve.py @@ -0,0 +1,51 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase +from unittest.mock import MagicMock, patch + +import cfnlint.helpers + + +class TestGetUrlRetrieve(BaseTestCase): + """Test Get URL Retrieve""" + + @patch("cfnlint.helpers.urlretrieve") + def test_get_url_retrieve(self, mocked_urlretrieve): + """Test the basics of URL retrieve""" + + mocked_urlretrieve.return_value = ("file/path", None) + + url = "http://foo.com" + result = cfnlint.helpers.get_url_retrieve(url) + mocked_urlretrieve.assert_called_with(url) + self.assertEqual(result, "file/path") + + @patch("cfnlint.helpers.urlopen") + @patch("cfnlint.helpers.load_metadata") + @patch("cfnlint.helpers.save_metadata") + @patch("cfnlint.helpers.urlretrieve") + def test_get_url_retrieve_cached( + self, mocked_urlretrieve, mock_save_metadata, mock_load_metadata, mocked_urlopen + ): + """Test the basics of URL retrieve""" + etag = "ETAG_ONE" + url = "http://foo.com" + + mock_load_metadata.return_value = {} + + cm = MagicMock() + cm.getcode.return_value = 200 + cm.info.return_value = {"Content-Encoding": "gzip", "ETag": etag} + cm.__enter__.return_value = cm + mocked_urlopen.return_value = cm + + mocked_urlretrieve.return_value = ("file/path", None) + + result = cfnlint.helpers.get_url_retrieve(url, caching=True) + mocked_urlretrieve.assert_called_with(url) + mock_load_metadata.assert_called_once() + mock_save_metadata.assert_called_once() + self.assertEqual(result, "file/path") diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_is_type_compatible.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_is_type_compatible.py new file mode 100644 index 0000000000000000000000000000000000000000..ce60b27db9c50cefce4d5882744940e7fe6109af --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_is_type_compatible.py @@ -0,0 +1,72 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import pytest + +from cfnlint.helpers import is_types_compatible + + +@pytest.mark.parametrize( + "name,source,destination,expected", + [ + ( + "Types are directly working together", + "string", + ["string"], + True, + ), + ( + "Types can be converted from source to destiniation", + "string", + ["integer"], + True, + ), + ( + "Types can be converted from destination to source", + "integer", + ["string"], + True, + ), + ( + "Types of integer against array are not compatible", + "integer", + "array", + False, + ), + ( + "Types of integer can be compatible", + "integer", + "number", + True, + ), + ( + "Types of number are not an integer", + "number", + "integer", + False, + ), + ( + "Types of integer is not compatible with boolean", + "integer", + "boolean", + False, + ), + ( + "Types of number is not compatible with boolean", + "number", + "boolean", + False, + ), + ( + "Types of number, string is compatible with boolean", + ["number", "string"], + "boolean", + True, + ), + ], +) +def test_validate(name, source, destination, expected): + result = is_types_compatible(source, destination) + assert result == expected, f"Test {name!r} got {result!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_load_plugins.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_load_plugins.py new file mode 100644 index 0000000000000000000000000000000000000000..3ab34eac38195bfba2bf2c9a4adc9debec738259 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_load_plugins.py @@ -0,0 +1,32 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import os +from test.testlib.testcase import BaseTestCase + +from cfnlint.config import _DEFAULT_RULESDIR +from cfnlint.helpers import load_plugins +from cfnlint.rules import CloudFormationLintRule + + +class TestLoadPlugins(BaseTestCase): + """Test loading rules.""" + + def testFromDefaultDirectory(self): + rules = load_plugins(_DEFAULT_RULESDIR) + + self.assertTrue(all(isinstance(r, CloudFormationLintRule) for r in rules)) + # From templates/Base.py + self.assertTrue("E1001" in (r.id for r in rules)) + # From resources/Name.py + self.assertTrue("E3006" in (r.id for r in rules)) + + def testFromSubDirectory(self): + path = os.path.join(_DEFAULT_RULESDIR, "templates") + rules = load_plugins(path) + + self.assertTrue(all(isinstance(r, CloudFormationLintRule) for r in rules)) + self.assertTrue("E1002" in (r.id for r in rules), rules) + self.assertFalse("E3006" in (r.id for r in rules), rules) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_regex_dict.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_regex_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..3509aef623b3975618536749d4cceefa7080be11 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/helpers/test_regex_dict.py @@ -0,0 +1,43 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase + +from cfnlint.helpers import RegexDict + + +class TestRegexDict(BaseTestCase): + """Test Regex Dict""" + + def test_getitem(self): + """Test success run""" + + obj = RegexDict() + obj["^Value$"] = True + + with self.assertRaises(KeyError): + obj["NotExist"] + + def test_get(self): + obj = RegexDict() + obj["^Value$"] = True + + self.assertEqual(obj.get("NotExist", "Default"), "Default") + + def test_return_longest(self): + obj = RegexDict() + obj["^Test"] = False + obj["^TestLonger.*"] = True + + self.assertTrue(obj["TestLongerObject"]) + + def test_contains_object(self): + obj = RegexDict() + obj["^Test"] = False + obj["^TestLonger.*"] = True + + self.assertTrue("TestLongerObject" in obj) + self.assertFalse("NotIn" in obj) + self.assertFalse({"a": "b"} in obj) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_exceptions.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..d1b27f1a0a6284b1134ca28c20646f24da08b979 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_exceptions.py @@ -0,0 +1,110 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import unittest +from collections import deque + +from cfnlint.jsonschema.exceptions import ( + FormatError, + UndefinedTypeCheck, + ValidationError, + best_match, +) +from cfnlint.rules import CloudFormationLintRule + + +class _RuleX(CloudFormationLintRule): + id = "X0000" + + +class _RuleY(CloudFormationLintRule): + id = "Y0000" + + +class TestExceptions(unittest.TestCase): + def test_validation_error(self): + err = ValidationError( + message="Failure", path=deque(["foo"]), schema_path=deque(["bar"]) + ) + + self.assertListEqual(list(err.absolute_path), ["foo"]) + + self.assertListEqual(list(err.absolute_schema_path), ["bar"]) + + self.assertEqual(err.json_path, "$.foo") + + def test_validation_parent_error(self): + parent = ValidationError( + message="Failure", path=deque(["foo"]), schema_path=deque(["foo"]) + ) + err = ValidationError( + message="Failure", + path=deque(["bar", 0]), + schema_path=deque(["bar"]), + parent=parent, + ) + + self.assertListEqual(list(err.absolute_path), ["foo", "bar", 0]) + + self.assertListEqual(list(err.absolute_schema_path), ["foo", "bar"]) + + self.assertEqual(err.json_path, "$.foo.bar[0]") + + def test_best_match(self): + one = ValidationError(message="One", path=deque(["foo", "bar", "foo"])) + two = ValidationError(message="Two", path=deque(["foo", "bar"])) + + self.assertEqual(best_match([one, two]).message, "Two") + + three = ValidationError( + message="Three", + path=deque(["foo"]), + context=[ + ValidationError(message="Four", path=deque(["a", "b"])), + ValidationError(message="Five", path=deque(["a", "b", "c", "d"])), + ValidationError(message="Size", path=deque(["a"])), + ], + ) + self.assertEqual(best_match([one, two, three]).message, "Five") + + self.assertEqual(best_match([]), None) + + def test_undefined_type_check(self): + err = UndefinedTypeCheck("foo") + self.assertEqual(str(err), "Type 'foo' is unknown to this type checker") + + def test_format_error(self): + err = FormatError("foo") + self.assertEqual(str(err), "foo") + + def test_equals(self): + self.assertEqual( + ValidationError(message="Failure", path=deque(["foo"])), + ValidationError(message="Failure", path=deque(["foo"])), + ) + + self.assertNotEqual( + ValidationError(message="Failure", path=deque(["foo"])), + ValidationError(message="Failure", path=deque(["foo"]), rule=_RuleX()), + ) + self.assertNotEqual( + ValidationError(message="Failure", path=deque(["foo"]), rule=_RuleX()), + ValidationError( + message="Failure", + path=deque(["foo"]), + ), + ) + self.assertNotEqual( + ValidationError(message="Failure", path=deque(["foo"]), rule=_RuleX()), + ValidationError( + message="Failure", + path=deque(["foo"]), + rule=_RuleY(), + ), + ) + self.assertNotEqual( + ValidationError(message="Failure", path=deque(["foo"]), rule=_RuleX()), + "test", + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_filter.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..c1fd3ec175b040855993bb893b8b8b9cdcce78b9 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_filter.py @@ -0,0 +1,160 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.context import create_context_for_template +from cfnlint.context.context import Path +from cfnlint.jsonschema import CfnTemplateValidator +from cfnlint.jsonschema._filter import FunctionFilter +from cfnlint.template import Template + + +@pytest.fixture(scope="module") +def filter(): + filter = FunctionFilter() + yield filter + + +@pytest.fixture() +def template(): + template = Template( + None, + { + "Parameters": {"MyParameter": {"Type": "String"}}, + "Conditions": {"Condition": {"Fn::Equals": [{"Ref": "MyParameter"}, ""]}}, + }, + ["us-east-1"], + ) + yield template + + +@pytest.mark.parametrize( + "name,instance,schema,path,functions,expected", + [ + ( + "Don't validate dynamic references inside of function", + "{{resolve:ssm:${AWS::AccountId}/${AWS::Region}/ac}}", + {"enum": "Foo"}, + deque(["Foo", "Test", "Fn::Sub"]), + [], + [], + ), + ( + "Validate dynamic references", + "{{resolve:ssm:secret}}", + {"enum": "Foo"}, + deque(["Foo", "Test"]), + [], + [ + ("{{resolve:ssm:secret}}", {"dynamicReference": {"enum": "Foo"}}), + ], + ), + ( + "Lack of functions returns the schema and instance", + { + "Foo": {"Ref": "AWS::NoValue"}, + }, + {"required": ["Foo"]}, + deque([]), + [], + [ + ( + { + "Foo": {"Ref": "AWS::NoValue"}, + }, + {"required": ["Foo"]}, + ), + ], + ), + ( + "Filtered schemas", + { + "Foo": {"Ref": "AWS::NoValue"}, + }, + {"required": ["Foo"]}, + deque([]), + ["Ref", "Fn::If"], + [ + ( + {}, + {"required": ["Foo"]}, + ), + ({"Foo": {"Ref": "AWS::NoValue"}}, {"cfnLint": [""]}), + ], + ), + ( + "Filtered schemas with list", + [ + { + "Fn::If": [ + "Condition", + {"Key": "1", "Value": "A"}, + {"Ref": "AWS::NoValue"}, + ] + }, + { + "Key": "2", + "Value": "B", + }, + {"Ref": "AWS::NoValue"}, + ], + {"items": {"required": ["Key"]}}, + deque([]), + ["Ref", "Fn::If"], + [ + ( + [ + { + "Fn::If": [ + "Condition", + {"Key": "1", "Value": "A"}, + {"Ref": "AWS::NoValue"}, + ] + }, + { + "Key": "2", + "Value": "B", + }, + {"Ref": "AWS::NoValue"}, + ], + {"items": {"required": ["Key"]}, "cfnLint": [""]}, + ), + ], + ), + ], +) +def test_filter( + name, + instance, + schema, + path, + functions, + expected, + filter, + template, +): + context = create_context_for_template(template) + validator = CfnTemplateValidator( + context=context, + cfn=template, + schema=schema, + ) + validator = validator.evolve( + context=validator.context.evolve( + path=Path(path), + functions=functions, + ) + ) + + results = list(filter.filter(validator, instance, schema)) + + assert len(results) == len(expected), f"For test {name} got {len(results)} results" + + for result, (exp_instance, exp_schema) in zip(results, expected): + assert result[0] == exp_instance, f"For test {name} got {result[0]!r}" + assert result[1] == exp_schema, f"For test {name} got {result[1]!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_format.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..53513392d25df5f24ebbd814d97ae3b097410c80 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_format.py @@ -0,0 +1,59 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import unittest + +from cfnlint.jsonschema._format import cfn_format_checker +from cfnlint.jsonschema.exceptions import FormatError + + +class TestFormat(unittest.TestCase): + def test_format_checker(self): + self.assertEqual( + str(cfn_format_checker), + ( + "" + ), + ) + + self.assertIsNone(cfn_format_checker.check("aws@amazon.com", "email")) + self.assertIsNone(cfn_format_checker.check({"foo": "bar"}, "email")) + with self.assertRaises(FormatError): + cfn_format_checker.check("foo", "email") + + self.assertIsNone(cfn_format_checker.check("127.0.0.1", "ipv4")) + self.assertIsNone(cfn_format_checker.check({"foo": "bar"}, "ipv4")) + with self.assertRaises(FormatError): + cfn_format_checker.check("foo", "ipv4") + + self.assertIsNone( + cfn_format_checker.check("0000:0000:0000:0000:0000:0000:0000:0000", "ipv6") + ) + self.assertIsNone(cfn_format_checker.check({"foo": "bar"}, "ipv6")) + with self.assertRaises(FormatError): + cfn_format_checker.check("foo", "ipv6") + + self.assertIsNone(cfn_format_checker.check("1970-01-01", "date")) + self.assertIsNone(cfn_format_checker.check({"foo": "bar"}, "date")) + with self.assertRaises(FormatError): + cfn_format_checker.check("foo", "date") + + self.assertIsNone( + cfn_format_checker.check("1970-01-01T00:00:00.000Z", "date-time") + ) + self.assertIsNone(cfn_format_checker.check({"foo": "bar"}, "date-time")) + with self.assertRaises(FormatError): + cfn_format_checker.check("foo", "date-time") + + self.assertIsNone(cfn_format_checker.check("00:00:00.000Z", "time")) + self.assertIsNone(cfn_format_checker.check({"foo": "bar"}, "time")) + with self.assertRaises(FormatError): + cfn_format_checker.check("foo", "time") + + self.assertIsNone(cfn_format_checker.check("^$", "regex")) + self.assertIsNone(cfn_format_checker.check({"foo": "bar"}, "regex")) + with self.assertRaises(FormatError): + cfn_format_checker.check("[a-", "regex") diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_keywords.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..00fa2dab17de20a41b597e26b9b8c5002a6889a6 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_keywords.py @@ -0,0 +1,136 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError, _keywords +from cfnlint.jsonschema.validators import CfnTemplateValidator +from cfnlint.rules import CloudFormationLintRule + + +class Error(CloudFormationLintRule): + id = "E1111" + + def validate(self, validator, s, instance, schema): + if s: + yield ValidationError( + "Error", + rule=self, + ) + + +class Warning(CloudFormationLintRule): + id = "W1111" + + def validate(self, validator, s, instance, schema): + yield ValidationError( + "Warning", + rule=self, + ) + + +@pytest.fixture +def validator(): + validator = CfnTemplateValidator(schema={}) + validator = validator.extend( + validators={ + "error": Error().validate, + "warning": Warning().validate, + } + ) + return validator({}) + + +@pytest.mark.parametrize( + "name,instance,schema,expected", + [ + ( + "Valid anyOf", + "foo", + [{"const": "foo"}, {"const": "bar"}], + [], + ), + ( + "Valid anyOf with error rule", + "foo", + [{"const": "foo"}, {"error": True}], + [], + ), + ( + "Invalid anyOf with error rule", + "foo", + [{"error": True}, {"error": True}], + [ + ValidationError( + "'foo' is not valid under any of the given schemas", + path=deque([]), + schema_path=deque([]), + context=[ + ValidationError( + "Error", + rule=Error(), + path=deque([]), + validator="error", + schema_path=deque([0, "error"]), + ), + ValidationError( + "Error", + rule=Error(), + path=deque([]), + validator="error", + schema_path=deque([1, "error"]), + ), + ], + ), + ], + ), + ( + "Valid anyOf with a warning validation error", + "foo", + [{"warning": True, "error": True}, {"error": True}], + [ + ValidationError( + "'foo' is not valid under any of the given schemas", + path=deque([]), + schema_path=deque([]), + context=[ + ValidationError( + "Error", + rule=Error(), + path=deque([]), + validator="error", + schema_path=deque([0, "error"]), + ), + ValidationError( + "Error", + rule=Error(), + path=deque([]), + validator="error", + schema_path=deque([1, "error"]), + ), + ValidationError( + "Warning", + rule=Warning(), + path=deque([]), + validator="warning", + schema_path=deque([0, "warning"]), + ), + ], + ), + ], + ), + ( + "Valid anyOf without a warning validation error", + "foo", + [{"error": True}, {"warning": True}], + [], + ), + ], +) +def test_anyof(name, instance, schema, validator, expected): + errs = list(_keywords.anyOf(validator, schema, instance, schema)) + assert errs == expected, f"{name!r} got errors {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_keywords_cfn.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_keywords_cfn.py new file mode 100644 index 0000000000000000000000000000000000000000..6d088e848ce5e320b4b5817e177d6d772860f4ca --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_keywords_cfn.py @@ -0,0 +1,179 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import unittest +from collections import namedtuple +from typing import List + +from cfnlint.context import Context +from cfnlint.jsonschema._keywords_cfn import FnItems, cfn_type +from cfnlint.jsonschema.exceptions import UnknownType +from cfnlint.jsonschema.validators import CfnTemplateValidator + + +class _Fns: + def __init__(self, resp) -> None: + self.resp = resp + + def get_value(self, instance, region): + for item in self.resp: + if isinstance(item, Exception): + raise item + yield item + + +class _Cfn: + def __init__(self, resp) -> None: + self.functions = _Fns(resp) + + +_T = namedtuple("_T", ["name", "instance", "schema", "errors", "cfn_response"]) + + +class Base(unittest.TestCase): + def message_errors(self, name, instance, errors, schema, **kwargs): + cfn_validator = CfnTemplateValidator({}).extend(validators={"type": cfn_type}) + context = Context(regions=["us-east-1"], strict_types=False) + cls = kwargs.pop("cls", cfn_validator(schema=schema, context=context)) + validator = cls.evolve(**kwargs) + i_errors = list(validator.iter_errors(instance)) + self.assertEqual( + len(errors), + len(i_errors), + msg=( + f"{name}: Expected exactly {len(errors)} error, " + f"found {i_errors!r}, need {errors!r}" + ), + ) + err_messages = [err.message for err in i_errors] + for err in errors: + self.assertIn( + err, err_messages, msg=f"{name}: expected {err} to be in {i_errors!r}" + ) + + def iterate_tests(self, tests: List[_T]): + for test in tests: + self.message_errors( + name=test.name, + instance=test.instance, + schema=test.schema, + errors=test.errors, + cfn=_Cfn(test.cfn_response), + ) + + +class TestCfnTypes(Base): + def build_execute_tests(self, instance, supported_types) -> None: + _all_types = ["string", "number", "integer", "boolean", "array", "object"] + tests: List[_T] = [] + for t in _all_types: + reprs = ", ".join(repr(type) for type in [t]) + if t in supported_types: + tests.append( + _T( + f"{instance} can return {t}", + instance, + {"type": t}, + [], + [], + ) + ) + else: + tests.append( + _T( + f"{instance} cannot return {t}", + instance, + {"type": t}, + [f"{instance!r} is not of type {reprs}"], + [], + ) + ) + self.iterate_tests(tests) + + def test_standard_values(self): + self.build_execute_tests({"Foo": True, "Bar": True}, ["object"]) + self.build_execute_tests({"Foo": True}, ["object"]) + self.build_execute_tests("a", ["string"]) + self.build_execute_tests("1.5", ["string", "number"]) + self.build_execute_tests("1", ["string", "number", "integer"]) + self.build_execute_tests(True, ["string", "boolean"]) + self.build_execute_tests("true", ["string", "boolean"]) + + def test_null_values(self): + self.message_errors( + "Null value with string type", + None, + ["None is not of type 'string'"], + {"type": "string"}, + ) + self.message_errors( + "String value with null type", + "foo", + ["'foo' is not of type 'null'"], + {"type": "null"}, + ) + self.message_errors( + "Object value with null type", + {}, + ["{} is not of type 'null'"], + {"type": "null"}, + ) + self.message_errors( + "None value with multiple types", + None, + [], + {"type": ["string", "null"]}, + ) + + +class TestMultiCfnTypes(Base): + def build_execute_tests(self, instance, supported_types, unsupported_type) -> None: + tests: List[_T] = [] + check_types = supported_types + [unsupported_type] + tests.append( + _T( + f"{instance} can return one of {check_types!r}", + instance, + {"type": check_types}, + [], + [], + ) + ) + + self.iterate_tests(tests) + + def test_standard_values(self): + # all these checks should return true as there is one good value + self.build_execute_tests({"Foo": True, "Bar": True}, ["object"], "string") + self.build_execute_tests({"Foo": True}, ["object"], "string") + self.build_execute_tests("a", ["string"], "number") + self.build_execute_tests("1.5", ["string", "number"], "integer") + self.build_execute_tests("1", ["string", "number", "integer"], "boolean") + self.build_execute_tests(True, ["string", "boolean"], "number") + self.build_execute_tests("true", ["string", "boolean"], "object") + + +class TestCfnTypeFailure(Base): + def test_cfn_type_failure(self): + with self.assertRaises(UnknownType) as err: + CfnTemplateValidator({}).is_type("foo", "bar") + self.assertIn( + "Unknown type 'bar' for validator with schema", str(err.exception) + ) + + +class TestFnItems(Base): + + def test_change_type(self): + schema = [ + { + "schema": {"type": "string"}, + }, + ] + validator = CfnTemplateValidator({}) + + items = list(FnItems().validate(validator, schema, [1], {})) + + self.assertListEqual(items, []) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_resolvers_cfn.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_resolvers_cfn.py new file mode 100644 index 0000000000000000000000000000000000000000..b0d316a32f2555f48a3779d16b5bf5fe0b8a757a --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_resolvers_cfn.py @@ -0,0 +1,561 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.context._mappings import Mappings +from cfnlint.context.context import Context, Parameter +from cfnlint.jsonschema import ValidationError +from cfnlint.jsonschema.validators import CfnTemplateValidator + + +def _resolve(name, instance, expected_results, **kwargs): + validator = CfnTemplateValidator().evolve(**kwargs) + + resolutions = list(validator.resolve_value(instance)) + + assert len(resolutions) == len( + expected_results + ), f"{name!r} got {len(resolutions)!r}" + + for i, (instance, v, errors) in enumerate(resolutions): + assert instance == expected_results[i][0], f"{name!r} got {instance!r}" + assert ( + v.context.path.value_path == expected_results[i][1] + ), f"{name!r} got {v.context.path.value_path!r}" + assert errors == expected_results[i][2], f"{name!r} got {errors!r}" + + +@pytest.mark.parametrize( + "name,instance,response", + [ + ( + "Valid Ref with a single instance", + {"Ref": {"Ref": "MyResource"}}, + [], + ), + ], +) +def test_resolvers_ref(name, instance, response): + _resolve(name, instance, response) + + +@pytest.mark.parametrize( + "name,instance,response", + [ + ( + "Invalid Ref with an array", + {"Ref": []}, + [], + ), + ( + "Invalid Ref with an invalid object", + {"Ref": {"foo": "bar"}}, + [], + ), + ( + "Invalid Join with an invalid type", + {"Fn::Join": {"foo": "bar"}}, + [], + ), + ( + "Invalid Join with an invalid array length", + {"Fn::Join": ["a", "b", "c"]}, + [], + ), + ( + "Invalid Join with an invalid type for first element", + {"Fn::Join": [["a"], "b"]}, + [], + ), + ( + "Invalid Join with an invalid type for second element", + {"Fn::Join": ["a", "b"]}, + [], + ), + ( + "Invalid Join with an invalid type for second element item", + {"Fn::Join": ["/", [["a"], "b"]]}, + [], + ), + ( + "Invalid Select with an invalid type", + {"Fn::Select": {"foo": "bar"}}, + [], + ), + ( + "Invalid Select with an invalid array length", + {"Fn::Select": ["a", "b", "c"]}, + [], + ), + ( + "Invalid Select with an invalid type for second element", + {"Fn::Select": ["a", "b"]}, + [], + ), + ( + "Invalid Select with an invalid type for second element", + {"Fn::Select": [0, "b"]}, + [], + ), + ( + "Invalid Split with an invalid type", + {"Fn::Split": {"foo": "bar"}}, + [], + ), + ( + "Invalid Split with an invalid array length", + {"Fn::Split": ["a", "b", "c"]}, + [], + ), + ( + "Invalid Split with an invalid type for first element", + {"Fn::Split": [0, "b"]}, + [], + ), + ( + "Invalid Split with an invalid type for second element", + {"Fn::Split": ["a", ["b"]]}, + [], + ), + ( + "Invalid GetAZs with an invalid type ", + {"Fn::GetAZs": {"a": "b"}}, + [], + ), + ( + "Invalid GetAZs with an invalid type ", + {"Fn::GetAZs": ["a", "b"]}, + [], + ), + ( + "Invalid GetAZs with an invalid region", + {"Fn::GetAZs": "foo"}, + [], + ), + ( + "Invalid FindInMap with an invalid type", + {"Fn::FindInMap": {"foo": "bar"}}, + [], + ), + ( + "Invalid FindInMap with an invalid length", + {"Fn::FindInMap": ["foo", "bar"]}, + [], + ), + ( + "Invalid FindInMap with an invalid type for first element", + {"Fn::FindInMap": [["foo"], "bar", "value"]}, + [], + ), + ( + "Invalid FindInMap with an invalid type for second element", + {"Fn::FindInMap": ["foo", ["bar"], "value"]}, + [], + ), + ( + "Invalid FindInMap with an invalid type for third element", + {"Fn::FindInMap": ["foo", "first", ["value"]]}, + [], + ), + ( + "Invalid FnSub with an invalid type", + {"Fn::Sub": {"foo": "bar"}}, + [], + ), + ( + "Invalid FnSub with an array of wrong length", + {"Fn::Sub": ["foo", "bar", "value"]}, + [], + ), + ( + "Invalid FnSub with the wrong type for element one", + {"Fn::Sub": [["foo"], {"foo": "bar"}]}, + [], + ), + ( + "Invalid FnSub with the wrong type for element two", + {"Fn::Sub": ["foo", ["bar"]]}, + [], + ), + ], +) +def test_invalid_functions(name, instance, response): + context = Context( + mappings=Mappings.create_from_dict({"foo": {"first": {"second": "bar"}}}) + ) + + _resolve(name, instance, response, context=context) + + +@pytest.mark.parametrize( + "name,instance,response", + [ + ( + "Valid Join with an empty type", + {"Fn::Join": [".", []]}, + [], + ), + ( + "Valid Join with a list of strings", + {"Fn::Join": [".", ["a", "b", "c"]]}, + [("a.b.c", deque([]), None)], + ), + ( + "Valid GetAZs with empty string", + {"Fn::GetAZs": ""}, + [ + ( + [ + "us-east-1a", + "us-east-1b", + "us-east-1c", + "us-east-1d", + "us-east-1e", + "us-east-1f", + ], + deque([]), + None, + ) + ], + ), + ( + "Valid FindInMap with bad keys and a default value", + {"Fn::FindInMap": ["foo", "bar", "value", {"DefaultValue": "default"}]}, + [("default", deque([4, "DefaultValue"]), None)], + ), + ( + "Valid FindInMap with valid keys and a default value", + {"Fn::FindInMap": ["foo", "first", "second", {"DefaultValue": "default"}]}, + [ + ("default", deque([4, "DefaultValue"]), None), + ("bar", deque(["Mappings", "foo", "first", "second"]), None), + ], + ), + ( + "Valid FindInMap with a bad mapping", + {"Fn::FindInMap": ["bar", "first", "second"]}, + [ + ( + None, + deque([]), + ValidationError( + ( + "'bar' is not one of ['foo', " + "'transformFirstKey', 'transformSecondKey', " + "'integers', 'accounts', 'environments']" + ), + path=deque(["Fn::FindInMap", 0]), + ), + ) + ], + ), + ( + "Valid FindInMap with a bad mapping and default", + {"Fn::FindInMap": ["bar", "first", "second", {"DefaultValue": "default"}]}, + [("default", deque([4, "DefaultValue"]), None)], + ), + ( + "Valid FindInMap with a bad mapping and aws no value", + { + "Fn::FindInMap": [ + "bar", + "first", + "second", + {"DefaultValue": {"Ref": "AWS::NoValue"}}, + ] + }, + [], + ), + ( + "Valid FindInMap with a bad top key", + {"Fn::FindInMap": ["foo", "second", "first"]}, + [ + ( + None, + deque([]), + ValidationError( + ("'second' is not one of ['first'] for " "mapping 'foo'"), + path=deque(["Fn::FindInMap", 1]), + ), + ) + ], + ), + ( + "Valid FindInMap with a bad top key and default", + {"Fn::FindInMap": ["foo", "second", "first", {"DefaultValue": "default"}]}, + [("default", deque([4, "DefaultValue"]), None)], + ), + ( + "Valid FindInMap with a map name that is a Ref to pseudo param", + {"Fn::FindInMap": [{"Ref": "AWS::StackName"}, "first", "second"]}, + [], + ), + ( + "Valid FindInMap with an top level key that is a Ref to an account", + {"Fn::FindInMap": ["accounts", {"Ref": "AWS::AccountId"}, "dev"]}, + [ + ( + "bar", + deque(["Mappings", "accounts", "123456789012", "dev"]), + None, + ) + ], + ), + ( + ( + "Valid FindInMap with an top level key " + "that is a Ref to non account non region" + ), + {"Fn::FindInMap": ["accounts", {"Ref": "AWS::StackName"}, "dev"]}, + [ + ( + "bar", + deque(["Mappings", "accounts", "123456789012", "dev"]), + None, + ) + ], + ), + ( + "Valid FindInMap with an top level key that is a Ref to a region", + {"Fn::FindInMap": ["accounts", {"Ref": "AWS::Region"}, "bar"]}, + [ + ( + "foo", + deque(["Mappings", "accounts", "us-east-1", "bar"]), + None, + ) + ], + ), + ( + "Invalid FindInMap with an top level key that is a Ref to an account", + {"Fn::FindInMap": ["accounts", {"Ref": "AWS::AccountId"}, "bar"]}, + [ + ( + None, + deque([]), + ValidationError( + ( + "'bar' is not a second level key " + "when {'Ref': 'AWS::AccountId'} is " + "resolved for mapping 'accounts'" + ), + path=deque(["Fn::FindInMap", 2]), + ), + ) + ], + ), + ( + "Invalid FindInMap with an top level key that is a Ref to pseudo param", + {"Fn::FindInMap": ["foo", {"Ref": "AWS::AccountId"}, "second"]}, + [ + ( + None, + deque([]), + ValidationError( + ( + "{'Ref': 'AWS::AccountId'} is not a " + "first level key for mapping 'foo'" + ), + path=deque(["Fn::FindInMap", 1]), + ), + ) + ], + ), + ( + "Valid FindInMap with a second level key that is a Ref to pseudo param", + {"Fn::FindInMap": ["foo", "first", {"Ref": "AWS::AccountId"}]}, + [], + ), + ( + "Valid FindInMap with a bad third key", + {"Fn::FindInMap": ["foo", "first", "third"]}, + [ + ( + None, + deque([]), + ValidationError( + ( + "'third' is not one of ['second'] for " + "mapping 'foo' and key 'first'" + ), + path=deque(["Fn::FindInMap", 2]), + ), + ) + ], + ), + ( + "Valid FindInMap with integer types", + {"Fn::FindInMap": ["integers", 1, 2]}, + [("Value", deque(["Mappings", "integers", "1", "2"]), None)], + ), + ( + ( + "Valid FindInMap with a Ref to a parameter " + "with allowed values for top level key" + ), + {"Fn::FindInMap": ["environments", {"Ref": "Environment"}, "foo"]}, + [ + ("one", deque(["Mappings", "environments", "dev", "foo"]), None), + ("two", deque(["Mappings", "environments", "test", "foo"]), None), + ], + ), + ( + "Valid FindInMap with a Ref to a parameter for top level key", + {"Fn::FindInMap": ["environments", {"Ref": "RandomString"}, "foo"]}, + [], + ), + ( + ( + "Valid FindInMap with a Ref to accounts for top level " + "key Ref to a ramom string for second level key" + ), + { + "Fn::FindInMap": [ + "accounts", + {"Ref": "AWS::AccountId"}, + {"Ref": "RandomString"}, + ] + }, + [], + ), + ( + ( + "Valid FindInMap with a Ref to accounts for top level " + "key Ref to an allowed value parameter for second level key" + ), + { + "Fn::FindInMap": [ + "accounts", + {"Ref": "AWS::AccountId"}, + {"Ref": "Environment"}, + ] + }, + [], + ), + ( + ( + "Valid FindInMap with a Ref to a parameter " + "with allowed values for second level key" + ), + {"Fn::FindInMap": ["environments", "lion", {"Ref": "Environment"}]}, + [ + ("one", deque(["Mappings", "environments", "lion", "dev"]), None), + ("two", deque(["Mappings", "environments", "lion", "test"]), None), + ("three", deque(["Mappings", "environments", "lion", "prod"]), None), + ], + ), + ( + "Valid FindInMap with a Ref to a parameter for top level key", + {"Fn::FindInMap": ["environments", {"Ref": "RandomString"}, "foo"]}, + [], + ), + ( + "Valid FindInMap with a Ref to a parameter and a Ref to pseudo parameter", + { + "Fn::FindInMap": [ + "accounts", + {"Ref": "AWS::AccountId"}, + {"Ref": "RandomString"}, + ] + }, + [], + ), + ( + "Valid FindInMap with a bad second key and default", + {"Fn::FindInMap": ["foo", "first", "third", {"DefaultValue": "default"}]}, + [("default", deque([4, "DefaultValue"]), None)], + ), + ( + "Valid FindInMap with a transform on first key", + {"Fn::FindInMap": ["transformFirstKey", "first", "third"]}, + [], + ), + ( + "Valid FindInMap with a transform on second key", + {"Fn::FindInMap": ["transformSecondKey", "first", "third"]}, + [], + ), + ( + "Valid Sub with a resolvable values", + {"Fn::Sub": ["${a}-${b}", {"a": "foo", "b": "bar"}]}, + [("foo-bar", deque([]), None)], + ), + ( + "Valid Sub with empty parameters", + {"Fn::Sub": ["foo", {}]}, + [("foo", deque([]), None)], + ), + ], +) +def test_valid_functions(name, instance, response): + context = Context( + parameters={ + "RandomString": Parameter( + { + "Type": "String", + } + ), + "Environment": Parameter( + { + "Type": "String", + "AllowedValues": ["dev", "test", "prod"], + } + ), + }, + mappings=Mappings.create_from_dict( + { + "foo": {"first": {"second": "bar"}}, + "transformFirstKey": {"Fn::Transform": {"second": "bar"}}, + "transformSecondKey": {"first": {"Fn::Transform": "bar"}}, + "integers": {"1": {"2": "Value"}}, + "accounts": { + "123456789012": {"dev": "bar"}, + "us-east-1": {"bar": "foo"}, + }, + "environments": { + "dev": {"foo": "one"}, + "test": {"foo": "two"}, + "prod": {"bar": "three"}, + "lion": { + "dev": "one", + "test": "two", + "prod": "three", + }, + }, + } + ), + ) + _resolve(name, instance, response, context=context) + + +@pytest.mark.parametrize( + "name,instance,response", + [ + ( + "Invalid FindInMap with no mappings", + {"Fn::FindInMap": [{"Ref": "MyParameter"}, "B", "C"]}, + [ + ( + None, + deque([]), + ValidationError( + ("{'Ref': 'MyParameter'} is not one of []"), + path=deque(["Fn::FindInMap", 0]), + ), + ) + ], + ), + ( + "Invalid FindInMap with no mappings and default value", + {"Fn::FindInMap": ["A", "B", "C", {"DefaultValue": "default"}]}, + [("default", deque([4, "DefaultValue"]), None)], + ), + ], +) +def test_no_mapping(name, instance, response): + _resolve(name, instance, response) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_types.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..27e0981070d97d60c758df4c809c8b6409252149 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_types.py @@ -0,0 +1,24 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import unittest + +from cfnlint.jsonschema._types import TypeChecker, is_null +from cfnlint.jsonschema.exceptions import UndefinedTypeCheck + + +class TestCfnTypeChecker(unittest.TestCase): + def test_class(self): + emptyChecker = TypeChecker() + self.assertEqual(emptyChecker.type_checkers, {}) + self.assertEqual(str(emptyChecker), "") + + with self.assertRaises(UndefinedTypeCheck): + emptyChecker.is_type("foo", "bar") + + def test_null(self): + # Only a small number of places can use null + self.assertTrue(is_null(None, None)) + self.assertFalse(is_null(None, "")) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_utils.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4aa8c3e3c5c4475035a15e687867535bb060abad --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_utils.py @@ -0,0 +1,50 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import unittest + +from cfnlint.jsonschema._utils import equal, uniq, uniq_keys + + +class TestUtils(unittest.TestCase): + def test_equal(self): + self.assertTrue(equal("foo", "foo")) + self.assertFalse(equal("foo", "bar")) + self.assertTrue(equal(["foo"], ["foo"])) + self.assertFalse(equal(["foo"], ["bar"])) + self.assertFalse(equal(["foo"], ["foo", "bar"])) + self.assertTrue(equal({"foo": "bar"}, {"foo": "bar"})) + self.assertFalse(equal({"foo": "bar"}, {"bar": "foo"})) + self.assertFalse(equal({"foo": "bar"}, {"foo": "bar", "bar": "foo"})) + self.assertTrue(equal(True, True)) + self.assertFalse(equal(True, False)) + self.assertTrue(equal(1, 1)) + self.assertFalse(equal(1, 2)) + + self.assertTrue(equal(1, "1")) + self.assertFalse(equal({"foo": "bar"}, "1")) + + def test_uniq(self): + self.assertTrue(uniq(["foo", "bar"])) + self.assertFalse(uniq(["foo", "foo"])) + self.assertFalse(uniq([{"foo": "bar"}, {"foo": "bar"}])) + self.assertTrue(uniq([{"foo": "bar"}, ["foo", "bar"]])) + self.assertTrue(uniq([{"foo": "bar"}, {"bar": "foo"}])) + + self.assertFalse(uniq(["1", 1])) + + def test_uniq_keys(self): + # Bad structure + self.assertTrue(uniq_keys(["foo", "bar"], ["foo"])) + + # Unknown keys + self.assertTrue(uniq_keys([{"foo": "foo"}, {"bar": "bar"}], ["key"])) + + # Valid and invalid configuration + self.assertTrue(uniq_keys([{"foo": "foo"}, {"foo": "bar"}], ["foo"])) + self.assertFalse(uniq_keys([{"foo": "foo"}, {"foo": "foo"}], ["foo"])) + self.assertFalse( + uniq_keys([{"foo": "foo"}, {"bar": "bar"}, {"foo": "foo"}], ["foo"]) + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_validator.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_validator.py new file mode 100644 index 0000000000000000000000000000000000000000..c291a180744b7cbde1efc85007a0c6e2ab8a894c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_validator.py @@ -0,0 +1,1146 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque +from unittest.mock import patch + +import pytest + +from cfnlint.jsonschema.exceptions import ValidationError +from cfnlint.jsonschema.validators import CfnTemplateValidator + + +def fail(validator, errors, instance, schema): + for each in errors: + each.setdefault("message", "You told me to fail!") + yield ValidationError(**each) + + +@pytest.fixture +def validator(): + validators = {"fail": fail} + validator = CfnTemplateValidator({}).extend( + validators=validators, + )({}) + return validator + + +def _eq(self, other): + return self.message == other.message + + +def _lt(self, other): + return hash(self.message) < hash(other.message) + + +@pytest.mark.parametrize( + "name,schema,instance,expected", + [ + ("Success", {"fail": []}, "hello", []), + ( + "One Error", + {"fail": [{"message": "Whoops!"}]}, + "goodbye", + [ + ValidationError( + "Whoops!", + instance="goodbye", + schema={"fail": [{"message": "Whoops!"}]}, + validator="fail", + validator_value=[{"message": "Whoops!"}], + schema_path=deque(["fail"]), + ) + ], + ), + ( + "Multiple Errors", + { + "fail": [ + {"message": "First"}, + {"message": "Second!", "validator": "asdf"}, + {"message": "Third"}, + ] + }, + "goodbye", + [ + ValidationError( + "First", + instance="goodbye", + schema={"message": "First"}, + validator="fail", + validator_value=[{"message": "Whoops!"}], + schema_path=deque(["fail"]), + ), + ValidationError( + "Second!", + instance="goodbye", + schema={"message": "Second!", "validator": "asdf"}, + validator="asdf", + validator_value=[{"message": "Whoops!"}], + schema_path=deque(["fail"]), + ), + ValidationError( + "Third", + instance="goodbye", + schema={"message": "Third"}, + validator="fail", + validator_value=[{"message": "Whoops!"}], + schema_path=deque(["fail"]), + ), + ], + ), + ], +) +def test_validator(name, schema, instance, expected, validator): + validator = validator.evolve(schema=schema) + errs = list(validator.iter_errors(instance)) + assert errs == expected, f"{name!r} returned {errs!r}" + + +@pytest.mark.parametrize( + "name,schema,instance,expected", + [ + ( + "Valid type single", + {"type": "string"}, + "foo", + [], + ), + ( + "Valid type single array", + {"type": ["string"]}, + "foo", + [], + ), + ( + "Valid type many in array", + {"type": ["string", "object"]}, + "foo", + [], + ), + ( + "Single type failure", + {"type": "string"}, + [], + [ValidationError("[] is not of type 'string'")], + ), + ( + "Multiple type failure", + {"type": ["string", "object"]}, + [], + [ + ValidationError( + "[] is not of type 'string', 'object'", + ) + ], + ), + ( + "Multiple type failure", + {"type": "string"}, + [], + [ValidationError("[] is not of type 'string'")], + ), + ( + "valid minimum", + {"minimum": 2}, + 2, + [], + ), + ( + "valid minimum with string", + {"minimum": 2}, + "2", + [], + ), + ( + "valid minimum with wrong type as string", + {"minimum": 2}, + "a", + [], + ), + ( + "valid minimum with wrong type", + {"minimum": 2}, + {}, + [], + ), + ( + "valid minimum with wrong type boolean", + {"minimum": 2}, + True, + [], + ), + ( + "minimum", + {"minimum": 2}, + 1, + [ValidationError("1 is less than the minimum of 2")], + ), + ( + "minimum with string", + {"minimum": 2}, + "1", + [ + ValidationError( + "'1' is less than the minimum of 2", + ) + ], + ), + ( + "valid maximum", + {"maximum": 2}, + "2", + [], + ), + ( + "valid maximum with string", + {"minimum": 2}, + "2", + [], + ), + ( + "valid maximum with wrong type", + {"maximum": 2}, + {}, + [], + ), + ( + "valid maximum with wrong type boolean", + {"maximum": 2}, + True, + [], + ), + ( + "valid maximum with wrong type as string", + {"maximum": 2}, + "a", + [], + ), + ( + "maximum", + {"maximum": 0}, + 1, + [ValidationError("1 is greater than the maximum of 0")], + ), + ( + "maximum with string", + {"maximum": 0}, + "1", + [ + ValidationError( + "'1' is greater than the maximum of 0", + ) + ], + ), + ( + "valid dependencies wrong type", + {"dependencies": {"bar": ["foo"]}}, + [], + [], + ), + ( + "dependencies list", + {"dependencies": {"bar": ["foo"]}}, + {"bar": 2}, + [ + ValidationError( + "'foo' is a dependency of 'bar'", + ) + ], + ), + ( + "valid dependencies when property not included", + {"dependencies": {"bar": ["foo"]}}, + {"foo": 2}, + [], + ), + ( + "dependencies object", + {"dependencies": {"foo": {"required": ["bar"]}}}, + {"foo": 2}, + [ + ValidationError( + "'bar' is a required property", + ) + ], + ), + ( + "valid additionalProperties", + {"additionalProperties": True}, + {"foo": "bar"}, + [], + ), + ( + "valid additionalProperties with wrong type", + {"additionalProperties": False}, + [], + [], + ), + ( + "additionalProperties false", + {"additionalProperties": False}, + {"foo": 2}, + [ + ValidationError( + "Additional properties are not allowed ('foo' was unexpected)", + ) + ], + ), + ( + "additionalProperties false", + {"additionalProperties": False, "properties": {"foooooo": True}}, + {"foooooa": 2}, + [ + ValidationError( + ( + "Additional properties are not allowed ('foooooa' " + "was unexpected. Did you mean 'foooooo'?)" + ), + ) + ], + ), + ( + "additionalProperties object", + {"additionalProperties": {"type": "string"}}, + {"foo": []}, + [ + ValidationError( + "[] is not of type 'string'", + ) + ], + ), + ( + "additionalProperties with patternProperties", + {"additionalProperties": False, "patternProperties": {"^bar$": False}}, + {"foo": []}, + [ + ValidationError( + "'foo' does not match any of the regexes: '^bar$'", + ) + ], + ), + ( + "additionalProperties with multiple properties", + {"additionalProperties": False}, + {"foo": [], "bar": []}, + [ + ValidationError( + "Additional properties are not allowed ('foo' was unexpected)", + ), + ValidationError( + "Additional properties are not allowed ('bar' was unexpected)", + ), + ], + ), + ( + "valid const", + {"const": 12}, + 12, + [], + ), + ( + "const", + {"const": 12}, + {"foo": "bar"}, + [ + ValidationError( + "12 was expected", + ) + ], + ), + ( + "valid enum", + {"enum": ["bar"]}, + "bar", + [], + ), + ( + "enum", + {"enum": ["bar"]}, + "foo", + [ + ValidationError( + "'foo' is not one of ['bar']", + validator="enum", + schema_path=deque(["enum"]), + ) + ], + ), + ( + "valid enum int", + {"enum": [0]}, + "0", + [], + ), + ( + "enum int", + {"enum": [0]}, + 1, + [ValidationError("1 is not one of [0]")], + ), + ( + "format default message", + {"format": "date-time"}, + "bla", + [ + ValidationError( + "'bla' is not a 'date-time'", + ) + ], + ), + ( + "a false schema", + False, + "foo", + [ValidationError("False schema does not allow 'foo'")], + ), + ( + "valid if", + {"if": {"type": "string"}, "then": True, "else": False}, + "", + [], + ), + ( + "if then with false", + {"if": {"type": "string"}, "then": False, "else": True}, + "a", + [ + ValidationError( + "False schema does not allow 'a'", + ) + ], + ), + ( + "valid else", + {"if": {"type": "string"}, "then": False, "else": True}, + [], + [], + ), + ( + "if then else with false", + {"if": {"type": "string"}, "then": True, "else": False}, + [], + [ + ValidationError( + "False schema does not allow []", + ) + ], + ), + ( + "valid items", + {"items": {"type": "string"}}, + ["foo"], + [], + ), + ( + "valid items with wrong type", + {"items": {"type": "string"}}, + {}, + [], + ), + ( + "items object", + {"items": {"type": "string"}}, + [[]], + [ + ValidationError( + "[] is not of type 'string'", + ) + ], + ), + ( + "items list", + {"items": [{"type": "string"}]}, + [[]], + [ + ValidationError( + "[] is not of type 'string'", + ) + ], + ), + ( + "valid multipleOf", + {"multipleOf": 2}, + 2, + [], + ), + ( + "valid multipleOf with string", + {"multipleOf": 2}, + "2", + [], + ), + ( + "valid multipleOf with wrong type", + {"multipleOf": 2}, + [], + [], + ), + ( + "valid multipleOf with wrong type string", + {"multipleOf": 2}, + "A", + [], + ), + ( + "multipleOf", + {"multipleOf": 2}, + 3, + [ + ValidationError( + "3 is not a multiple of 2", + ) + ], + ), + ( + "multipleOf with string", + {"multipleOf": 2}, + "3", + [ + ValidationError( + "'3' is not a multiple of 2", + ) + ], + ), + ( + "multipleOf with number", + {"multipleOf": 2.0}, + "3", + [ + ValidationError( + "'3' is not a multiple of 2.0", + ) + ], + ), + ( + "valid minItems", + {"minItems": 1}, + ["foo"], + [], + ), + ( + "valid minItems with wrong type", + {"minItems": 1}, + {}, + [], + ), + ( + "minItems", + {"minItems": 2}, + [], + [ + ValidationError( + "[] is too short (2)", + ) + ], + ), + ( + "valid maxItems", + {"maxItems": 1}, + ["foo"], + [], + ), + ( + "valid maxItems with wrong type", + {"maxItems": 1}, + {}, + [], + ), + ( + "maxItems", + {"maxItems": 0}, + ["foo"], + [ + ValidationError( + "['foo'] is too long (0)", + ) + ], + ), + ( + "valid minLength", + {"minLength": 1}, + "foo", + [], + ), + ( + "valid minLength with wrong type", + {"minLength": 1}, + 1, + [], + ), + ( + "minLength", + {"minLength": 2}, + "", + [ + ValidationError( + "'' is shorter than 2", + ) + ], + ), + ( + "valid maxLength", + {"maxLength": 3}, + "foo", + [], + ), + ( + "valid maxLength with wrong type", + {"maxLength": 1}, + 1, + [], + ), + ( + "maxLength", + {"maxLength": 0}, + "foo", + [ + ValidationError( + "'foo' is longer than 0", + ) + ], + ), + ( + "valid not", + {"not": False}, + True, + [], + ), + ( + "not", + {"not": True}, + False, + [ + ValidationError( + "False should not be valid under True", + ) + ], + ), + ( + "valid pattern", + {"pattern": "^foo$"}, + "foo", + [], + ), + ( + "valid pattern with wrong type", + {"pattern": "^foo$"}, + {}, + [], + ), + ( + "pattern", + {"pattern": "^a*$"}, + "bbb", + [ + ValidationError( + "'bbb' does not match '^a*$'", + ) + ], + ), + ( + "valid contains", + {"contains": {"type": "string"}}, + ["foo"], + [], + ), + ( + "valid contains with wrong type", + {"contains": {"type": "string"}}, + {}, + [], + ), + ( + "contains", + {"contains": {"type": "string"}}, + [], + [ + ValidationError( + "[] does not contain items matching the given schema", + ) + ], + ), + ( + "valid exclusiveMinimum", + {"exclusiveMinimum": 4}, + 5, + [], + ), + ( + "valid exclusiveMinimum with wrong type", + {"exclusiveMinimum": 4}, + {}, + [], + ), + ( + "valid exclusiveMinimum with non number string", + {"exclusiveMinimum": 4}, + "foo", + [], + ), + ( + "exclusiveMinimum", + {"exclusiveMinimum": 5}, + 5, + [ + ValidationError( + "5 is less than or equal to the minimum of 5", + ) + ], + ), + ( + "exclusiveMinimum with string", + {"exclusiveMinimum": 5}, + "5", + [ + ValidationError( + "'5' is less than or equal to the minimum of 5", + ) + ], + ), + ( + "valid exclusiveMaximum", + {"exclusiveMaximum": 5}, + 4, + [], + ), + ( + "valid exclusiveMaximum with wrong type", + {"exclusiveMaximum": 5}, + {}, + [], + ), + ( + "valid exclusiveMaximum with wrong string type", + {"exclusiveMaximum": 5}, + "foo", + [], + ), + ( + "exclusiveMaximum with string", + {"exclusiveMaximum": 5}, + "5", + [ + ValidationError( + "'5' is greater than or equal to the maximum of 5", + ) + ], + ), + ( + "valid required", + {"required": ["foo"]}, + {"foo": False}, + [], + ), + ( + "valid required wrong type", + {"required": ["foo"]}, + [], + [], + ), + ( + "required", + {"required": ["foo"]}, + {}, + [ + ValidationError( + "'foo' is a required property", + ) + ], + ), + ( + "valid minProperties", + {"minProperties": 1}, + {"foo": False}, + [], + ), + ( + "valid minProperties with wrong type", + {"minProperties": 1}, + [], + [], + ), + ( + "minProperties", + {"minProperties": 1}, + {}, + [ + ValidationError( + "{} does not have enough properties", + ) + ], + ), + ( + "valid maxProperties", + {"maxProperties": 1}, + {"foo": False}, + [], + ), + ( + "valid maxProperties with wrong type", + {"maxProperties": 1}, + [], + [], + ), + ( + "maxProperties", + {"maxProperties": 1}, + {"foo": {}, "bar": {}}, + [ + ValidationError( + "{'foo': {}, 'bar': {}} has too many properties", + ) + ], + ), + ( + "valid patternProperties", + {"patternProperties": {"^foo$": True}}, + {"foo": {}}, + [], + ), + ( + "valid patternProperties with wrong type", + {"patternProperties": {"^foo$": True}}, + [], + [], + ), + ( + "patternProperties", + {"patternProperties": {"^foo$": False}}, + {"foo": "bar"}, + [ + ValidationError( + "False schema does not allow 'bar'", + ) + ], + ), + ( + "valid properties", + {"properties": {"foo": True}}, + {"foo": "bar"}, + [], + ), + ( + "valid properties with wrong type", + {"properties": {"foo": True}}, + [], + [], + ), + ( + "properties", + {"properties": {"foo": False}}, + {"foo": "bar"}, + [ + ValidationError( + "False schema does not allow 'bar'", + ) + ], + ), + ( + "valid propertyNames", + {"propertyNames": {"pattern": "^bar$"}}, + {"bar": "foo"}, + [], + ), + ( + "valid propertyNames with wrong type", + {"propertyNames": {"pattern": "^bar$"}}, + [], + [], + ), + ( + "propertyNames", + {"propertyNames": {"pattern": "^bar$"}}, + {"foo": "bar"}, + [ + ValidationError( + "'foo' does not match '^bar$'", + ) + ], + ), + ( + "valid oneOf matches none", + {"oneOf": [True]}, + False, + [], + ), + ( + "oneOf matches none", + {"oneOf": [False]}, + {}, + [ + ValidationError( + "{} is not valid under any of the given schemas", + ) + ], + ), + ( + "oneOf matches too many", + {"oneOf": [True, True]}, + {}, + [ + ValidationError( + "{} is valid under each of True, True", + ) + ], + ), + ( + "valid allOf", + {"allOf": [True, True]}, + False, + [], + ), + ( + "allOf matches one False", + {"allOf": [True, False]}, + {}, + [ + ValidationError( + "False schema does not allow {}", + ) + ], + ), + ( + "allOf matches multiple False", + {"allOf": [True, False, False]}, + {}, + [ + ValidationError( + "False schema does not allow {}", + ), + ValidationError( + "False schema does not allow {}", + ), + ], + ), + ( + "valid anyOf matches more than one", + {"anyOf": [True, True]}, + False, + [], + ), + ( + "anyOf matches none", + {"anyOf": [False, False]}, + {}, + [ + ValidationError( + "{} is not valid under any of the given schemas", + ) + ], + ), + ( + "valid uniqueItems", + {"uniqueItems": True}, + [1, 2, "3"], + [], + ), + ( + "uniqueItems", + {"uniqueItems": True}, + [1, 2, "1"], + [ + ValidationError( + "[1, 2, '1'] has non-unique elements", + ) + ], + ), + ( + "valid requiredOr", + {"requiredOr": ["foo", "bar"]}, + {"foo": {}}, + [], + ), + ( + "valid requiredOr with wrong type", + {"requiredOr": ["foo", "bar"]}, + [], + [], + ), + ( + "invalid requiredOr with empty object", + {"requiredOr": ["foo", "bar"]}, + {}, + [ + ValidationError( + "One of ['foo', 'bar'] is a required property", + ) + ], + ), + ( + "valid requiredXor", + {"requiredXor": ["foo", "bar"]}, + {"foo": {}}, + [], + ), + ( + "valid requiredXor with wrong type", + {"requiredXor": ["foo", "bar"]}, + [], + [], + ), + ( + "requiredXor", + {"requiredXor": ["foo", "bar"]}, + {}, + [ + ValidationError( + "Only one of ['foo', 'bar'] is a required property", + ) + ], + ), + ( + "requiredXor with multiple errors", + {"requiredXor": ["foo", "bar"]}, + {"foo": "foo", "bar": "bar"}, + [ + ValidationError( + "Only one of ['foo', 'bar'] is a required property", + ), + ValidationError( + "Only one of ['foo', 'bar'] is a required property", + ), + ], + ), + ( + "valid uniqueKeys", + {"uniqueKeys": ["Name"]}, + [{"Name": "foo"}, {"Name": "bar"}], + [], + ), + ( + "valid uniqueKeys with wrong types", + {"uniqueKeys": ["Name"]}, + {"Name": "foo"}, + [], + ), + ( + "valid uniqueKeys with wrong type in array", + {"uniqueKeys": ["Name"]}, + [{"Name": "foo"}, []], + [], + ), + ( + "uniqueKeys", + {"uniqueKeys": ["Name"]}, + [ + { + "Name": "foo", + }, + { + "Name": "foo", + }, + ], + [ + ValidationError( + "[{'Name': 'foo'}, {'Name': 'foo'}] has non-unique " + "elements for keys ['Name']", + ) + ], + ), + ( + "valid dependentExcluded when wrong type", + {"dependentExcluded": {"foo": ["bar"]}}, + [], + [], + ), + ( + "valid dependentExcluded when not specified", + {"dependentExcluded": {"foo": ["bar"]}}, + {"bar": "bar"}, + [], + ), + ( + "dependentExcluded", + {"dependentExcluded": {"foo": ["bar"], "bar": ["foo"]}}, + {"foo": "foo", "bar": "bar"}, + [ + ValidationError("'bar' should not be included with 'foo'"), + ValidationError("'foo' should not be included with 'bar'"), + ], + ), + ( + "dependentRequired", + {"dependentRequired": {"foo": ["bar"]}}, + {"foo": "foo"}, + [ + ValidationError("'bar' is a dependency of 'foo'"), + ], + ), + ( + "dependentRequired with multiple properties", + {"dependentRequired": {"foo": ["a", "b"]}}, + {"foo": "foo"}, + [ + ValidationError("'a' is a dependency of 'foo'"), + ValidationError("'b' is a dependency of 'foo'"), + ], + ), + ( + "valid dependentRequired when property not included", + {"dependentRequired": {"foo": ["a", "b"]}}, + {"bar": "bar"}, + [], + ), + ( + "valid dependentRequired", + {"dependentRequired": {"foo": ["bar"]}}, + {"foo": "foo", "bar": "bar"}, + [], + ), + ( + "valid dependentRequired with wrong type", + {"dependentRequired": {"foo": ["bar"]}}, + [], + [], + ), + ( + "valid prefixItems", + {"prefixItems": [{"type": "string"}]}, + ["foo"], + [], + ), + ( + "invalid prefixItems with wrong type", + {"prefixItems": [{"type": "string"}]}, + [1], + [ + ValidationError("1 is not of type 'string'"), + ], + ), + ( + "valid enum case insensitive", + {"enumCaseInsensitive": ["A"]}, + "a", + [], + ), + ( + "valid enum case insensitive with non string", + {"enumCaseInsensitive": ["a", 1]}, + "A", + [], + ), + ( + "valid enum case insensitive with non string value", + {"enumCaseInsensitive": ["A", 1]}, + 1, + [], + ), + ( + "valid enum case insensitive with non string value", + {"enumCaseInsensitive": ["A"]}, + "b", + [ + ValidationError("'b' is not one of ['a'] (case-insensitive)"), + ], + ), + ], +) +@patch.object(ValidationError, "__eq__", spec=True, new=_eq) +@patch.object(ValidationError, "__lt__", spec=True, new=_lt) +def test_messages(name, schema, instance, expected, validator): + validator = validator.evolve(schema=schema) + errs = list(validator.iter_errors(instance)) + assert sorted(errs) == sorted(expected), f"{name!r} returned {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_validator_exceptions.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_validator_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..a1dc08b1a602104fd2a16d85b95b8992a75a6efd --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_validator_exceptions.py @@ -0,0 +1,47 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema.exceptions import ValidationError +from cfnlint.jsonschema.validators import CfnTemplateValidator + + +def fail(validator, errors, instance, schema): + raise ValueError(f"Bad {errors!r}") + + +@pytest.fixture +def validator(): + validators = { + "foo": fail, + "bar": fail, + } + validator = CfnTemplateValidator({}).extend( + validators=validators, + )({"foo": True, "bar": False}) + return validator + + +def test_validator_raises_exception(validator): + + errs = list(validator.iter_errors("")) + + assert errs == [ + ValidationError( + "Exception 'Bad True' raised while validating 'foo'", + validator="foo", + schema_path=deque(["foo"]), + path=deque([]), + ), + ValidationError( + "Exception 'Bad False' raised while validating 'bar'", + validator="bar", + schema_path=deque(["bar"]), + path=deque([]), + ), + ] diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_validator_resolver.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_validator_resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..94feb8af26e783e70bc4fc994532686da7841f1d --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/jsonschema/test_validator_resolver.py @@ -0,0 +1,56 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque +from typing import Any + +import pytest + +from cfnlint.jsonschema._resolvers_cfn import ResolutionResult, Validator +from cfnlint.jsonschema.exceptions import ValidationError +from cfnlint.jsonschema.validators import CfnTemplateValidator + + +def _resolver(validator: Validator, instance: Any) -> ResolutionResult: + if instance == "fail": + yield None, validator, ValidationError("Foo") + return + + yield "foo", validator, None + + +@pytest.fixture +def validator(): + validator = CfnTemplateValidator({}) + validator.fn_resolvers = { + "Ref": _resolver, + } + validator.context = validator.context.evolve(functions=["Ref"]) + return validator + + +@pytest.mark.parametrize( + "name,instance,expected", + [ + ( + "Valid with function", + {"Ref": "fail"}, + [(None, ValidationError("Foo", path=deque(["Ref"])))], + ), + ("Valid string", "foo", [("foo", None)]), + ("Valid with function", {"Ref": "pass"}, [("foo", None)]), + ], +) +def test_validator_resolver(name, instance, expected, validator): + results = list(validator.resolve_value(instance)) + + if len(results) > len(expected): + for result, expected_result in zip(results, expected): + assert result[0] == expected_result[0] + assert result[2] == expected_result[1] + else: + for expected_result, result in zip(expected, results): + assert result[0] == expected_result[0] + assert result[2] == expected_result[1] diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/maintenance/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/maintenance/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/maintenance/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/maintenance/test_update_documentation.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/maintenance/test_update_documentation.py new file mode 100644 index 0000000000000000000000000000000000000000..6613e85a4f1d779ed5c9691afce0932286f413a9 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/maintenance/test_update_documentation.py @@ -0,0 +1,85 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import logging +from test.testlib.testcase import BaseTestCase +from unittest.mock import call, mock_open, patch + +import cfnlint.maintenance +from cfnlint.config import _DEFAULT_RULESDIR +from cfnlint.rules import Rules + +LOGGER = logging.getLogger("cfnlint.maintenance") +LOGGER.addHandler(logging.NullHandler()) + + +class TestUpdateDocumentation(BaseTestCase): + """Used for Testing Updating the Documentation""" + + TEST_TEXT = """ +Regular Text +## Rules +""" + + def test_update_docs(self): + collection = Rules.create_from_directory(_DEFAULT_RULESDIR + "/errors") + builtin_module_name = "builtins" + + mo = mock_open(read_data=self.TEST_TEXT) + mo.return_value.__iter__ = lambda self: self + mo.return_value.__iter__ = lambda self: iter(self.readline, "") + with patch("{}.open".format(builtin_module_name), mo) as mock_builtin_open: + cfnlint.maintenance.update_documentation(collection) + + expected_calls = [ + call("\n"), + call("Regular Text\n"), + call("## Rules\n"), + call( + "(_This documentation is generated by running `cfn-lint" + " --update-documentation`, do not alter this manually_)\n\n" + ), + call( + "The following **{}** rules are applied by this linter:\n\n".format( + len(collection) + 3 + ) + ), + call( + "| Rule ID | Title | Description | Config
(Name:Type:Default)" + " | Source | Tags |\n" + ), + call( + "| -------- | ----- | ----------- | ---------- | ------ | ---- |\n" + ), + call( + '| [E0000]' + "(../src/cfnlint/rules/errors/parse.py) |" + " Parsing error found when parsing the template | Checks for" + " JSON/YAML formatting errors in your template | |" + " [Source](https://github.com/aws-cloudformation/cfn-lint) |" + " `base` |\n" + ), + call( + '| [E0001]' + "(../src/cfnlint/rules/errors/transform.py) |" + " Error found when transforming the template | Errors found when" + " performing transformation on the template | |" + " [Source](https://github.com/aws-cloudformation/cfn-lint) |" + " `base`,`transform` |\n" + ), + call( + '| [E0002]' + "(../src/cfnlint/rules/errors/rule.py) |" + " Error processing rule on the template | Errors found when" + " processing a rule on the template | |" + " [Source](https://github.com/aws-cloudformation/cfn-lint) |" + " `base`,`rule` |\n" + ), + call("\n\\* experimental rules\n"), + ] + mock_builtin_open.return_value.write.assert_has_calls(expected_calls) + self.assertEqual( + len(expected_calls), mock_builtin_open.return_value.write.call_count + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/maintenance/test_update_iam_policies.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/maintenance/test_update_iam_policies.py new file mode 100644 index 0000000000000000000000000000000000000000..72eba28dc837d482f234c22877b8623619a232e7 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/maintenance/test_update_iam_policies.py @@ -0,0 +1,46 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import logging +from test.testlib.testcase import BaseTestCase +from unittest.mock import patch + +import cfnlint.maintenance + +LOGGER = logging.getLogger("cfnlint.maintenance") +LOGGER.addHandler(logging.NullHandler()) + + +class TestUpdateIamPolicies(BaseTestCase): + """Used for Testing Rules""" + + @patch("cfnlint.maintenance.get_url_content") + @patch("cfnlint.maintenance.json.dump") + def test_update_iam_policies(self, mock_json_dump, mock_content): + """Success update iam policies""" + + mock_content.return_value = ( + 'app.PolicyEditorConfig={"serviceMap":{"Manage Amazon API' + ' Gateway":{"Actions":[]},"Amazon Kinesis Video Streams":{"Actions":[]}}}' + ) + + builtin_module_name = "builtins" + + with patch("{}.open".format(builtin_module_name)) as mock_builtin_open: + cfnlint.maintenance.update_iam_policies() + mock_json_dump.assert_called_with( + { + "serviceMap": { + "Manage Amazon API Gateway": {"Actions": ["HEAD", "OPTIONS"]}, + "Amazon Kinesis Video Streams": { + "Actions": ["StartStreamEncryption"] + }, + } + }, + mock_builtin_open.return_value.__enter__.return_value, + indent=1, + separators=(",", ": "), + sort_keys=True, + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/override/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/override/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/override/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/override/test_complete.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/override/test_complete.py new file mode 100644 index 0000000000000000000000000000000000000000..d8961513455f61b14d31ecacbd58bba043a38c6e --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/override/test_complete.py @@ -0,0 +1,63 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase + +from cfnlint import ConfigMixIn +from cfnlint.config import _DEFAULT_RULESDIR +from cfnlint.rules import Rules +from cfnlint.runner import Runner +from cfnlint.schema.manager import PROVIDER_SCHEMA_MANAGER + + +class TestComplete(BaseTestCase): + """Used for Testing Rules""" + + def setUp(self): + """Setup""" + self.collection = Rules.create_from_directory(_DEFAULT_RULESDIR) + self.region = "us-east-1" + + def tearDown(self): + """Tear Down""" + # Reset the Spec override to prevent other tests to fail + PROVIDER_SCHEMA_MANAGER.reset() + + def test_success_run(self): + """Success test""" + filename = "test/fixtures/templates/good/override/complete.yaml" + + PROVIDER_SCHEMA_MANAGER.patch( + "test/fixtures/templates/override_spec/complete.json", regions=[self.region] + ) + + config = ConfigMixIn( + regions=[self.region], + templates=[filename], + ) + runner = Runner(config) + runner.rules = self.collection + + self.assertEqual([], list(runner.run())) + + def test_fail_run(self): + """Failure test required""" + filename = "test/fixtures/templates/bad/override/complete.yaml" + + PROVIDER_SCHEMA_MANAGER.patch( + "test/fixtures/templates/override_spec/complete.json", regions=[self.region] + ) + + config = ConfigMixIn( + regions=[self.region], + templates=[filename], + ignore_checks=["I", "W", "E"], + mandatory_checks=["E3001", "E3003", "E3006"], + ) + runner = Runner(config) + runner.rules = self.collection + + errs = list(runner.run()) + self.assertEqual(3, len(errs), errs) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/override/test_exclude.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/override/test_exclude.py new file mode 100644 index 0000000000000000000000000000000000000000..bc8d8da2853d8444f03dfc1a5e7c76cbb3e3b9dc --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/override/test_exclude.py @@ -0,0 +1,61 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase + +from cfnlint import ConfigMixIn +from cfnlint.config import _DEFAULT_RULESDIR +from cfnlint.rules import Rules +from cfnlint.runner import Runner +from cfnlint.schema.manager import PROVIDER_SCHEMA_MANAGER + + +class TestExclude(BaseTestCase): + """Used for Testing Rules""" + + def setUp(self): + """Setup""" + self.collection = Rules.create_from_directory(_DEFAULT_RULESDIR) + self.region = "us-east-1" + + def tearDown(self): + """Tear Down""" + # Reset the Spec override to prevent other tests to fail + PROVIDER_SCHEMA_MANAGER.reset() + + def test_success_run(self): + """Success test""" + filename = "test/fixtures/templates/good/generic.yaml" + + PROVIDER_SCHEMA_MANAGER.patch( + "test/fixtures/templates/override_spec/exclude.json", regions=[self.region] + ) + + config = ConfigMixIn( + regions=[self.region], + templates=[filename], + ) + runner = Runner(config) + runner.rules = self.collection + + self.assertEqual([], list(runner.run())) + + def test_fail_run(self): + """Failure test required""" + filename = "test/fixtures/templates/bad/override/exclude.yaml" + + PROVIDER_SCHEMA_MANAGER.patch( + "test/fixtures/templates/override_spec/exclude.json", regions=[self.region] + ) + + config = ConfigMixIn( + regions=[self.region], + templates=[filename], + ) + runner = Runner(config) + runner.rules = self.collection + + errs = list(runner.run()) + self.assertEqual(2, len(errs)) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/override/test_include.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/override/test_include.py new file mode 100644 index 0000000000000000000000000000000000000000..0141257ca598f7643a9480731f3b365741339b59 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/override/test_include.py @@ -0,0 +1,46 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase + +from cfnlint import ConfigMixIn +from cfnlint.config import _DEFAULT_RULESDIR +from cfnlint.rules import Rules +from cfnlint.runner import Runner +from cfnlint.schema.manager import PROVIDER_SCHEMA_MANAGER + + +class TestInclude(BaseTestCase): + """Used for Testing Rules""" + + def setUp(self): + """Setup""" + self.collection = Rules.create_from_directory(_DEFAULT_RULESDIR) + self.region = "us-east-1" + + def tearDown(self): + """Tear Down""" + # Reset the Spec override to prevent other tests to fail + PROVIDER_SCHEMA_MANAGER.reset() + + def test_fail_run(self): + """Failure test required""" + filename = "test/fixtures/templates/bad/override/include.yaml" + + PROVIDER_SCHEMA_MANAGER.patch( + "test/fixtures/templates/override_spec/include.json", regions=[self.region] + ) + + config = ConfigMixIn( + regions=[self.region], + templates=[filename], + ignore_checks=["I", "W", "E"], + mandatory_checks=["E3006"], + ) + runner = Runner(config) + runner.rules = self.collection + + errs = list(runner.run()) + self.assertEqual(2, len(errs)) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/override/test_required.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/override/test_required.py new file mode 100644 index 0000000000000000000000000000000000000000..f5745dd1322e331ea8df5bdc203ab87bf7b643e7 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/override/test_required.py @@ -0,0 +1,63 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase + +from cfnlint import ConfigMixIn +from cfnlint.config import _DEFAULT_RULESDIR +from cfnlint.rules import Rules +from cfnlint.runner import Runner +from cfnlint.schema.manager import PROVIDER_SCHEMA_MANAGER + + +class TestOverrideRequired(BaseTestCase): + """Used for Testing Rules""" + + def setUp(self): + """Setup""" + self.collection = Rules.create_from_directory(_DEFAULT_RULESDIR) + self.region = "us-east-1" + + def tearDown(self): + """Tear Down""" + # Reset the Spec override to prevent other tests to fail + PROVIDER_SCHEMA_MANAGER.reset() + + def test_success_run(self): + """Success test""" + filename = "test/fixtures/templates/good/override/required.yaml" + + PROVIDER_SCHEMA_MANAGER.patch( + "test/fixtures/templates/override_spec/required.json", regions=[self.region] + ) + + config = ConfigMixIn( + regions=[self.region], + templates=[filename], + ) + runner = Runner(config) + runner.rules = self.collection + + self.assertEqual([], list(runner.run())) + + def test_fail_run(self): + """Failure test required""" + filename = "test/fixtures/templates/bad/override/required.yaml" + + PROVIDER_SCHEMA_MANAGER.patch( + "test/fixtures/templates/override_spec/required.json", regions=[self.region] + ) + + config = ConfigMixIn( + regions=[self.region], + templates=[filename], + ignore_checks=["I", "W", "E"], + mandatory_checks=["E3003"], + ) + runner = Runner(config) + runner.rules = self.collection + + errs = list(runner.run()) + self.assertEqual(1, len(errs), errs) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/rule/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/rule/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/rule/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/rule/test_matching.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/rule/test_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..efe7a20f8631ff129aefafeb22b8b6220638bb91 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/rule/test_matching.py @@ -0,0 +1,59 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase +from typing import Any + +from cfnlint.rules import CloudFormationLintRule, Match, RuleMatch +from cfnlint.rules._rule import matching + + +class rule(CloudFormationLintRule): + id: str = "ETest" + pass + + +rule_match = RuleMatch([], "Message", rule=rule(), location=(0, 0, 0, 0)) + + +class TestMatching(BaseTestCase): + """Test Matching Wrapper""" + + def example(self: Any, *args: Any, **kwargs: Any): + return [rule_match] + + def test_matching_location(self): + f = matching("example") + r = f(self.example) + t = r(self, "", None) + self.assertEqual( + list(t), + [ + Match( + linenumber=1, + columnnumber=1, + linenumberend=1, + columnnumberend=1, + filename="", + rule=rule(), + message="Message", + rulematch_obj=rule_match, + ) + ], + ) + + def test_compare(self): + rule_match_1 = RuleMatch( + ["path"], "Message", rule=rule(), location=(0, 0, 0, 0) + ) + rule_match_2 = RuleMatch( + ["path"], "Message", rule=rule(), location=(0, 0, 0, 0) + ) + self.assertEqual(rule_match_1, rule_match_2) + + rule_match_3 = RuleMatch( + ["path"], "New Message", rule=rule(), location=(1, 1, 1, 1) + ) + self.assertNotEqual(rule_match_1, rule_match_3) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/rule/test_rule.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/rule/test_rule.py new file mode 100644 index 0000000000000000000000000000000000000000..2e9f326f799e81912c6656b1459f578bcff0d8d8 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/rule/test_rule.py @@ -0,0 +1,163 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase + +from cfnlint.rules import CloudFormationLintRule + + +class TestCloudFormationRule(BaseTestCase): + """Test CloudFormation Rule""" + + def test_base(self): + """Test Base Rule""" + + class TestRule(CloudFormationLintRule): + """Def Rule""" + + id = "E1000" + shortdesc = "Test Rule" + description = "Test Rule Description" + source_url = "https://github.com/aws-cloudformation/cfn-lint/" + tags = ["resources"] + + self.assertEqual(TestRule.id, "E1000") + self.assertEqual(TestRule.shortdesc, "Test Rule") + self.assertEqual(TestRule.description, "Test Rule Description") + self.assertEqual( + TestRule.source_url, + "https://github.com/aws-cloudformation/cfn-lint/", + ) + self.assertEqual(TestRule.tags, ["resources"]) + + def test_config(self): + """Test Configuration""" + + class TestRule(CloudFormationLintRule): + """Def Rule""" + + id = "E1000" + shortdesc = "Test Rule" + description = "Test Rule" + source_url = "https://github.com/aws-cloudformation/cfn-lint/" + tags = ["resources"] + + def __init__(self): + """Init""" + super(TestRule, self).__init__() + self.config_definition = { + "testBoolean": {"default": True, "type": "boolean"}, + "testString": {"default": "default", "type": "string"}, + "testInteger": {"default": 1, "type": "integer"}, + "testListBoolean": { + "type": "list", + "itemtype": "boolean", + "default": [False], + }, + "testListString": { + "type": "list", + "itemtype": "string", + "default": ["bar"], + }, + "testListInteger": { + "type": "list", + "itemtype": "integer", + "default": [0], + }, + } + self.configure() + + def get_config(self): + """Get the Config""" + return self.config + + rule = TestRule() + config = rule.get_config() + self.assertTrue(config.get("testBoolean")) + self.assertEqual(config.get("testString"), "default") + self.assertEqual(config.get("testInteger"), 1) + self.assertListEqual(config.get("testListBoolean"), [False]) + self.assertListEqual(config.get("testListString"), ["bar"]) + self.assertListEqual(config.get("testListInteger"), [0]) + + rule.configure( + { + "testBoolean": "false", + "testString": "new", + "testInteger": 2, + "testListBoolean": ["true"], + "testListString": ["foo"], + "testListInteger": [1], + } + ) + + self.assertFalse(config.get("testBoolean")) + self.assertEqual(config.get("testString"), "new") + self.assertEqual(config.get("testInteger"), 2) + self.assertListEqual(config.get("testListBoolean"), [True]) + self.assertListEqual(config.get("testListString"), ["foo"]) + self.assertListEqual(config.get("testListInteger"), [1]) + + def test_experimental(self): + """Test Configuration""" + + class TestRule(CloudFormationLintRule): + """Def Rule""" + + id = "E1000" + shortdesc = "Test Rule" + description = "Test Rule" + source_url = "https://github.com/aws-cloudformation/cfn-lint/" + tags = ["resources"] + + def __init__(self): + """Init""" + super(TestRule, self).__init__() + self.config_definition = { + "experimental": {"default": True, "type": "boolean"}, + } + self.configure() + + def get_config(self): + """Get the Config""" + return self.config + + rule = TestRule() + rule.configure({}, True) + config = rule.get_config() + self.assertTrue(config.get("experimental")) + + rule.configure({}, False) + config = rule.get_config() + self.assertFalse(config.get("experimental")) + + def test_non_configured_experimental(self): + class TestRule(CloudFormationLintRule): + """Def Rule""" + + id = "E1000" + shortdesc = "Test Rule" + description = "Test Rule" + source_url = "https://github.com/aws-cloudformation/cfn-lint/" + tags = ["resources"] + + rule = TestRule() + + rule.configure({}, True) + self.assertFalse(rule.config.get("experimental")) + + def test_none_equal(self): + class TestRule(CloudFormationLintRule): + """Def Rule""" + + id = "E1000" + shortdesc = "Test Rule" + description = "Test Rule" + source_url = "https://github.com/aws-cloudformation/cfn-lint/" + tags = ["resources"] + + rule = TestRule() + + self.assertNotEqual(rule, None) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/rule/test_rule_child.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/rule/test_rule_child.py new file mode 100644 index 0000000000000000000000000000000000000000..1c2f448d42217c5c35a8edbc3d1ba7a0e960ffb3 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/rule/test_rule_child.py @@ -0,0 +1,169 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase +from typing import Any, Dict + +from cfnlint import ConfigMixIn +from cfnlint.decode.decode import decode_str +from cfnlint.rules import CloudFormationLintRule, Match, RuleMatch, Rules +from cfnlint.runner import TemplateRunner + + +class TestCloudFormationRuleChild(BaseTestCase): + """Test CloudFormation Rule""" + + def test_child_rules(self) -> None: + class TestRuleParent(CloudFormationLintRule): + """Def Rule""" + + id = "E1000" + shortdesc = "Test Rule" + description = "Test Rule Description" + source_url = "https://github.com/aws-cloudformation/cfn-lint/" + tags = ["resources"] + child_rules: Dict[str, Any] = {"E1001": None} + + def match(self, _): + return self.child_rules["E1001"].failure() + + class TestRuleChild(CloudFormationLintRule): + """Def Rule""" + + id = "E1001" + shortdesc = "Test Rule" + description = "Test Rule Description" + source_url = "https://github.com/aws-cloudformation/cfn-lint/" + tags = ["resources"] + + def failure(self): + return [RuleMatch(["key"], "failure", rule=self)] + + rule_collection = Rules() + test_rule_parent = TestRuleParent() + test_rule_child = TestRuleChild() + rule_collection.register(test_rule_parent) + rule_collection.register(test_rule_child) + + template, _ = decode_str('{"key": "value"}') + self.assertIsNotNone(template) + if template is not None: + runner = TemplateRunner(None, template, ConfigMixIn([]), rule_collection) + failures = list(runner.run()) + + self.assertListEqual( + failures, + [ + Match( + linenumber=1, + columnnumber=2, + linenumberend=1, + columnnumberend=7, + filename=None, + rule=test_rule_child, + message="failure", + ) + ], + ) + + def test_child_rules_suppressed(self) -> None: + class TestRuleParent(CloudFormationLintRule): + """Def Rule""" + + id = "E1000" + shortdesc = "Test Rule" + description = "Test Rule Description" + source_url = "https://github.com/aws-cloudformation/cfn-lint/" + tags = ["resources"] + child_rules: Dict[str, Any] = {"E1001": None} + + def match(self, _): + if self.child_rules.get("E1001"): + return self.child_rules["E1001"].failure() + return [] + + class TestRuleChild(CloudFormationLintRule): + """Def Rule""" + + id = "E1001" + shortdesc = "Test Rule" + description = "Test Rule Description" + source_url = "https://github.com/aws-cloudformation/cfn-lint/" + tags = ["resources"] + + def failure(self): + return [RuleMatch(["key"], "failure", rule=self)] + + rule_collection = Rules() + test_rule_parent = TestRuleParent() + test_rule_child = TestRuleChild() + rule_collection.register(test_rule_parent) + rule_collection.register(test_rule_child) + + template, _ = decode_str('{"key": "value"}') + self.assertIsNotNone(template) + if template is not None: + runner = TemplateRunner( + None, + template, + ConfigMixIn(ignore_checks=["E1001"]), + rule_collection, + ) + failures = list(runner.run()) + + self.assertListEqual(failures, []) + + def test_child_rules_configured(self) -> None: + class TestRuleParent(CloudFormationLintRule): + """Def Rule""" + + id = "E1000" + shortdesc = "Test Rule" + description = "Test Rule Description" + source_url = "https://github.com/aws-cloudformation/cfn-lint/" + tags = ["resources"] + child_rules: Dict[str, Any] = {"E1001": None} + + def match(self, _): + return self.child_rules["E1001"].failure() + + class TestRuleChild(CloudFormationLintRule): + """Def Rule""" + + id = "E1001" + shortdesc = "Test Rule" + description = "Test Rule Description" + source_url = "https://github.com/aws-cloudformation/cfn-lint/" + tags = ["resources"] + + def __init__(self): + """Init""" + super(TestRuleChild, self).__init__() + self.config_definition = {"pass": {"default": True, "type": "boolean"}} + self.configure() + + def failure(self): + if self.config["pass"]: + return [RuleMatch(["key"], "failure", rule=self)] + return [] + + rule_collection = Rules() + test_rule_parent = TestRuleParent() + test_rule_child = TestRuleChild() + rule_collection.register(test_rule_parent) + rule_collection.register(test_rule_child) + + template, _ = decode_str('{"key": "value"}') + self.assertIsNotNone(template) + if template is not None: + runner = TemplateRunner( + None, + template, + ConfigMixIn(configure_rules={"E1001": {"pass": False}}), + rule_collection, + ) + failures = list(runner.run()) + + self.assertListEqual(failures, []) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/rule/test_rules.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/rule/test_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..48c74fd454b0024e9e7f1eb2b1780b93c10321b8 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/rule/test_rules.py @@ -0,0 +1,190 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase + +from cfnlint import ConfigMixIn, Template +from cfnlint.decode.mark import Mark +from cfnlint.decode.node import dict_node +from cfnlint.exceptions import DuplicateRuleError +from cfnlint.rules import CloudFormationLintRule, Match, RuleMatch, Rules +from cfnlint.rules.errors import RuleError + + +class Rule(CloudFormationLintRule): + """Def Rule""" + + id = "EXXXX" + shortdesc = "Test Rule" + description = "Test Rule" + source_url = "https://github.com/aws-cloudformation/cfn-lint/" + tags = ["resources"] + + def __init__(self): + """Init""" + super(Rule, self).__init__() + self.config_definition = { + "testBoolean": {"default": True, "type": "boolean"}, + "testString": {"default": "default", "type": "string"}, + "testInteger": {"default": 1, "type": "integer"}, + } + self.configure() + + def get_config(self): + """Get the Config""" + return self.config + + +class RuleFail(CloudFormationLintRule): + """Def Rule""" + + id = "EYYYY" + shortdesc = "Test Rule" + description = "Test Rule" + source_url = "https://github.com/aws-cloudformation/cfn-lint/" + tags = ["resources"] + + def match(self, cfn): + raise KeyError("Bad template") + + +class RuleChild(CloudFormationLintRule): + id = "ECCCC" + shortdesc = "Child Rule" + description = "Child Rule" + source_url = "https://github.com/aws-cloudformation/cfn-lint/" + tags = ["resources"] + + def validate(self, cfn): + return [RuleMatch([], "Child Rule", rule=self)] + + +class RuleParent(CloudFormationLintRule): + id = "EPPPP" + shortdesc = "Parent Rule" + description = "Parent Rule" + source_url = "https://github.com/aws-cloudformation/cfn-lint/" + tags = ["resources"] + + def __init__(self) -> None: + super().__init__() + self.child_rules = { + "ECCCC": RuleChild(), + } + + def match(self, cfn): + return [RuleMatch([], "Parent Rule")] + self.child_rules["ECCCC"].validate(cfn) + + +class TestRules(BaseTestCase): + """Test CloudFormation Rules""" + + def test_rule_failure(self): + rules = Rules() + rules.extend([RuleFail(), RuleError()]) + + cfn = Template("-", {}, regions=["us-east-1"]) + + matches = list(rules.run("-", cfn, ConfigMixIn([]))) + self.assertListEqual( + [ + Match( + linenumber=1, + linenumberend=1, + columnnumber=1, + columnnumberend=2, + filename="-", + rule=RuleError(), + message=( + "Unknown exception while processing rule " + "EYYYY: \"'Bad template'\"" + ), + ) + ], + matches, + ) + + def test_parent_child(self): + rules = Rules() + rules.extend([RuleParent(), RuleChild()]) + + cfn = Template( + "-", dict_node({}, Mark(0, 0), Mark(0, 0)), regions=["us-east-1"] + ) + + matches = list(rules.run("-", cfn, ConfigMixIn([]))) + self.assertListEqual( + [ + Match( + linenumber=1, + columnnumber=1, + linenumberend=1, + columnnumberend=1, + filename="-", + rule=RuleParent(), + message="Parent Rule", + ), + Match( + linenumber=1, + columnnumber=1, + linenumberend=1, + columnnumberend=1, + filename="-", + rule=RuleChild(), + message="Child Rule", + ), + ], + matches, + matches, + ) + + def test_parent_child_ignore(self): + rules = Rules() + rules.extend([RuleParent(), RuleChild()]) + + cfn = Template( + "-", dict_node({}, Mark(0, 0), Mark(0, 0)), regions=["us-east-1"] + ) + + matches = list( + rules.run( + "-", cfn, ConfigMixIn(ignore_checks=["E"], mandatory_checks=["ECCCC"]) + ) + ) + self.assertListEqual( + [ + Match( + linenumber=1, + columnnumber=1, + linenumberend=1, + columnnumberend=1, + filename="-", + rule=RuleChild(), + message="Child Rule", + ) + ], + matches, + matches, + ) + + def test_rule_deletion(self): + rules = Rules() + rules.extend([Rule()]) + + with self.assertRaises(RuntimeError): + del rules["EXXXX"] + + def test_failure_on_duplicate_rule(self): + rules = Rules() + + with self.assertRaises(DuplicateRuleError): + rules.extend([Rule(), Rule()]) + + def test_custom_rules(self): + rules = Rules.create_from_custom_rules_file( + "test/fixtures/custom_rules/good/custom_rule_perfect.txt" + ) + + self.assertEqual(len(rules), 15) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_cli.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..318067520bac3406c127635259f7578c1083e091 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_cli.py @@ -0,0 +1,99 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import logging +from test.testlib.testcase import BaseTestCase +from unittest.mock import patch + +from cfnlint import ConfigMixIn +from cfnlint.runner import Runner + +LOGGER = logging.getLogger("cfnlint") + + +class TestCli(BaseTestCase): + """Test CLI with config""" + + def tearDown(self): + """Setup""" + for handler in LOGGER.handlers: + LOGGER.removeHandler(handler) + + @patch("cfnlint.maintenance.update_documentation") + def test_update_documentation(self, mock_maintenance): + config = ConfigMixIn(["--update-documentation"]) + + runner = Runner(config) + + with self.assertRaises(SystemExit) as e: + runner.cli() + + self.assertEqual(e.exception.code, 0) + mock_maintenance.assert_called_once() + + @patch("cfnlint.maintenance.update_resource_specs") + def test_update_specs(self, mock_maintenance): + config = ConfigMixIn(["--update-specs"]) + + runner = Runner(config) + + with self.assertRaises(SystemExit) as e: + runner.cli() + + self.assertEqual(e.exception.code, 0) + mock_maintenance.assert_called_once() + + @patch("cfnlint.maintenance.update_iam_policies") + def test_update_iam_policies(self, mock_maintenance): + config = ConfigMixIn(["--update-iam-policies"]) + + runner = Runner(config) + + with self.assertRaises(SystemExit) as e: + runner.cli() + + self.assertEqual(e.exception.code, 0) + mock_maintenance.assert_called_once() + + def test_list_rules(self): + config = ConfigMixIn(["--list-rules"]) + + runner = Runner(config) + + with self.assertRaises(SystemExit) as e: + runner.cli() + + self.assertEqual(e.exception.code, 0) + + @patch("argparse.ArgumentParser.print_help") + @patch("sys.stdin.isatty") + def test_print_help(self, mock_isatty, mock_print_help): + config = ConfigMixIn([]) + + runner = Runner(config) + mock_isatty.return_value = True + with self.assertRaises(SystemExit) as e: + runner.cli() + + self.assertEqual(e.exception.code, 1) + mock_print_help.assert_called_once() + mock_isatty.assert_called_once() + + def test_bad_regions(self): + config = ConfigMixIn( + [ + "--regions", + "us-north-5", + "--template", + "test/fixtures/templates/good/generic.yaml", + ] + ) + + runner = Runner(config) + + with self.assertRaises(SystemExit) as e: + runner.cli() + + self.assertEqual(e.exception.code, 32) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_exit_code.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_exit_code.py new file mode 100644 index 0000000000000000000000000000000000000000..baa4fdf029662b0cb5b1127694dc301ccc40645b --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_exit_code.py @@ -0,0 +1,74 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase + +from cfnlint import ConfigMixIn +from cfnlint.rules import CloudFormationLintRule, Match +from cfnlint.runner import Runner + + +class ErrorRule(CloudFormationLintRule): + id = "E0000" + description = "Error" + + +class WarningRule(CloudFormationLintRule): + id = "W0000" + description = "Warning" + + +class InformationRule(CloudFormationLintRule): + id = "I0000" + description = "Informational" + + +error_match = Match("", ErrorRule(), "", 0, 0, 0, 0) +warning_match = Match("", WarningRule(), "", 0, 0, 0, 0) +informational_match = Match("", InformationRule(), "", 0, 0, 0, 0) + + +class TestExitCodes(BaseTestCase): + """Test Exit Codes""" + + def test_exit_code_zero(self): + params = [ + [[], "informational", 0], + [[error_match], "informational", 2], + [[error_match], "warning", 2], + [[error_match], "error", 2], + [[error_match], "none", 0], + [[error_match, warning_match], "informational", 6], + [[error_match, warning_match], "warning", 6], + [[error_match, warning_match], "error", 2], + [[error_match, warning_match], "none", 0], + [[warning_match, informational_match], "informational", 12], + [[warning_match, informational_match], "warning", 4], + [[warning_match, informational_match], "error", 0], + [[warning_match, informational_match], "none", 0], + [[error_match, informational_match], "informational", 10], + [[error_match, informational_match], "warning", 2], + [[error_match, informational_match], "error", 2], + [[error_match, informational_match], "none", 0], + [[error_match, warning_match, informational_match], "informational", 14], + [[error_match, warning_match, informational_match], "warning", 6], + [[error_match, warning_match, informational_match], "error", 2], + [[error_match, warning_match, informational_match], "none", 0], + ] + + for matches, level, exit_code in params: + with self.subTest(): + runner = Runner(ConfigMixIn(non_zero_exit_code=level)) + match_names = [x.rule.description for x in matches] + with self.assertRaises(SystemExit) as e: + runner._exit(matches) + self.assertEqual( + e.exception.code, + exit_code, + ( + f"{match_names} matches with {level} " + f"level should yield {exit_code}" + ), + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_get_formatter.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_get_formatter.py new file mode 100644 index 0000000000000000000000000000000000000000..603ae637f0c6fc0e009511f3a4b4854369ba033f --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_get_formatter.py @@ -0,0 +1,56 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase + +import cfnlint.formatters +from cfnlint import ConfigMixIn +from cfnlint.runner import get_formatter + + +class TestGetFormatter(BaseTestCase): + """Test get formatter with config""" + + def test_basic(self): + config = ConfigMixIn([]) + formatter = get_formatter(config) + + self.assertIsInstance(formatter, cfnlint.formatters.Formatter) + + def test_json(self): + config = ConfigMixIn(["--format", "json"]) + formatter = get_formatter(config) + + self.assertIsInstance(formatter, cfnlint.formatters.JsonFormatter) + + def test_quiet(self): + config = ConfigMixIn(["--format", "quiet"]) + formatter = get_formatter(config) + + self.assertIsInstance(formatter, cfnlint.formatters.QuietFormatter) + + def test_parseable(self): + config = ConfigMixIn(["--format", "parseable"]) + formatter = get_formatter(config) + + self.assertIsInstance(formatter, cfnlint.formatters.ParseableFormatter) + + def test_junit(self): + config = ConfigMixIn(["--format", "junit"]) + formatter = get_formatter(config) + + self.assertIsInstance(formatter, cfnlint.formatters.JUnitFormatter) + + def test_pretty(self): + config = ConfigMixIn(["--format", "pretty"]) + formatter = get_formatter(config) + + self.assertIsInstance(formatter, cfnlint.formatters.PrettyFormatter) + + def test_sarif(self): + config = ConfigMixIn(["--format", "sarif"]) + formatter = get_formatter(config) + + self.assertIsInstance(formatter, cfnlint.formatters.SARIFFormatter) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_rule_configuration.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_rule_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..444ad341e1425856b4e72021735d5891228425ed --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_rule_configuration.py @@ -0,0 +1,50 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import os +from test.testlib.testcase import BaseTestCase + +from cfnlint.config import ConfigMixIn +from cfnlint.runner import Runner, UnexpectedRuleException + + +class TestGetRules(BaseTestCase): + """Test Run Checks""" + + def test_invalid_rule(self): + """test invalid rules""" + err = None + config = ConfigMixIn( + append_rules=["invalid"], + ) + + try: + Runner(config) + except UnexpectedRuleException as e: + err = e + self.assertIsInstance(err, UnexpectedRuleException) + + def test_append_module(self): + """test appending rules from a module""" + config = ConfigMixIn( + append_rules=["test.fixtures.rules.custom1"], + ) + runner = Runner(config) + self.assertIn("E9001", runner.rules) + # Make sure the default rules are there too. + self.assertIn("E1001", runner.rules) + + def test_append_directory(self): + """test appending rules from a directory""" + import test.fixtures.rules + + path = os.path.dirname(test.fixtures.rules.__file__) + config = ConfigMixIn( + append_rules=[path], + ) + runner = Runner(config) + self.assertIn("E9001", runner.rules) + # Make sure the default rules are there too. + self.assertIn("E1001", runner.rules) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_run.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_run.py new file mode 100644 index 0000000000000000000000000000000000000000..06d7734e1bddfa95dc9b5a0eac5f9ede467dc04b --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_run.py @@ -0,0 +1,55 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import pytest + +from cfnlint.config import ConfigMixIn +from cfnlint.runner import Runner + + +@pytest.mark.parametrize( + "name,config,expected_count", + [ + ( + "Test decode errors with multiple files", + ConfigMixIn( + cli_args=[ + "--template", + "test/fixtures/templates/bad/duplicate.yaml", + "test/fixtures/templates/bad/duplicate.json", + ] + ), + 6, + ), + ( + "Test decode errors with E0000 being ignored", + ConfigMixIn( + cli_args=[ + "--template", + "test/fixtures/templates/bad/core/parse_invalid_map.yaml", + "--ignore-bad-template", + ] + ), + 0, + ), + ( + "Test decode return E0000 errors", + ConfigMixIn( + cli_args=[ + "--template", + "test/fixtures/templates/bad/core/parse_invalid_map.yaml", + ] + ), + 1, + ), + ], +) +def test_run(name, config, expected_count): + + runner = Runner(config) + + errs = list(runner.run()) + + assert len(errs) == expected_count, f"{name}: {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_template_runner.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_template_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..d3d599239e28c74497b377540d84f30b01a9a77b --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/runner/test_template_runner.py @@ -0,0 +1,112 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase + +import cfnlint.decode.cfn_json # pylint: disable=E0401 +import cfnlint.decode.cfn_yaml # pylint: disable=E0401 +from cfnlint import ConfigMixIn +from cfnlint.config import _DEFAULT_RULESDIR +from cfnlint.rules import Rules +from cfnlint.runner import TemplateRunner + + +class TestRunner(BaseTestCase): + """Test Duplicates Parsing""" + + def setUp(self): + """SetUp template object""" + self.rules = Rules.create_from_directory(_DEFAULT_RULESDIR) + (self.template, _) = cfnlint.decode.decode_str( + """ + AWSTemplateFormatVersion: "2010-09-09" + Description: > + Template with all error levels: Warning, Error and Informational + # Adding in an issue outside of the Resources for validating + Conditions: + IsUsEast1: !Equals ["a", "b", "c"] + Resources: + myTable: + Metadata: + cfn-lint: + config: + ignore_checks: + - I3011 + - W1020 + - E8003 # condition error # + Type: "AWS::DynamoDB::Table" + Properties: + TableName: !Sub "TableName" + AttributeDefinitions: + - AttributeName: "Id" + AttributeType: "S" # Valid AllowedValue + KeySchema: + - AttributeName: "Id" + KeyType: "HASH" + ProvisionedThroughput: + ReadCapacityUnits: 5 + WriteCapacityUnits: "5" + myTable2: + # With no ignore_checks so we + # should still get issues from this + Type: "AWS::DynamoDB::Table" + Properties: + TableName: !Sub "TableName1" + AttributeDefinitions: + - AttributeName: "Id" + AttributeType: "S" # Valid AllowedValue + KeySchema: + - AttributeName: "Id" + KeyType: "HASH" + ProvisionedThroughput: + ReadCapacityUnits: !If [IsUsEast1, 5, 5] + WriteCapacityUnits: "5" + """ + ) + + def test_runner(self): + """Success test""" + runner = TemplateRunner( + filename=None, + template=self.template, + config=ConfigMixIn( + regions=["us-east-1"], + include_checks=["I"], + include_experimental=True, + ), + rules=self.rules, + ) + failures = list(runner.run()) + self.assertEqual(len(failures), 4, "Got failures {}".format(failures)) + + def test_runner_mandatory_rules(self): + """Success test""" + runner = TemplateRunner( + filename=None, + template=self.template, + config=ConfigMixIn( + mandatory_checks=["W1020"], + regions=["us-east-1"], + include_checks=["I"], + include_experimental=True, + ), + rules=self.rules, + ) + failures = list(runner.run()) + self.assertEqual(len(failures), 5, "Got failures {}".format(failures)) + + runner = TemplateRunner( + filename=None, + template=self.template, + config=ConfigMixIn( + mandatory_checks=["W9000"], + regions=["us-east-1"], + include_checks=["I"], + include_experimental=True, + ), + rules=self.rules, + ) + failures = list(runner.run()) + self.assertEqual(len(failures), 4, "Got failures {}".format(failures)) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/schema/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/schema/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/schema/resolver/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/schema/resolver/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/schema/resolver/test_resolve_from_url.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/schema/resolver/test_resolve_from_url.py new file mode 100644 index 0000000000000000000000000000000000000000..ccc4412b7c3b8e2c2167fcf762c0a95b95f5ea34 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/schema/resolver/test_resolve_from_url.py @@ -0,0 +1,102 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import logging + +import pytest + +from cfnlint.schema._schema import Schema +from cfnlint.schema.resolver._exceptions import RefResolutionError + +LOGGER = logging.getLogger("cfnlint.schema.manager") +LOGGER.disabled = True + + +@pytest.fixture +def resource_schema(): + return { + "additionalProperties": False, + "definitions": { + "ListItem": {"description": "A a list Id.", "type": "string"}, + "ResourceArn": { + "description": "A resource ARN.", + "maxLength": 256, + "minLength": 1, + "pattern": "^arn:aws.*$", + "type": "string", + }, + "AList": { + "items": [ + {"type": "string"}, + {"type": "boolean"}, + ], + "type": "array", + }, + }, + "properties": { + "Name": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[a-zA-Z0-9-]+$", + "type": "string", + }, + "List": { + "insertionOrder": False, + "items": {"$ref": "#/definitions/ListItem"}, + "type": "array", + }, + "Arn": {"$ref": "#/definitions/ResourceArn"}, + "Id": { + "maxLength": 36, + "minLength": 36, + "pattern": "^([0-9a-f]{8})-([0-9a-f]{4}-){3}([0-9a-f]{12})$", + "type": "string", + }, + }, + "readOnlyProperties": [ + "/properties/Arn", + "/properties/Id", + "/properties/List", + ], + "typeName": "AWS::NetworkFirewall::Firewall", + } + + +def test_schema(resource_schema): + + schema = Schema(schema=resource_schema) + + assert schema.resolver.resolve_from_url("#/") == resource_schema + + assert schema.resolver.resolve_from_url("#/properties/Name") == { + "maxLength": 128, + "minLength": 1, + "pattern": "^[a-zA-Z0-9-]+$", + "type": "string", + } + + assert schema.resolver.resolve_from_url("#/definitions/ListItem") == { + "description": "A a list Id.", + "type": "string", + } + assert schema.resolver.resolve_from_url("#/definitions/AList/items/0") == { + "type": "string" + } + assert schema.resolver.resolve_from_url("#/definitions/AList/items/1") == { + "type": "boolean" + } + + with pytest.raises(RefResolutionError): + schema.resolver.resolve_from_url("#/definitions/AList/items/2") + + with pytest.raises(RefResolutionError): + schema.resolver.resolve_from_url("#/properties/bar/key") + + with pytest.raises(RefResolutionError): + schema.resolver.resolve_from_url("test#/properties/bar/key") + + with pytest.raises(RefResolutionError): + schema.resolver.pop_scope() + schema.resolver.pop_scope() diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/schema/test_manager.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/schema/test_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..74b9ce0e864292a77b71c3c4c8c518ffd67b48af --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/schema/test_manager.py @@ -0,0 +1,285 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import json +import logging +from test.testlib.testcase import BaseTestCase +from unittest.mock import MagicMock, call, mock_open, patch + +from cfnlint.schema.manager import ProviderSchemaManager, ResourceNotFoundError +from cfnlint.schema.patch import SchemaPatch + +LOGGER = logging.getLogger("cfnlint.schema.manager") +LOGGER.disabled = True + + +class TestUpdateResourceSchemas(BaseTestCase): + """Used for Testing Resource Schemas""" + + def setUp(self) -> None: + super().setUp() + + self.schema_zip = "test/fixtures/registry/schema.zip" + self.manager = ProviderSchemaManager() + self.schemas = dict.fromkeys(["aws-lambda-codesigningconfig"]) + for resource in self.schemas: + with open(f"test/fixtures/registry/schemas/{resource}.json") as fh: + self.schemas[resource] = fh.read() + + self.schema_patch = [{"op": "add", "path": "/cfnSchema", "value": ["test"]}] + + @patch("cfnlint.schema.manager.url_has_newer_version") + @patch("cfnlint.schema.manager.json.dump") + @patch("cfnlint.schema.manager.REGIONS", ["us-east-1"]) + @patch("cfnlint.schema.manager.get_url_retrieve") + @patch("cfnlint.schema.manager.zipfile.ZipFile") + @patch("cfnlint.schema.manager.os.listdir") + @patch("cfnlint.schema.manager.os.path.isfile") + @patch("cfnlint.schema.manager.os.remove") + @patch("cfnlint.schema.manager.os.walk") + @patch("cfnlint.schema.manager.filecmp.cmp") + @patch("cfnlint.schema.manager.load_resource") + @patch("cfnlint.schema.manager.shutil.rmtree") + def test_update_resource_spec( + self, + mock_shutil_rmtree, + mock_load_resource, + mock_filecmp_cmp, + mock_os_walk, + mock_os_remove, + mock_os_path_isfile, + mock_os_listdir, + mock_zipfile, + mock_get_url_retrieve, + mock_json_dump, + mock_url_newer_version, + ): + schema = self.schemas["aws-lambda-codesigningconfig"] + schema_json = json.loads(schema) + + """Success update resource spec""" + mock_url_newer_version.return_value = True + mock_get_url_retrieve.return_value = self.schema_zip + mock_zipfile.return_value = MagicMock() + mock_os_listdir.return_value = [ + "aws_lambda_codesigningconfig.json", + "__init__.py", + ] + mock_os_path_isfile.side_effect = [True, True, True, True] + mock_load_resource.return_value = self.schema_patch + mock_os_walk.return_value = iter( + [("all", [], ["aws_lambda_codesigningconfig.json"])] + ) + builtin_module_name = "builtins" + + with patch( + "{}.open".format(builtin_module_name), mock_open(read_data=schema) + ) as mock_builtin_open: + self.manager._update_provider_schema("us-east-1", False) + schema_patched = {**schema_json, **{"cfnSchema": ["test"]}} + mock_json_dump.assert_called_with( + schema_patched, + mock_builtin_open.return_value.__enter__.return_value, + indent=1, + separators=(",", ": "), + sort_keys=True, + ) + mock_os_listdir.assert_has_calls( + [ + call(f"{self.manager._root.path_relative}/us_east_1/"), + ] + ) + mock_zipfile.assert_has_calls([call(self.schema_zip, "r")]) + mock_filecmp_cmp.assert_not_called() + mock_os_remove.assert_not_called() + + @patch("cfnlint.schema.manager.url_has_newer_version") + @patch("cfnlint.schema.manager.get_url_retrieve") + @patch("cfnlint.schema.manager.json.dump") + @patch("cfnlint.schema.manager.REGIONS", ["us-east-1"]) + @patch("cfnlint.schema.manager.load_resource") + @patch("cfnlint.schema.manager.zipfile.ZipFile") + @patch("cfnlint.schema.manager.os.listdir") + @patch("cfnlint.schema.manager.os.path.isfile") + @patch("cfnlint.schema.manager.os.remove") + @patch("cfnlint.schema.manager.os.walk") + @patch("cfnlint.schema.manager.filecmp.cmp") + @patch("cfnlint.schema.manager.shutil.rmtree") + def test_update_resource_spec_cache( + self, + mock_shutil_rmtree, + mock_filecmp_cmp, + mock_os_walk, + mock_os_remove, + mock_os_path_isfile, + mock_os_listdir, + mock_zipfile, + mock_load_resource, + mock_json_dump, + mock_get_url_retrieve, + mock_url_newer_version, + ): + """Success update resource spec with cache""" + schema = self.schemas["aws-lambda-codesigningconfig"] + schema_json = json.loads(schema) + + mock_url_newer_version.return_value = True + mock_get_url_retrieve.return_value = self.schema_zip + mock_zipfile.return_value = MagicMock() + mock_os_listdir.return_value = [ + "aws-lambda-codesigningconfig.json", + "__init__.py", + ] + mock_os_path_isfile.side_effect = [True, True, True, True] + mock_filecmp_cmp.side_effect = [True] + mock_load_resource.return_value = self.schema_patch + mock_os_walk.return_value = iter( + [("all", [], ["aws_lambda_codesigningconfig.json"])] + ) + builtin_module_name = "builtins" + + with patch( + "{}.open".format(builtin_module_name), mock_open(read_data=schema) + ) as mock_builtin_open: + self.manager._update_provider_schema("us-west-2", False) + schema_patched = {**schema_json, **{"cfnSchema": ["test"]}} + mock_json_dump.assert_called_with( + schema_patched, + mock_builtin_open.return_value.__enter__.return_value, + indent=1, + separators=(",", ": "), + sort_keys=True, + ) + mock_os_listdir.assert_has_calls( + [ + call(f"{self.manager._root.path_relative}/us_west_2/"), + call(f"{self.manager._root.path_relative}/us_west_2/"), + ] + ) + mock_zipfile.assert_has_calls([call(self.schema_zip, "r")]) + mock_filecmp_cmp.assert_called_once() + mock_os_remove.assert_called_once() + + @patch("cfnlint.schema.manager.url_has_newer_version") + @patch("cfnlint.schema.manager.get_url_retrieve") + @patch("cfnlint.schema.manager.json.dump") + @patch("cfnlint.schema.manager.ProviderSchemaManager._patch_provider_schema") + @patch("cfnlint.schema.manager.REGIONS", {"us-east-1": []}) + def test_do_not_update_resource_spec( + self, + mock_provider_schema, + mock_json_dump, + mock_get_url_retrieve, + mock_url_newer_version, + ): + """Success update resource spec""" + + mock_url_newer_version.return_value = False + + result = self.manager._update_provider_schema("us-east-1", False) + self.assertIsNone(result) + mock_get_url_retrieve.assert_not_called() + mock_provider_schema.assert_not_called() + mock_json_dump.assert_not_called() + + @patch("cfnlint.schema.manager.multiprocessing.Pool") + @patch("cfnlint.schema.manager.ProviderSchemaManager._update_provider_schema") + @patch("cfnlint.schema.manager.REGIONS", {"us-east-1": []}) + def test_update_resource_specs_python(self, mock_update_resource_spec, mock_pool): + fake_pool = MagicMock() + mock_pool.return_value.__enter__.return_value = fake_pool + + self.manager.update(True) + + fake_pool.starmap.assert_called_once() + + +class TestManagerPatch(BaseTestCase): + """Used for Testing Resource Schemas""" + + def setUp(self) -> None: + super().setUp() + + self.manager = ProviderSchemaManager() + self.schemas = dict.fromkeys(["aws-lambda-codesigningconfig"]) + for resource in self.schemas: + with open(f"test/fixtures/registry/schemas/{resource}.json") as fh: + self.schemas[resource] = fh.read() + + def test_patch_file_not_found_error(self): + with patch("builtins.open", mock_open()) as mock_builtin_open: + err = FileNotFoundError() + err.errno = 2 + mock_builtin_open.side_effect = [err] + with self.assertRaises(SystemExit) as mock_exit: + self.manager.patch("bad", regions=["us-east-1"]) + self.assertEqual(mock_exit.type, SystemExit) + self.assertEqual(mock_exit.value.code == 1) + + def test_patch_file_is_dir(self): + with patch("builtins.open", mock_open()) as mock_builtin_open: + err = IOError() + err.errno = 21 + mock_builtin_open.side_effect = [err] + with self.assertRaises(SystemExit) as mock_exit: + self.manager.patch("bad", regions=["us-east-1"]) + self.assertEqual(mock_exit.type, SystemExit) + self.assertEqual(mock_exit.value.code == 1) + + def test_patch_permission_error(self): + with patch("builtins.open", mock_open()) as mock_builtin_open: + err = PermissionError() + err.errno = 13 + mock_builtin_open.side_effect = [err] + with self.assertRaises(SystemExit) as mock_exit: + self.manager.patch("bad", regions=["us-east-1"]) + self.assertEqual(mock_exit.type, SystemExit) + self.assertEqual(mock_exit.value.code == 1) + + def test_patch_value_error(self): + with patch("builtins.open", mock_open()) as mock_builtin_open: + err = ValueError() + mock_builtin_open.side_effect = [err] + with self.assertRaises(SystemExit) as mock_exit: + self.manager.patch("bad", regions=["us-east-1"]) + self.assertEqual(mock_exit.type, SystemExit) + self.assertEqual(mock_exit.value.code == 1) + + +class TestManagerGetResourceSchema(BaseTestCase): + """Test get resource schema""" + + def setUp(self) -> None: + super().setUp() + + self.manager = ProviderSchemaManager() + + def test_getting_cached_schema(self): + rt = "AWS::EC2::VPC" + + self.manager.get_resource_schema("us-east-1", rt) + schema = self.manager.get_resource_schema("us-east-2", rt) + + self.assertTrue(schema.is_cached) + + def test_removed_types(self): + rt = "AWS::EC2::VPC" + region = "us-east-1" + self.manager._patch(SchemaPatch([], [rt], {}), region) + + with self.assertRaises(ResourceNotFoundError): + self.manager.get_resource_schema(region, rt) + + def test_type_normalization(self): + + rt = "MyCompany::MODULE" + schema = self.manager.get_resource_schema("us-east-1", rt) + + assert schema.schema.get("typeName") == "Module" + + self.manager.get_resource_schema.cache_clear() + self.manager._registry_schemas[rt] = True + schema = self.manager.get_resource_schema("us-east-1", rt) + assert schema is True diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/schema/test_schema.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/schema/test_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..10a10c8baab32b7f9c230c1be36907cf190d2972 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/schema/test_schema.py @@ -0,0 +1,314 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import logging + +import pytest + +from cfnlint.schema._schema import Schema + +LOGGER = logging.getLogger("cfnlint.schema.manager") +LOGGER.disabled = True + + +@pytest.fixture +def resource_schema(): + return { + "additionalProperties": False, + "definitions": { + "ListItem": {"description": "A a list Id.", "type": "string"}, + "ResourceArn": { + "description": "A resource ARN.", + "maxLength": 256, + "minLength": 1, + "pattern": "^arn:aws.*$", + "type": "string", + }, + }, + "properties": { + "Name": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[a-zA-Z0-9-]+$", + "type": "string", + }, + "List": { + "insertionOrder": False, + "items": {"$ref": "#/definitions/ListItem"}, + "type": "array", + }, + "Arn": {"$ref": "#/definitions/ResourceArn"}, + "Id": { + "maxLength": 36, + "minLength": 36, + "pattern": "^([0-9a-f]{8})-([0-9a-f]{4}-){3}([0-9a-f]{12})$", + "type": "string", + }, + }, + "readOnlyProperties": [ + "/properties/Arn", + "/properties/Id", + "/properties/List", + ], + "typeName": "AWS::NetworkFirewall::Firewall", + } + + +def test_schema(resource_schema): + + schema = Schema(schema=resource_schema) + assert list(schema.get_atts.keys()) == ["Arn", "Id", "List"] + assert schema.get_atts["Arn"] == "/properties/Arn" + assert schema.get_atts["Id"] == "/properties/Id" + assert schema.get_atts["List"] == "/properties/List" + + +@pytest.fixture +def resource_vpc_schema(): + return { + "additionalProperties": False, + "conditionalCreateOnlyProperties": ["/properties/InstanceTenancy"], + "createOnlyProperties": [ + "/properties/CidrBlock", + "/properties/Ipv4IpamPoolId", + "/properties/Ipv4NetmaskLength", + ], + "definitions": { + "Tag": { + "additionalProperties": False, + "properties": {"Key": {"type": "string"}, "Value": {"type": "string"}}, + "required": ["Value", "Key"], + "type": "object", + } + }, + "dependentRequired": {"Ipv4IpamPoolId": ["Ipv4NetmaskLength"]}, + "primaryIdentifier": ["/properties/VpcId"], + "properties": { + "CidrBlock": {"type": "string"}, + "CidrBlockAssociations": { + "insertionOrder": False, + "items": {"type": "string"}, + "type": "array", + "uniqueItems": False, + }, + "DefaultNetworkAcl": {"insertionOrder": False, "type": "string"}, + "DefaultSecurityGroup": { + "format": "AWS::EC2::SecurityGroup.GroupId", + "insertionOrder": False, + "type": "string", + }, + "EnableDnsHostnames": {"type": "boolean"}, + "EnableDnsSupport": {"type": "boolean"}, + "InstanceTenancy": {"type": "string"}, + "Ipv4IpamPoolId": {"type": "string"}, + "Ipv4NetmaskLength": {"type": "integer"}, + "Ipv6CidrBlocks": { + "insertionOrder": False, + "items": {"type": "string"}, + "type": "array", + "uniqueItems": False, + }, + "Tags": { + "insertionOrder": False, + "items": {"$ref": "#/definitions/Tag"}, + "type": "array", + "uniqueItems": False, + }, + "VpcId": {"format": "AWS::EC2::VPC.Id", "type": "string"}, + }, + "readOnlyProperties": [ + "/properties/CidrBlockAssociations", + "/properties/DefaultNetworkAcl", + "/properties/DefaultSecurityGroup", + "/properties/Ipv6CidrBlocks", + "/properties/VpcId", + ], + "requiredXor": ["CidrBlock", "Ipv4IpamPoolId"], + "tagging": { + "cloudFormationSystemTags": True, + "tagOnCreate": True, + "tagProperty": "/properties/Tags", + "tagUpdatable": True, + "taggable": True, + }, + "typeName": "AWS::EC2::VPC", + "writeOnlyProperties": [ + "/properties/Ipv4IpamPoolId", + "/properties/Ipv4NetmaskLength", + ], + } + + +def test_vpc_schema(resource_vpc_schema): + schema = Schema(schema=resource_vpc_schema) + assert list(schema.get_atts.keys()) == [ + "CidrBlock", + "CidrBlockAssociations", + "DefaultNetworkAcl", + "DefaultSecurityGroup", + "EnableDnsHostnames", + "EnableDnsSupport", + "InstanceTenancy", + "Ipv4IpamPoolId", + "Ipv4NetmaskLength", + "Ipv6CidrBlocks", + "Tags", + "VpcId", + ] + assert schema.get_atts["VpcId"] == "/properties/VpcId" + assert schema.get_atts["CidrBlock"] == "/properties/CidrBlock" + assert schema.get_atts["Ipv6CidrBlocks"] == "/properties/Ipv6CidrBlocks" + + +@pytest.fixture +def resource_servicecatalog_schema(): + return { + "additionalProperties": False, + "createOnlyProperties": [ + "/properties/NotificationArns", + "/properties/ProvisionedProductName", + ], + "definitions": { + "OutputType": {"type": "string"}, + "ProvisioningParameter": { + "additionalProperties": False, + "properties": { + "Key": {"maxLength": 1000, "minLength": 1, "type": "string"}, + "Value": {"maxLength": 4096, "type": "string"}, + }, + "required": ["Key", "Value"], + "type": "object", + }, + "ProvisioningPreferences": { + "additionalProperties": False, + "properties": { + "StackSetAccounts": { + "items": {"pattern": "^[0-9]{12}$", "type": "string"}, + "type": "array", + "uniqueItems": True, + }, + "StackSetFailureToleranceCount": {"minimum": 0, "type": "integer"}, + "StackSetFailureTolerancePercentage": { + "maximum": 100, + "minimum": 0, + "type": "integer", + }, + "StackSetMaxConcurrencyCount": {"minimum": 1, "type": "integer"}, + "StackSetMaxConcurrencyPercentage": { + "maximum": 100, + "minimum": 1, + "type": "integer", + }, + "StackSetOperationType": { + "enum": ["CREATE", "UPDATE", "DELETE"], + "type": "string", + }, + "StackSetRegions": { + "items": { + "pattern": "^[a-z]{2}-([a-z]+-)+[1-9]", + "type": "string", + }, + "type": "array", + "uniqueItems": True, + }, + }, + "type": "object", + }, + "Tag": { + "additionalProperties": False, + "properties": { + "Key": { + "maxLength": 128, + "minLength": 1, + "pattern": "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$", + "type": "string", + }, + "Value": { + "maxLength": 256, + "minLength": 1, + "pattern": "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$", + "type": "string", + }, + }, + "required": ["Key", "Value"], + "type": "object", + }, + }, + "documentationUrl": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-cloudformationprovisionedproduct.html", + "handlers": { + "create": {"permissions": ["*"], "timeoutInMinutes": 720}, + "delete": {"permissions": ["*"]}, + "read": {"permissions": ["*"]}, + "update": {"permissions": ["*"], "timeoutInMinutes": 720}, + }, + "primaryIdentifier": ["/properties/ProvisionedProductId"], + "properties": { + "AcceptLanguage": {"enum": ["en", "jp", "zh"], "type": "string"}, + "CloudformationStackArn": { + "maxLength": 256, + "minLength": 1, + "type": "string", + }, + "NotificationArns": { + "items": {"type": "string"}, + "maxItems": 5, + "type": "array", + "uniqueItems": True, + }, + "Outputs": { + "additionalProperties": False, + "maxProperties": 100, + "patternProperties": { + "^[A-Za-z0-9]{1,64}$": {"$ref": "#/definitions/OutputType"} + }, + "type": "object", + }, + "PathId": {"maxLength": 100, "minLength": 1, "type": "string"}, + "PathName": {"maxLength": 100, "minLength": 1, "type": "string"}, + "ProductId": {"maxLength": 100, "minLength": 1, "type": "string"}, + "ProductName": {"maxLength": 128, "minLength": 1, "type": "string"}, + "ProvisionedProductId": {"maxLength": 50, "minLength": 1, "type": "string"}, + "ProvisionedProductName": { + "maxLength": 128, + "minLength": 1, + "type": "string", + }, + "ProvisioningArtifactId": { + "maxLength": 100, + "minLength": 1, + "type": "string", + }, + "ProvisioningArtifactName": {"type": "string"}, + "ProvisioningParameters": { + "items": {"$ref": "#/definitions/ProvisioningParameter"}, + "type": "array", + }, + "ProvisioningPreferences": { + "$ref": "#/definitions/ProvisioningPreferences" + }, + "RecordId": {"maxLength": 50, "minLength": 1, "type": "string"}, + "Tags": {"items": {"$ref": "#/definitions/Tag"}, "type": "array"}, + }, + "readOnlyProperties": [ + "/properties/RecordId", + "/properties/CloudformationStackArn", + "/properties/Outputs", + "/properties/ProvisionedProductId", + ], + "sourceUrl": "https://github.com/aws-cloudformation/aws-cloudformation-rpdk.git", + "typeName": "AWS::ServiceCatalog::CloudFormationProvisionedProduct", + } + + +def test_servicecatalog_cloudformation_schema(resource_servicecatalog_schema): + + schema = Schema(schema=resource_servicecatalog_schema) + assert list(schema.get_atts.keys()) == [ + "RecordId", + "CloudformationStackArn", + "Outputs\\..*", + "ProvisionedProductId", + ] + assert schema.get_atts["Outputs.Example"] == "/properties/CfnLintStringType" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/test_api.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/test_api.py new file mode 100644 index 0000000000000000000000000000000000000000..bdefd385ba7ea212483d502ef583080fb490088f --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/test_api.py @@ -0,0 +1,169 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from __future__ import annotations + +from unittest import TestCase + +from cfnlint import lint, lint_all +from cfnlint.config import ManualArgs +from cfnlint.core import get_rules +from cfnlint.helpers import REGIONS + + +class TestLint(TestCase): + def helper_lint_string_from_file( + self, filename=None, config: ManualArgs | None = None + ): + with open(filename, "r") as f: + return lint(f.read(), config=config) + + def helper_lint_string_from_file_all(self, filename): + with open(filename, "r") as f: + return lint_all(f.read()) + + def test_noecho_yaml_template(self): + filename = "test/fixtures/templates/bad/noecho.yaml" + matches = self.helper_lint_string_from_file( + filename=filename, + config=ManualArgs(regions=["us-east-1", "us-west-2", "eu-west-1"]), + ) + self.assertEqual( + ["W2010", "W2010"], + [match.rule.id for match in matches], + f"Got matches: {matches!r}", + ) + + def test_noecho_yaml_template_warnings_ignored(self): + filename = "test/fixtures/templates/bad/noecho.yaml" + matches = self.helper_lint_string_from_file( + filename=filename, + config=ManualArgs( + ignore_checks=["W", "I"], + ), + ) + self.assertListEqual([], matches, f"Got matches: {matches!r}") + + def test_duplicate_json_template(self): + filename = "test/fixtures/templates/bad/duplicate.json" + matches = self.helper_lint_string_from_file( + filename=filename, + config=ManualArgs( + regions=["us-east-1", "us-west-2", "eu-west-1"], + ), + ) + self.assertEqual( + ["E0000", "E0000", "E0000"], + [match.rule.id for match in matches], + f"Got matches: {matches!r}", + ) + + def test_invalid_yaml_template(self): + filename = "test/fixtures/templates/bad/core/config_invalid_yaml.yaml" + matches = self.helper_lint_string_from_file( + filename=filename, + config=ManualArgs(regions=["us-east-1", "us-west-2", "eu-west-1"]), + ) + self.assertEqual( + ["E0000"], [match.rule.id for match in matches], f"Got matches: {matches!r}" + ) + + def test_invalid_yaml_template_lint_all(self): + filename = "test/fixtures/templates/bad/core/config_invalid_yaml.yaml" + matches = self.helper_lint_string_from_file_all(filename=filename) + self.assertEqual( + ["E0000"], [match.rule.id for match in matches], f"Got matches: {matches!r}" + ) + + def test_invalid_json_template(self): + filename = "test/fixtures/templates/bad/core/config_invalid_json.json" + matches = self.helper_lint_string_from_file( + filename=filename, + config=ManualArgs(regions=["us-east-1", "us-west-2", "eu-west-1"]), + ) + self.assertEqual( + ["E0000"], [match.rule.id for match in matches], f"Got matches: {matches!r}" + ) + + def test_invalid_json_template_lint_all(self): + filename = "test/fixtures/templates/bad/core/config_invalid_json.json" + matches = self.helper_lint_string_from_file_all(filename=filename) + self.assertEqual(["E0000"], [match.rule.id for match in matches]) + + def test_issues_template(self): + filename = "test/fixtures/templates/bad/issues.yaml" + matches = self.helper_lint_string_from_file( + filename=filename, + config=ManualArgs(regions=["us-east-1", "us-west-2", "eu-west-1"]), + ) + self.assertEqual( + ["E1020"], [match.rule.id for match in matches], f"Got matches: {matches!r}" + ) + + def test_sam_template(self): + filename = "test/fixtures/templates/good/transform/list_transform_many.yaml" + matches = self.helper_lint_string_from_file(filename) + self.assertEqual([], matches, f"Got matches: {matches!r}") + + +class TestV0Usage(TestCase): + def helper_lint_string_from_file( + self, + filename, + rules=get_rules([], [], ["I", "W", "E"], include_experimental=True), + regions=REGIONS, + ): + with open(filename, "r") as f: + return lint(f.read(), rules, regions) + + def test_noecho_yaml_template(self): + filename = "test/fixtures/templates/bad/noecho.yaml" + matches = self.helper_lint_string_from_file(filename) + self.assertEqual( + ["W2010", "W2010"], + [match.rule.id for match in matches], + f"Got matches: {matches!r}", + ) + + def test_noecho_yaml_template_warnings_ignored(self): + filename = "test/fixtures/templates/bad/noecho.yaml" + rules = get_rules([], ["W", "I"], []) + matches = self.helper_lint_string_from_file(filename, rules=rules) + self.assertEqual([], matches, f"Got {matches!r}") + + def test_duplicate_json_template(self): + filename = "test/fixtures/templates/bad/duplicate.json" + matches = self.helper_lint_string_from_file(filename) + self.assertEqual( + ["E0000", "E0000", "E0000"], + [match.rule.id for match in matches], + f"Got matches: {matches!r}", + ) + + def test_invalid_yaml_template(self): + filename = "test/fixtures/templates/bad/core/config_invalid_yaml.yaml" + matches = self.helper_lint_string_from_file(filename) + self.assertEqual( + ["E0000"], [match.rule.id for match in matches], f"Got matches: {matches!r}" + ) + + def test_invalid_json_template(self): + filename = "test/fixtures/templates/bad/core/config_invalid_json.json" + matches = self.helper_lint_string_from_file(filename) + self.assertEqual( + ["E0000"], [match.rule.id for match in matches], f"Got matches: {matches!r}" + ) + + def test_issues_template(self): + filename = "test/fixtures/templates/bad/issues.yaml" + matches = self.helper_lint_string_from_file(filename) + self.assertEqual( + ["E1020"], [match.rule.id for match in matches], f"Got matches: {matches!r}" + ) + + def test_sam_template(self): + filename = "test/fixtures/templates/good/transform/list_transform_many.yaml" + matches = self.helper_lint_string_from_file(filename) + self.assertEqual([], matches, f"Got matches: {matches!r}") diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/test_string_template.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/test_string_template.py new file mode 100644 index 0000000000000000000000000000000000000000..9a2e5ac3f886dcac54e3572963c656b87c847ea3 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/test_string_template.py @@ -0,0 +1,24 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase + +import cfnlint.decode.cfn_json # pylint: disable=E0401 +import cfnlint.decode.cfn_yaml # pylint: disable=E0401 + + +class TestNonObjectTemplate(BaseTestCase): + """Test Duplicates Parsing""" + + def setUp(self): + """SetUp template object""" + + def test_fail_yaml_run(self): + """Test failure run""" + + filename = "test/fixtures/templates/bad/string.yaml" + + _, matches = cfnlint.decode.decode(filename) + assert len(matches) == 1 diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/transform/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/transform/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/transform/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/module/transform/test_transform.py b/testbed/aws-cloudformation__cfn-lint/test/unit/module/transform/test_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..a291a58b4b582e84c2c3fa98b556030d2f8cd065 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/module/transform/test_transform.py @@ -0,0 +1,154 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase + +from cfnlint.decode import cfn_yaml +from cfnlint.template.transforms._sam import Transform + + +class TestTransform(BaseTestCase): + """Test Transform Parsing""" + + def test_parameter_for_autopublish_version(self): + """Test Parameter is created for autopublish version run""" + filename = "test/fixtures/templates/good/transform/auto_publish_alias.yaml" + region = "us-east-1" + template = cfn_yaml.load(filename) + transformed_template = Transform(filename, template, region) + transformed_template.transform_template() + self.assertDictEqual( + transformed_template._parameters, {"Stage1": "Alias", "Stage2": "Alias"} + ) + self.assertDictEqual( + transformed_template._template.get("Resources") + .get("SkillFunctionAliasAlias") + .get("Properties"), + { + "Name": "Alias", + "FunctionName": {"Ref": "SkillFunction"}, + "FunctionVersion": { + "Fn::GetAtt": ["SkillFunctionVersion55ff35af87", "Version"] + }, + }, + ) + + def test_conversion_of_application_location(self): + """Tests if serverless application converts location to string when dict""" + filename = "test/fixtures/templates/good/transform/applications_location.yaml" + region = "us-east-1" + template = cfn_yaml.load(filename) + transformed_template = Transform(filename, template, region) + transformed_template.transform_template() + self.assertEqual( + transformed_template._template.get("Resources") + .get("App1") + .get("Properties") + .get("TemplateURL"), + "./step_function_local_definition.yaml", + ) + self.assertEqual( + transformed_template._template.get("Resources") + .get("App2") + .get("Properties") + .get("TemplateURL"), + "s3://bucket/value", + ) + + def test_conversion_of_step_function_definition_uri(self): + """ + Tests that the a serverless step function can convert + a local path to a s3 path + """ + filename = ( + "test/fixtures/templates/good/transform/step_function_local_definition.yaml" + ) + region = "us-east-1" + template = cfn_yaml.load(filename) + transformed_template = Transform(filename, template, region) + transformed_template.transform_template() + self.assertDictEqual( + transformed_template._template.get("Resources") + .get("StateMachine") + .get("Properties") + .get("DefinitionS3Location"), + {"Bucket": "bucket", "Key": "value"}, + ) + + def test_conversion_of_serverless_function_uri(self): + """Tests that the a serverless function can convert a CodeUri Sub""" + filename = "test/fixtures/templates/good/transform/function_use_s3_uri.yaml" + region = "us-east-1" + template = cfn_yaml.load(filename) + transformed_template = Transform(filename, template, region) + transformed_template.transform_template() + self.assertDictEqual( + transformed_template._template.get("Resources") + .get("Function") + .get("Properties") + .get("Code"), + {"S3Bucket": "bucket", "S3Key": "value"}, + ) + + def test_parameter_for_autopublish_version_bad(self): + """Test Parameter is created for autopublish version run""" + filename = "test/fixtures/templates/bad/transform/auto_publish_alias.yaml" + region = "us-east-1" + template = cfn_yaml.load(filename) + transformed_template = Transform(filename, template, region) + transformed_template.transform_template() + self.assertDictEqual(transformed_template._parameters, {}) + + def test_test_function_using_image_good(self): + """Test Parameter is created for autopublish version run""" + filename = "test/fixtures/templates/good/transform/function_using_image.yaml" + region = "us-east-1" + template = cfn_yaml.load(filename) + transformed_template = Transform(filename, template, region) + transformed_template.transform_template() + self.assertDictEqual(transformed_template._parameters, {}) + + def test_sam_with_language_extension(self): + """Test language extension""" + filename = "test/fixtures/templates/good/transform/language_extension.yaml" + region = "us-east-1" + template = cfn_yaml.load(filename) + transformed_template = Transform(filename, template, region) + results = transformed_template.transform_template() + self.assertEqual(results, []) + + def test_parameter_for_autopublish_code_sha256(self): + filename = ( + "test/fixtures/templates/good/transform/auto_publish_code_sha256.yaml" + ) + region = "us-east-1" + template = cfn_yaml.load(filename) + transformed_template = Transform(filename, template, region) + transformed_template.transform_template() + self.assertDictEqual(transformed_template._parameters, {}) + self.assertDictEqual( + transformed_template._template.get("Resources") + .get("LambdaFunction") + .get("Properties"), + { + "Code": { + "S3Bucket": {"Ref": "CodeBucket"}, + "S3Key": {"Fn::Sub": "${ Basepath }/lambda.zip"}, + }, + "Description": "fakesha", + "FunctionName": {"Fn::Sub": "${ AWS::StackName }"}, + "Handler": "lambda.handler", + "MemorySize": 256, + "Role": {"Fn::GetAtt": ["LambdaFunctionRole", "Arn"]}, + "Runtime": "python3.12", + "Tags": [{"Key": "lambda:createdBy", "Value": "SAM"}], + "Timeout": 30, + "TracingConfig": {"Mode": "PassThrough"}, + }, + ) + self.assertIn( + "LambdaFunctionVersionfakesha", + transformed_template._template.get("Resources").keys(), + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba28f38cb9bd8e14cb4d02b8acd8b93366e04967 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/__init__.py @@ -0,0 +1,62 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.testlib.testcase import BaseTestCase +from typing import List + +from cfnlint import ConfigMixIn, Rules +from cfnlint.config import ManualArgs +from cfnlint.runner import TemplateRunner + + +class BaseRuleTestCase(BaseTestCase): + """Used for Testing Rules""" + + success_templates: List[str] = [] + + def setUp(self): + """Setup""" + self.collection = Rules() + self.config = ConfigMixIn( + include_experimental=True, + include_checks=["I"], + ) + + def helper_file_positive(self, config=None): + """Success test""" + config = config or self.config + for filename in self.success_templates: + template = self.load_template(filename) + good_runner = TemplateRunner(filename, template, config, self.collection) + failures = list(good_runner.run()) + self.assertEqual( + [], failures, "Got failures {} on {}".format(failures, filename) + ) + + def helper_file_positive_template(self, filename, config=None): + """Success test with template parameter""" + config = config or self.config + template = self.load_template(filename) + good_runner = TemplateRunner(filename, template, config, self.collection) + failures = list(good_runner.run()) + self.assertEqual( + [], + failures, + "Expected {} failures but got {} on {}".format(0, failures, filename), + ) + + def helper_file_negative(self, filename, err_count, config=None): + """Failure test""" + config = config or self.config + template = self.load_template(filename) + bad_runner = TemplateRunner(filename, template, config, self.collection) + failures = list(bad_runner.run()) + self.assertEqual( + err_count, + len(failures), + "Expected {} failures but got {} on {}".format( + err_count, failures, filename + ), + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/conftest.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..57d44c225d906711793e0a02e5ca01058cc90e82 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/conftest.py @@ -0,0 +1,84 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from __future__ import annotations + +from collections import deque + +import pytest + +from cfnlint.context import Path, create_context_for_template +from cfnlint.helpers import FUNCTIONS +from cfnlint.jsonschema import CfnTemplateValidator +from cfnlint.template import Template + + +@pytest.fixture +def template(request): + if hasattr(request, "param"): + return request.param + return {} + + +@pytest.fixture +def regions(): + return ["us-east-1"] + + +@pytest.fixture +def cfn(template, regions): + return Template( + "", + template, + regions, + ) + + +@pytest.fixture +def path(request): + if hasattr(request, "param"): + t_path = deque(request.param.get("path", [])) + value_path = deque(request.param.get("value_path", [])) + cfn_path = deque(request.param.get("cfn_path", [])) + + return Path( + path=t_path, + value_path=value_path, + cfn_path=cfn_path, + ) + + return Path( + path=deque(), + value_path=deque(), + cfn_path=deque(), + ) + + +@pytest.fixture +def functions(): + return FUNCTIONS + + +@pytest.fixture +def strict_types(strict_types=True): + return strict_types + + +@pytest.fixture +def context(cfn, path, functions, strict_types): + return create_context_for_template(cfn).evolve( + path=path, + functions=functions, + strict_types=strict_types, + ) + + +@pytest.fixture +def validator(cfn, context): + return CfnTemplateValidator( + context=context, + cfn=cfn, + schema={}, + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/functions/test_sub_needed.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/functions/test_sub_needed.py new file mode 100644 index 0000000000000000000000000000000000000000..9941edd15a2e13011eda4b0e83ff4335df979bda --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/functions/test_sub_needed.py @@ -0,0 +1,59 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.unit.rules import BaseRuleTestCase + +from cfnlint import ConfigMixIn +from cfnlint.rules.functions.SubNeeded import SubNeeded # pylint: disable=E0401 + + +class TestSubNeeded(BaseRuleTestCase): + """Test Rules Get Att""" + + def setUp(self): + """Setup""" + super(TestSubNeeded, self).setUp() + self.collection.register(SubNeeded()) + self.success_templates = [ + "test/fixtures/templates/good/functions/sub.yaml", + "test/fixtures/templates/good/functions/sub_needed.yaml", + "test/fixtures/templates/good/functions/sub_needed_transform.yaml", + ] + + def test_file_positive(self): + """Test Positive""" + self.helper_file_positive() + + def test_template_config(self): + """Test custom excludes configuration""" + self.helper_file_positive_template( + "test/fixtures/templates/good/functions/sub_needed_custom_excludes.yaml", + ConfigMixIn( + [], + configure_rules={ + "E1029": {"custom_excludes": "^\\$\\{Stage\\}$"}, + }, + ), + ) + self.helper_file_positive_template( + "test/fixtures/templates/good/functions/sub_needed_custom_excludes.yaml", + ConfigMixIn( + [], + configure_rules={ + "E1029": {"custom_excludes": "^\\$\\{Stage\\}$"}, + }, + ), + ) + self.helper_file_negative( + "test/fixtures/templates/good/functions/sub_needed_custom_excludes.yaml", + 1, + ConfigMixIn([]), + ) + + def test_file_negative(self): + """Test failure""" + self.helper_file_negative( + "test/fixtures/templates/bad/functions/sub_needed.yaml", 7 + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/functions/test_sub_parameters_used.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/functions/test_sub_parameters_used.py new file mode 100644 index 0000000000000000000000000000000000000000..e782afdea264f049f8dc61b2643a302502051ba2 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/functions/test_sub_parameters_used.py @@ -0,0 +1,31 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.functions.SubParametersUsed import SubParametersUsed + + +@pytest.fixture(scope="module") +def rule(): + rule = SubParametersUsed() + yield rule + + +@pytest.mark.parametrize( + "name,instance,expected", + [ + ("Valid with matching parameters", ["${Foo}", {"Foo": "Bar"}], []), + ( + "Invalid with a missing parameter", + ["${Foo}", {"Foo": "Bar", "Bar": "Foo"}], + [ValidationError("Parameter 'Bar' not used in 'Fn::Sub'", path=[1, "Bar"])], + ), + ], +) +def test_sub_parameters_used(name, instance, expected, rule, validator): + errors = list(rule.validate(validator, {}, instance, {})) + assert errors == expected, f"Test {name!r} got {errors!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/helpers/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/helpers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/apigateway/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/apigateway/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/apigateway/test_restapi_openapi.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/apigateway/test_restapi_openapi.py new file mode 100644 index 0000000000000000000000000000000000000000..046c819852bbb3e727577308a7e2c3114eb699c6 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/apigateway/test_restapi_openapi.py @@ -0,0 +1,60 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.apigateway.RestApiOpenApi import RestApiOpenApi + + +@pytest.fixture(scope="module") +def rule(): + rule = RestApiOpenApi() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "Name": "Foo", + }, + [], + ), + ( + { + "Body": "Foo", + }, + [], + ), + ( + { + "BodyS3Location": "s3://foo", + }, + [], + ), + ( + {}, + [ + ValidationError( + ( + "'Name' is a required property when not specifying " + "one of ['Body', 'BodyS3Location']" + ), + rule=RestApiOpenApi(), + path=deque([]), + validator="required", + schema_path=deque(["else", "required"]), + ) + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/backup/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/backup/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/backup/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/backup/test_backup_plan_lifecycle_rule.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/backup/test_backup_plan_lifecycle_rule.py new file mode 100644 index 0000000000000000000000000000000000000000..368a4f57b6dceea4bb076511acc4eec699b89a36 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/backup/test_backup_plan_lifecycle_rule.py @@ -0,0 +1,70 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.backup.BackupPlanLifecycleRule import ( + BackupPlanLifecycleRule, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = BackupPlanLifecycleRule() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + {}, + [], + ), + ( + { + "DeleteAfterDays": 100, + "MoveToColdStorageAfterDays": 10, + }, + [], + ), + ( + { + "DeleteAfterDays": "foo", + "MoveToColdStorageAfterDays": 10, + }, + [], + ), + ( + { + "DeleteAfterDays": 100, + "MoveToColdStorageAfterDays": "foo", + }, + [], + ), + ( + { + "DeleteAfterDays": 10, + "MoveToColdStorageAfterDays": 30, + }, + [ + ValidationError( + ( + "DeleteAfterDays 10 must be at least 90 " + "days after MoveToColdStorageAfterDays 30" + ), + rule=BackupPlanLifecycleRule(), + path=deque(["DeleteAfterDays"]), + ) + ], + ), + ], +) +def test_backup_lifecycle(instance, expected, rule, validator): + errs = list(rule.validate(validator, "LambdaRuntime", instance, {})) + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/cloudformation/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/cloudformation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/cloudformation/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/cloudformation/test_nested_stack_parameters.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/cloudformation/test_nested_stack_parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..00aa93d69ae2b3efadf6293a84e45d49514a5262 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/cloudformation/test_nested_stack_parameters.py @@ -0,0 +1,42 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import logging +from test.unit.rules import BaseRuleTestCase + +from cfnlint.rules.resources.cloudformation.NestedStackParameters import ( + NestedStackParameters, # pylint: disable=E0401 +) + + +class TestNestedStackParameters(BaseRuleTestCase): + """Test CloudFormation Nested stack parameters""" + + def tearDown(self) -> None: + super().tearDown() + logger = logging.getLogger("cfnlint.decode.decode") + logger.disabled = False + + def setUp(self): + """Setup""" + super(TestNestedStackParameters, self).setUp() + self.collection.register(NestedStackParameters()) + logger = logging.getLogger("cfnlint.decode.decode") + logger.disabled = True + self.success_templates = [ + "test/fixtures/templates/good/resources/cloudformation/stacks.yaml" + ] + + def test_file_positive(self): + """Test Positive""" + self.helper_file_positive() + + def test_file_negative(self): + """Test failure""" + err_count = 8 + self.helper_file_negative( + "test/fixtures/templates/bad/resources/cloudformation/stacks.yaml", + err_count, + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/cloudwatch/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/cloudwatch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/cloudwatch/test_alarm_period.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/cloudwatch/test_alarm_period.py new file mode 100644 index 0000000000000000000000000000000000000000..0d61f67e350b9eca2108e030de073b85ef4a1434 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/cloudwatch/test_alarm_period.py @@ -0,0 +1,116 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.cloudwatch.AlarmPeriod import AlarmPeriod + + +@pytest.fixture(scope="module") +def rule(): + rule = AlarmPeriod() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "Period": 60, + }, + [], + ), + ( + [], # wrong type + [], + ), + ( + { + "Period": {"Ref": "Period"}, # ignore when object + }, + [], + ), + ( + { + "Period": 30, + }, + [], + ), + ( + { + "Period": 600, + }, + [], + ), + ( + { + "Period": 45, + }, + [ + ValidationError( + "45 is not one of [10, 30, 60] or a multiple of 60", + rule=AlarmPeriod(), + path=deque(["Period"]), + validator="enum", + schema_path=deque(["then", "properties", "Period", "then", "enum"]), + ) + ], + ), + ( + { + "Period": "45", + }, + [ + ValidationError( + "'45' is not one of [10, 30, 60] or a multiple of 60", + rule=AlarmPeriod(), + path=deque(["Period"]), + validator="enum", + schema_path=deque(["then", "properties", "Period", "then", "enum"]), + ) + ], + ), + ( + { + "Period": 121, + }, + [ + ValidationError( + "121 is not one of [10, 30, 60] or a multiple of 60", + rule=AlarmPeriod(), + path=deque(["Period"]), + validator="multipleOf", + schema_path=deque( + ["then", "properties", "Period", "else", "multipleOf"] + ), + ) + ], + ), + ( + { + "Period": "121", + }, + [ + ValidationError( + "'121' is not one of [10, 30, 60] or a multiple of 60", + rule=AlarmPeriod(), + path=deque(["Period"]), + validator="multipleOf", + schema_path=deque( + ["then", "properties", "Period", "else", "multipleOf"] + ), + ) + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/ec2/test_sg_all_to_and_from_ports.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/ec2/test_sg_all_to_and_from_ports.py new file mode 100644 index 0000000000000000000000000000000000000000..a82f8acf5918b1b87c33e352b5e345e4a543c9b7 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/ec2/test_sg_all_to_and_from_ports.py @@ -0,0 +1,155 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.ectwo.SecurityGroupAllToAndFromPorts import ( + SecurityGroupAllToAndFromPorts, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = SecurityGroupAllToAndFromPorts() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "ToPort": -1, + "FromPort": -1, + }, + [], + ), + ( + [], # wrong type + [], + ), + ( + { + "ToPort": "-1", + "FromPort": -1, + }, + [], + ), + ( + { + "IpProtocol": 1, + "ToPort": -1, + "FromPort": 8, + }, + [], + ), + ( + { + "ToPort": -1, + }, + [ + ValidationError( + ("Both ['FromPort', 'ToPort'] must " "be -1 when one is -1"), + rule=SecurityGroupAllToAndFromPorts(), + path=deque([]), + validator="required", + validator_value=["FromPort"], + instance={"ToPort": -1}, + schema={ + "properties": {"FromPort": {"enum": [-1, "-1"]}}, + "required": ["FromPort"], + }, + schema_path=deque(["else", "allOf", 0, "then", "required"]), + ) + ], + ), + ( + { + "FromPort": -1, + }, + [ + ValidationError( + ("Both ['FromPort', 'ToPort'] must " "be -1 when one is -1"), + rule=SecurityGroupAllToAndFromPorts(), + path=deque([]), + validator="required", + validator_value=["ToPort"], + instance={"FromPort": -1}, + schema={ + "properties": {"ToPort": {"enum": [-1, "-1"]}}, + "required": ["ToPort"], + }, + schema_path=deque(["else", "allOf", 1, "then", "required"]), + ) + ], + ), + ( + { + "ToPort": -1, + "FromPort": 5, + }, + [ + ValidationError( + ("Both ['FromPort', 'ToPort'] must " "be -1 when one is -1"), + rule=SecurityGroupAllToAndFromPorts(), + path=deque(["FromPort"]), + validator="enum", + validator_value=[-1, "-1"], + instance=5, + schema={"enum": [-1, "-1"]}, + schema_path=deque( + ["else", "allOf", 0, "then", "properties", "FromPort", "enum"] + ), + ) + ], + ), + ( + { + "ToPort": 5, + "FromPort": -1, + }, + [ + ValidationError( + ("Both ['FromPort', 'ToPort'] must " "be -1 when one is -1"), + rule=SecurityGroupAllToAndFromPorts(), + path=deque(["ToPort"]), + validator="enum", + validator_value=[-1, "-1"], + instance=5, + schema={"enum": [-1, "-1"]}, + schema_path=deque( + ["else", "allOf", 1, "then", "properties", "ToPort", "enum"] + ), + ) + ], + ), + ( + { + "IpProtocol": "icmp", + "ToPort": 8, + "FromPort": -1, + }, + [ + ValidationError( + ("Both ['FromPort', 'ToPort'] must " "be -1 when one is -1"), + rule=SecurityGroupAllToAndFromPorts(), + path=deque(["ToPort"]), + validator="enum", + validator_value=[-1, "-1"], + instance=5, + schema={"enum": [-1, "-1"]}, + schema_path=deque(["then", "then", "properties", "ToPort", "enum"]), + ) + ], + ), + ], +) +def test_backup_lifecycle(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/ec2/test_sg_protocols_ports_inclusive.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/ec2/test_sg_protocols_ports_inclusive.py new file mode 100644 index 0000000000000000000000000000000000000000..3293eb9fdcc93080006e9e8219def8d46ad9a744 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/ec2/test_sg_protocols_ports_inclusive.py @@ -0,0 +1,66 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.ectwo.SecurityGroupProtocolsAndPortsInclusive import ( + SecurityGroupProtocolsAndPortsInclusive, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = SecurityGroupProtocolsAndPortsInclusive() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "IpProtocol": -1, + }, + [], + ), + ( + { + "IpProtocol": 9, + }, + [], + ), + ( + [], # wrong type + [], + ), + ( + { + "IpProtocol": "tcp", + "FromPort": 1, + }, + [ + ValidationError( + ( + "['FromPort', 'ToPort'] are required properties " + "when using 'IpProtocol' value 'tcp'" + ), + rule=SecurityGroupProtocolsAndPortsInclusive(), + path=deque([]), + instance={"IpProtocol": "tcp", "FromPort": 1}, + validator="required", + validator_value=["FromPort", "ToPort"], + schema_path=deque(["then", "required"]), + ) + ], + ), + ], +) +def test_backup_lifecycle(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/ecs/test_service_health_check_grace_period_seconds.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/ecs/test_service_health_check_grace_period_seconds.py new file mode 100644 index 0000000000000000000000000000000000000000..dcabd42182f50dfe40d2880c46bcf1cc260f0d98 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/ecs/test_service_health_check_grace_period_seconds.py @@ -0,0 +1,115 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.ecs.ServiceHealthCheckGracePeriodSeconds import ( + ServiceHealthCheckGracePeriodSeconds, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = ServiceHealthCheckGracePeriodSeconds() + yield rule + + +@pytest.fixture +def template(): + return { + "Conditions": { + "IsUsEast1": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]} + }, + } + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + {"HealthCheckGracePeriodSeconds": "Foo", "LoadBalancers": ["Bar"]}, + [], + ), + ( + {"LoadBalancers": []}, + [], + ), + ( + [], # wrong type + [], + ), + ( + {"HealthCheckGracePeriodSeconds": "Foo", "LoadBalancers": []}, + [ + ValidationError( + "[] is too short (1)", + rule=ServiceHealthCheckGracePeriodSeconds(), + path=deque(["LoadBalancers"]), + validator="minItems", + schema_path=deque( + ["then", "then", "properties", "LoadBalancers", "minItems"] + ), + ) + ], + ), + ( + { + "HealthCheckGracePeriodSeconds": "Foo", + }, + [ + ValidationError( + "'LoadBalancers' is a required property", + rule=ServiceHealthCheckGracePeriodSeconds(), + path=deque([]), + validator="required", + schema_path=deque(["then", "required"]), + ) + ], + ), + ( + { + "HealthCheckGracePeriodSeconds": "Foo", + "LoadBalancers": [ + {"Fn::If": ["IsUsEast1", "Bar", {"Ref": "AWS::NoValue"}]} + ], + }, + [ + ValidationError( + "[] is too short (1)", + rule=ServiceHealthCheckGracePeriodSeconds(), + path=deque(["LoadBalancers"]), + validator="minItems", + schema_path=deque( + ["then", "then", "properties", "LoadBalancers", "minItems"] + ), + ) + ], + ), + ( + { + "HealthCheckGracePeriodSeconds": "Foo", + "LoadBalancers": { + "Fn::If": ["IsUsEast1", ["Bar"], {"Ref": "AWS::NoValue"}] + }, + }, + [ + ValidationError( + "'LoadBalancers' is a required property", + rule=ServiceHealthCheckGracePeriodSeconds(), + path=deque([]), + validator="required", + schema_path=deque(["then", "required"]), + ) + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/ecs/test_task_definition_aws_vpc.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/ecs/test_task_definition_aws_vpc.py new file mode 100644 index 0000000000000000000000000000000000000000..3db1ac38f495343c9062238f49c1b1ff5181e708 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/ecs/test_task_definition_aws_vpc.py @@ -0,0 +1,212 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from __future__ import annotations + +from collections import deque + +import jsonpatch +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.helpers import get_value_from_path +from cfnlint.rules.resources.ecs.TaskDefinitionAwsVpc import TaskDefinitionAwsVpc + + +@pytest.fixture +def rule(): + rule = TaskDefinitionAwsVpc() + yield rule + + +_task_definition = { + "Type": "AWS::ECS::TaskDefinition", + "Properties": { + "NetworkMode": "awsvpc", + "ContainerDefinitions": [ + { + "Name": "my-container", + "Image": "my-image", + "PortMappings": [ + { + "ContainerPort": 8080, + } + ], + } + ], + }, +} + + +@pytest.mark.parametrize( + "template,start_path,expected", + [ + ( + { + "Resources": { + "TaskDefinition": dict(_task_definition), + } + }, + deque(["Resources", "TaskDefinition", "Properties"]), + [], + ), + ( + { + "Resources": { + "TaskDefinition": jsonpatch.apply_patch( + dict(_task_definition), + [ + { + "op": "add", + "path": ( + "/Properties/ContainerDefinitions/" + "0/PortMappings/0/HostPort" + ), + "value": "8080", + }, + ], + ), + } + }, + deque(["Resources", "TaskDefinition", "Properties"]), + [], + ), + ( + { + "Resources": { + "TaskDefinition": jsonpatch.apply_patch( + dict(_task_definition), + [ + { + "op": "add", + "path": ( + "/Properties/ContainerDefinitions/" + "0/PortMappings/0/HostPort" + ), + "value": "8080", + }, + { + "op": "replace", + "path": ( + "/Properties/ContainerDefinitions/" + "0/PortMappings/0/ContainerPort" + ), + "value": {"Fn::Sub": "8080"}, + }, + ], + ), + } + }, + deque(["Resources", "TaskDefinition", "Properties"]), + [], + ), + ( + { + "Parameters": { + "MyPort": {"Type": "String"}, + "MySecondPort": {"Type": "String"}, + }, + "Resources": { + "TaskDefinition": jsonpatch.apply_patch( + dict(_task_definition), + [ + { + "op": "add", + "path": ( + "/Properties/ContainerDefinitions/0" + "/PortMappings/0/ContainerPort" + ), + "value": {"Ref": "MyPort"}, + }, + { + "op": "add", + "path": ( + "/Properties/ContainerDefinitions/0" + "/PortMappings/0/HostPort" + ), + "value": {"Ref": "MySecondPort"}, + }, + ], + ), + }, + }, + deque(["Resources", "TaskDefinition", "Properties"]), + [], + ), + ( + { + "Resources": { + "TaskDefinition": jsonpatch.apply_patch( + dict(_task_definition), + [ + { + "op": "add", + "path": ( + "/Properties/ContainerDefinitions/0" + "/PortMappings/0/HostPort" + ), + "value": "80", + }, + { + "op": "replace", + "path": ("/Properties/NetworkMode"), + "value": "bridge", + }, + ], + ), + } + }, + deque(["Resources", "TaskDefinition", "Properties"]), + [], + ), + ( + { + "Resources": { + "TaskDefinition": jsonpatch.apply_patch( + dict(_task_definition), + [ + { + "op": "add", + "path": ( + "/Properties/ContainerDefinitions/0" + "/PortMappings/0/HostPort" + ), + "value": "80", + } + ], + ), + } + }, + deque(["Resources", "TaskDefinition", "Properties"]), + [ + ValidationError( + ("'80' does not equal 8080"), + validator="const", + rule=TaskDefinitionAwsVpc(), + path_override=deque( + [ + "Resources", + "TaskDefinition", + "Properties", + "ContainerDefinitions", + 0, + "PortMappings", + 0, + "HostPort", + ] + ), + ) + ], + ), + ], + indirect=["template"], +) +def test_validate(template, start_path, expected, rule, validator): + for instance, instance_validator in get_value_from_path( + validator, template, start_path + ): + errs = list(rule.validate(instance_validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elasticache/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elasticache/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elasticache/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elasticache/test_cache_cluster_failover.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elasticache/test_cache_cluster_failover.py new file mode 100644 index 0000000000000000000000000000000000000000..4ed24bf0d7d1807e127e37f0c7c6cd4fdba5a045 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elasticache/test_cache_cluster_failover.py @@ -0,0 +1,33 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.unit.rules import BaseRuleTestCase + +from cfnlint.rules.resources.elasticache.CacheClusterFailover import ( + CacheClusterFailover, # pylint: disable=E0401 +) + + +class TestElasticCacheClusterFailover(BaseRuleTestCase): + """Test ElasticCache CacheClusterFailover""" + + def setUp(self): + """Setup""" + super(TestElasticCacheClusterFailover, self).setUp() + self.collection.register(CacheClusterFailover()) + self.success_templates = [ + "test/fixtures/templates/good/resources/elasticache/cache_cluster_failover.yaml" + ] + + def test_file_positive(self): + """Test Positive""" + self.helper_file_positive() + + def test_file_artifact_failure(self): + """Test failure""" + self.helper_file_negative( + "test/fixtures/templates/bad/resources/elasticache/cache_cluster_failover.yaml", + 5, + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elb/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elb/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elb/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elb/test_certificate.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elb/test_certificate.py new file mode 100644 index 0000000000000000000000000000000000000000..a5fd9bd2c62b6049b8f15a09abfcb53c221cd53f --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elb/test_certificate.py @@ -0,0 +1,50 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.elb.Certificate import Certificate + + +@pytest.fixture(scope="module") +def rule(): + rule = Certificate() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + {"Protocol": "HTTP"}, + [], + ), + ( + {"Protocol": "HTTPS", "SSLCertificateId": "Id"}, + [], + ), + ( + { + "Protocol": "SSL", + }, + [ + ValidationError( + ("'SSLCertificateId' is a required property"), + rule=Certificate(), + path=deque([]), + validator="required", + schema_path=deque(["then", "required"]), + ) + ], + ), + ], +) +def test_backup_lifecycle(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elbv2/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elbv2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elbv2/test_listener_certificate.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elbv2/test_listener_certificate.py new file mode 100644 index 0000000000000000000000000000000000000000..fbca794d19ad87ad49092b64f9e369dbc0c2be5d --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elbv2/test_listener_certificate.py @@ -0,0 +1,52 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.elasticloadbalancingv2.ListenerCertificate import ( + ListenerCertificate, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = ListenerCertificate() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + {"Protocol": "HTTP"}, + [], + ), + ( + {"Protocol": "HTTPS", "Certificates": ["Certificate"]}, + [], + ), + ( + { + "Protocol": "TLS", + }, + [ + ValidationError( + ("'Certificates' is a required property"), + rule=ListenerCertificate(), + path=deque([]), + validator="required", + schema_path=deque(["then", "required"]), + ) + ], + ), + ], +) +def test_backup_lifecycle(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elbv2/test_loadbalancer_application_subnets.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elbv2/test_loadbalancer_application_subnets.py new file mode 100644 index 0000000000000000000000000000000000000000..3ff797df518134f35fa37785f03bda95aea558b4 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/elbv2/test_loadbalancer_application_subnets.py @@ -0,0 +1,71 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError + +# ruff: noqa: E501 +from cfnlint.rules.resources.elasticloadbalancingv2.LoadBalancerApplicationSubnets import ( + LoadBalancerApplicationSubnets, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = LoadBalancerApplicationSubnets() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + {"Type": "network"}, + [], + ), + ( + {"Type": "application", "Subnets": ["SubnetA", "SubnetB"]}, + [], + ), + ( + {"Type": "network", "Subnets": ["SubnetA"]}, + [], + ), + ( + {"Subnets": ["SubnetA"]}, + [ + ValidationError( + ("['SubnetA'] is too short (2)"), + rule=LoadBalancerApplicationSubnets(), + path=deque(["Subnets"]), + validator="minItems", + schema_path=deque(["then", "properties", "Subnets", "minItems"]), + ) + ], + ), + ( + { + "Type": "application", + "Subnets": ["SubnetA"], + }, + [ + ValidationError( + ("['SubnetA'] is too short (2)"), + rule=LoadBalancerApplicationSubnets(), + path=deque(["Subnets"]), + validator="minItems", + schema_path=deque(["then", "properties", "Subnets", "minItems"]), + ) + ], + ), + ], +) +def test_backup_lifecycle(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/events/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/events/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/events/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/events/test_rule_schedule_expression.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/events/test_rule_schedule_expression.py new file mode 100644 index 0000000000000000000000000000000000000000..a3a288170e0dcab7b3b66a0cfbf255d4e01c17a6 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/events/test_rule_schedule_expression.py @@ -0,0 +1,171 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.events.RuleScheduleExpression import RuleScheduleExpression + + +@pytest.fixture(scope="module") +def rule(): + rule = RuleScheduleExpression() + yield rule + + +@pytest.mark.parametrize( + "name,instance,expected", + [ + ( + "wrong format", + [], + [], + ), + ( + "10:15 AM (UTC) every day", + "cron(15 10 * * ? *)", + [], + ), + ( + "6:00 PM Monday through Friday", + "cron(0 18 ? * MON-FRI *)", + [], + ), + ( + "8:00 AM on the first day of the month", + "cron(0 8 1 * ? *)", + [], + ), + ( + "Every 10 min on weekdays", + "cron(0/10 * ? * MON-FRI *)", + [], + ), + ( + "Every 5 minutes between 8:00 AM and 5:55 PM weekdays", + "cron(0/5 8-17 ? * MON-FRI *)", + [], + ), + ( + "9:00 AM on the first Monday of each month", + "cron(0 9 ? * 2#1 *)", + [], + ), + ( + "Every 5 minutes", + "rate(5 minutes)", + [], + ), + ( + "Every hour", + "rate(1 hour)", + [], + ), + ( + "Every seven days", + "rate(7 days)", + [], + ), + ( + "has to be cron() or rate()", + "daily", + [ + ValidationError( + ("'daily' has to be either 'cron()' or 'rate()'"), + ) + ], + ), + ( + "Empty cron", + "cron()", + [ + ValidationError( + ("'' is not of type 'string'"), + ) + ], + ), + ( + "Empty rate", + "rate()", + [ + ValidationError( + ("'' is not of type 'string'"), + ) + ], + ), + ( + "Not enough values", + "rate(5)", + [ + ValidationError( + ("'5' has to be of format rate(Value Unit)"), + ) + ], + ), + ( + "Value has to be a digit", + "rate(five minutes)", + [ + ValidationError( + ("'five' is not of type 'integer'"), + ) + ], + ), + ( + "Not enough values", + "cron(0 */1 * * WED)", + [ + ValidationError( + ( + ( + "'0' is not of length 6. (Minutes Hours " + "Day-of-month Month Day-of-week Year)" + ) + ), + ) + ], + ), + ( + ( + "Specify the Day-of-month and Day-of-week " + "fields in the same cron expression" + ), + "cron(* 1 * * * *)", + [ + ValidationError( + ( + ( + "'*' specifies both Day-of-month and " + "Day-of-week. (Minutes Hours " + "Day-of-month Month Day-of-week Year)" + ) + ), + ) + ], + ), + ( + "Value of 1 should be singular. 'minute' not 'minutes'", + "rate(1 minutes)", + [ + ValidationError( + ("'minutes' is not one of ['minute', 'hour', 'day']"), + ) + ], + ), + ( + "Value has to be greater than 0", + "rate(0 hour)", + [ + ValidationError( + ("'0' is less than the minimum of 0"), + ) + ], + ), + ], +) +def test_validate(name, instance, expected, rule, validator): + + errs = list(rule.validate(validator, {}, instance, {})) + assert errs == expected, f"Test {name!r} got {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/iam/test_iam_policy_version.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/iam/test_iam_policy_version.py new file mode 100644 index 0000000000000000000000000000000000000000..7ef70804162caca8384ed8b4eb534c305310abe8 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/iam/test_iam_policy_version.py @@ -0,0 +1,37 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.iam.PolicyVersion import PolicyVersion + + +@pytest.fixture(scope="module") +def rule(): + rule = PolicyVersion() + yield rule + + +@pytest.mark.parametrize( + "name,instance,expected", + [ + ("Valid version", "2012-10-17", []), + ( + "Invalid version", + "2008-10-17", + [ + ValidationError( + "IAM Policy Version should be updated to '2012-10-17'", + rule=PolicyVersion(), + ), + ], + ), + ("No error on invalid structure", {}, []), + ], +) +def test_policy_version(name, instance, expected, rule, validator): + errors = list(rule.validate(validator, {}, instance, {})) + assert errors == expected, f"Test {name!r} got {errors!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/iam/test_identity_policy.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/iam/test_identity_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..ced3940fc75bf3a2520eced481fc86c99b8fc4a6 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/iam/test_identity_policy.py @@ -0,0 +1,210 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from unittest import TestCase + +from cfnlint.context import Context +from cfnlint.helpers import FUNCTIONS +from cfnlint.jsonschema import CfnTemplateValidator +from cfnlint.rules.resources.iam.IdentityPolicy import IdentityPolicy + + +class TestIdentityPolicies(TestCase): + """Test IAM identity Policies""" + + def setUp(self): + """Setup""" + self.rule = IdentityPolicy() + + def test_object_basic(self): + """Test Positive""" + validator = CfnTemplateValidator() + + policy = {"Version": "2012-10-18"} + + errs = list( + self.rule.validate( + validator=validator, policy=policy, schema={}, policy_type=None + ) + ) + self.assertEqual(errs[0].message, "'Statement' is a required property") + self.assertListEqual(list(errs[0].path), []) + self.assertEqual(len(errs), 2, errs) + self.assertEqual( + errs[1].message, "'2012-10-18' is not one of ['2008-10-17', '2012-10-17']" + ) + self.assertListEqual(list(errs[1].path), ["Version"]) + + def test_object_multiple_effect(self): + validator = CfnTemplateValidator() + + policy = { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "NotAction": "*", + "Action": [ + "cloudformation:*", + ], + "Resource": "*", + } + ], + } + + errs = list( + self.rule.validate( + validator=validator, policy=policy, schema={}, policy_type=None + ) + ) + self.assertEqual(len(errs), 2, errs) + self.assertEqual( + errs[0].message, + ("Only one of ['Action', 'NotAction'] is a required property"), + ) + self.assertEqual( + errs[1].message, + ("Only one of ['Action', 'NotAction'] is a required property"), + ) + self.assertIn( + ["Statement", 0, "NotAction"], [list(errs[0].path), list(errs[1].path)] + ) + self.assertIn( + ["Statement", 0, "Action"], [list(errs[0].path), list(errs[1].path)] + ) + + def test_object_statements(self): + validator = CfnTemplateValidator({}).evolve( + context=Context(functions=FUNCTIONS) + ) + + policy = { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "NotAllow", + "Action": [ + "cloudformation:Describe*", + "cloudformation:List*", + "cloudformation:Get*", + ], + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:iam::123456789012:role/object-role" + }, + { + "Fn::Sub": "arn:aws:cloudformation:${AWS::Region}:aws:transform/Serverless-2016-10-31" + }, + { + "NotValid": [ + "arn:${AWS::Partition}:iam::123456789012:role/object-role" + ] + }, + "arn:aws:medialive:*", + ], + } + ], + } + + errs = list( + self.rule.validate( + validator=validator, policy=policy, schema={}, policy_type=None + ) + ) + self.assertEqual(len(errs), 2, errs) + self.assertEqual(errs[0].message, "'NotAllow' is not one of ['Allow', 'Deny']") + self.assertListEqual(list(errs[0].path), ["Statement", 0, "Effect"]) + self.assertEqual( + errs[1].message, + "{'NotValid': ['arn:${AWS::Partition}:iam::123456789012:role/object-role']} is not of type 'string'", + ) + self.assertListEqual(list(errs[1].path), ["Statement", 0, "Resource", 2]) + + def test_string_statements(self): + """Test Positive""" + validator = CfnTemplateValidator() + + # ruff: noqa: E501 + policy = """ + { + "Version": "2012-10-18", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "cloudformation:Describe*", + "cloudformation:List*", + "cloudformation:Get*" + ], + "Resource": [ + "*", + {"Fn::Sub": ["arn:${AWS::Partition}:iam::123456789012/role/string-role"]} + ] + } + ] + } + """ + + errs = list( + self.rule.validate( + validator=validator, policy=policy, schema={}, policy_type=None + ) + ) + self.assertEqual(len(errs), 2, errs) + self.assertEqual( + errs[0].message, + "{'Fn::Sub': ['arn:${AWS::Partition}:iam::123456789012/role/string-role']} is not of type 'string'", + ) + self.assertListEqual(list(errs[0].path), ["Statement", 0, "Resource", 1]) + self.assertEqual( + errs[1].message, "'2012-10-18' is not one of ['2008-10-17', '2012-10-17']" + ) + self.assertListEqual(list(errs[1].path), ["Version"]) + + def test_string_statements_with_condition(self): + validator = CfnTemplateValidator() + + policy = """ + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "*", + "Resource": "*", + "Condition": { + "iam:PassedToService": "cloudformation.amazonaws.com", + "StringEquals": {"aws:PrincipalTag/job-category": "iamuser-admin"}, + "StringLike": {"s3:prefix": ["", "home/", "home/${aws:username}/"]}, + "ArnLike": {"aws:SourceArn": "arn:aws:cloudtrail:*:111122223333:trail/*"}, + "NumericLessThanEquals": {"s3:max-keys": "10"}, + "DateGreaterThan": {"aws:TokenIssueTime": "2020-01-01T00:00:01Z"}, + "Bool": { "aws:SecureTransport": "false"}, + "BinaryEquals": { "key" : "QmluYXJ5VmFsdWVJbkJhc2U2NA=="}, + "IpAddress": {"aws:SourceIp": "203.0.113.0/24"}, + "ArnEquals": {"aws:SourceArn": "arn:aws:sns:REGION:123456789012:TOPIC-ID"}, + "StringLikeIfExists": { "ec2:InstanceType": [ "t1.*", "t2.*" ]}, + "Null":{"aws:TokenIssueTime":"true"}, + "ForAllValues:StringEquals":{"aws:PrincipalTag/job-category":["iamuser-admin","iamuser-read-only"]}, + "ForAnyValue:StringEquals":{"aws:PrincipalTag/job-category":"iamuser-admin"}, + "ForAllValues:StringLike": {"aws:TagKeys": ["key1*"]} + } + } + ] + } + """ + + errs = list( + self.rule.validate( + validator=validator, policy=policy, schema={}, policy_type=None + ) + ) + self.assertEqual(len(errs), 1, errs) + self.assertTrue( + errs[0].message.startswith("'iam:PassedToService' does not match") + ) + self.assertListEqual( + list(errs[0].path), ["Statement", 0, "Condition", "iam:PassedToService"] + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/iam/test_resource_ecr_policy.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/iam/test_resource_ecr_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..957c50022fc0572440860f58f1f7cdb41dc45a49 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/iam/test_resource_ecr_policy.py @@ -0,0 +1,52 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from unittest import TestCase + +from cfnlint.jsonschema import CfnTemplateValidator +from cfnlint.rules.resources.iam.ResourceEcrPolicy import ResourceEcrPolicy + + +class TestResourceEcrPolicy(TestCase): + """Test IAM identity Policies""" + + def setUp(self): + """Setup""" + self.rule = ResourceEcrPolicy() + + def test_string_statements(self): + """Test Positive""" + validator = CfnTemplateValidator() + + # no resource statement + # ruff: noqa: E501 + policy = """ + { + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "AllowCrossAccountPush", + "Effect": "Allow", + "Principal": { + "AWS": "arn:aws:iam::123456789012:root" + }, + "Action": [ + "ecr:BatchCheckLayerAvailability", + "ecr:CompleteLayerUpload", + "ecr:InitiateLayerUpload", + "ecr:PutImage", + "ecr:UploadLayerPart" + ] + } + ] + } + """ + + errs = list( + self.rule.validate( + validator=validator, policy=policy, schema={}, policy_type=None + ) + ) + self.assertEqual(len(errs), 0, errs) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/iam/test_resource_policy.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/iam/test_resource_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..1651f94e2fe9e22dddc6fae53bb072bece6fab63 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/iam/test_resource_policy.py @@ -0,0 +1,252 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from unittest import TestCase + +from cfnlint.context import Context +from cfnlint.helpers import FUNCTIONS +from cfnlint.jsonschema import CfnTemplateValidator +from cfnlint.rules.resources.iam.ResourcePolicy import ResourcePolicy + + +class TestResourcePolicy(TestCase): + """Test IAM identity Policies""" + + def setUp(self): + """Setup""" + self.rule = ResourcePolicy() + + def test_object_basic(self): + """Test Positive""" + validator = CfnTemplateValidator() + + policy = {"Version": "2012-10-18"} + + errs = list( + self.rule.validate( + validator=validator, policy=policy, schema={}, policy_type=None + ) + ) + self.assertEqual(len(errs), 2, errs) + self.assertEqual(errs[0].message, "'Statement' is a required property") + self.assertListEqual(list(errs[0].path), []) + self.assertEqual( + errs[1].message, "'2012-10-18' is not one of ['2008-10-17', '2012-10-17']" + ) + self.assertListEqual(list(errs[1].path), ["Version"]) + + def test_object_multiple_effect(self): + validator = CfnTemplateValidator() + + policy = { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "NotAction": "*", + "Action": [ + "cloudformation:*", + ], + "Resource": "*", + "Principal": { + "AWS": [ + "arn:aws:iam::123456789012:root", + "999999999999", + "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E1234ABCDE12AB", + ], + "CanonicalUser": "79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be", + }, + "Condition": { + "Null": { + "s3:x-amz-server-side-encryption": ["false"], + "aws:TagKeys": "false", + } + }, + } + ], + } + + errs = list( + self.rule.validate( + validator=validator, policy=policy, schema={}, policy_type=None + ) + ) + self.assertEqual(len(errs), 2, errs) + self.assertEqual( + errs[0].message, + ("Only one of ['Action', 'NotAction'] is a required property"), + ) + self.assertEqual( + errs[1].message, + ("Only one of ['Action', 'NotAction'] is a required property"), + ) + self.assertIn( + ["Statement", 0, "NotAction"], [list(errs[0].path), list(errs[1].path)] + ) + self.assertIn( + ["Statement", 0, "Action"], [list(errs[0].path), list(errs[1].path)] + ) + + def test_object_statements(self): + validator = CfnTemplateValidator({}).evolve( + context=Context(functions=FUNCTIONS) + ) + + policy = { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "NotAllow", + "Action": [ + "cloudformation:Describe*", + "cloudformation:List*", + "cloudformation:Get*", + ], + "Resource": [ + { + "Fn::Sub": "arn:${AWS::Partition}:iam::123456789012:role/object-role" + }, + { + "NotValid": [ + "arn:${AWS::Partition}:iam::123456789012:role/object-role" + ] + }, + ], + } + ], + } + + errs = list( + self.rule.validate( + validator=validator, policy=policy, schema={}, policy_type=None + ) + ) + self.assertEqual(len(errs), 3, errs) + self.assertEqual( + errs[0].message, + "Only one of ['Principal', 'NotPrincipal'] is a required property", + ) + self.assertEqual(errs[1].message, "'NotAllow' is not one of ['Allow', 'Deny']") + self.assertListEqual(list(errs[1].path), ["Statement", 0, "Effect"]) + self.assertEqual( + errs[2].message, + "{'NotValid': ['arn:${AWS::Partition}:iam::123456789012:role/object-role']} is not of type 'string'", + ) + self.assertListEqual(list(errs[2].path), ["Statement", 0, "Resource", 1]) + + def test_string_statements(self): + """Test Positive""" + validator = CfnTemplateValidator() + + # ruff: noqa: E501 + policy = """ + { + "Version": "2012-10-18", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "cloudformation:Describe*", + "cloudformation:List*", + "cloudformation:Get*" + ], + "Resource": [ + "*", + {"Fn::Sub": ["arn:${AWS::Partition}:iam::123456789012/role/string-role"]} + ] + } + ] + } + """ + + errs = list( + self.rule.validate( + validator=validator, policy=policy, schema={}, policy_type=None + ) + ) + self.assertEqual(len(errs), 3, errs) + self.assertEqual( + errs[0].message, + "Only one of ['Principal', 'NotPrincipal'] is a required property", + ) + self.assertEqual( + errs[1].message, + "{'Fn::Sub': ['arn:${AWS::Partition}:iam::123456789012/role/string-role']} is not of type 'string'", + ) + self.assertListEqual(list(errs[1].path), ["Statement", 0, "Resource", 1]) + self.assertEqual( + errs[2].message, "'2012-10-18' is not one of ['2008-10-17', '2012-10-17']" + ) + self.assertListEqual(list(errs[2].path), ["Version"]) + + def test_principal_wildcard(self): + validator = CfnTemplateValidator({}).evolve( + context=Context(functions=FUNCTIONS) + ) + + policy = { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "*", + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:iam::123456789012:role/object-role" + }, + "Principal": "*", + }, + { + "Effect": "Allow", + "Action": "*", + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:iam::123456789012:role/object-role" + }, + "Principal": { + "AWS": "*", + }, + }, + { + "Effect": "Allow", + "Action": "*", + "Resource": { + "Fn::Sub": "arn:${AWS::Partition}:iam::123456789012:role/object-role" + }, + "Principal": {"Fn::Sub": "*"}, + }, + ], + } + + errs = list( + self.rule.validate( + validator=validator, policy=policy, schema={}, policy_type=None + ) + ) + self.assertListEqual(errs, []) + + def test_assumed_role(self): + validator = CfnTemplateValidator({}).evolve( + context=Context(functions=FUNCTIONS) + ) + + policy = { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "*", + "Resource": "arn:aws:s3:::bucket", + "Principal": { + "AWS": "arn:aws:sts::123456789012:assumed-role/rolename/rolesessionname" + }, + }, + ], + } + + errs = list( + self.rule.validate( + validator=validator, policy=policy, schema={}, policy_type=None + ) + ) + self.assertListEqual(errs, []) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/iam/test_role_arn_pattern.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/iam/test_role_arn_pattern.py new file mode 100644 index 0000000000000000000000000000000000000000..f967fe57c004dee168128e62925a70f65fe7294d --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/iam/test_role_arn_pattern.py @@ -0,0 +1,58 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import pytest + +from cfnlint.jsonschema.validators import CfnTemplateValidator +from cfnlint.rules.resources.iam.RoleArnPattern import RoleArnPattern + + +def _message_errors(name, arn, errors, **kwargs): + validator = CfnTemplateValidator().evolve(**kwargs) + + i_errors = list(RoleArnPattern().validate(validator, {}, arn, {})) + + assert len(errors) == len(i_errors), ( + f"{name}: Expected exactly {len(errors)} error, " + f"found {i_errors!r}, need {errors!r}" + ) + + err_messages = [err.message for err in i_errors] + for err in errors: + assert err in err_messages, f"{name}: expected {err} to be in {i_errors!r}" + + +@pytest.mark.parametrize( + "name,arn,errors", + [ + ( + "Invalid Arn", + "test", + [ + ( + "'test' does not match '^arn:(aws[a-zA-Z-]*)?:" + "iam::\\\\d{12}:role/[a-zA-Z_0-9+=,.@\\\\-_/]+$'" + ) + ], + ), + ( + "Valid but wrong type", + {}, + [], + ), + ( + "Valid Arn", + "arn:aws:iam::123456789012:role/test", + [], + ), + ( + "Valid Arn for aws-us-gov", + "arn:aws-us-gov:iam::123456789012:role/test", + [], + ), + ], +) +def test_iam_role_arn(name, arn, errors): + _message_errors(name, arn, errors) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_deprecated_runtime_create.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_deprecated_runtime_create.py new file mode 100644 index 0000000000000000000000000000000000000000..e197bcffea045315d711e41867ea467059a91648 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_deprecated_runtime_create.py @@ -0,0 +1,69 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from datetime import datetime + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.lmbd.DeprecatedRuntimeCreate import DeprecatedRuntimeCreate + + +@pytest.fixture(scope="module") +def rule(): + rule = DeprecatedRuntimeCreate() + yield rule + + +@pytest.mark.parametrize( + "instance,date,expected", + [ + ( + "nodejs16.x", + datetime(2023, 12, 14), + [], + ), + ( + "foo", # not existent runtime + datetime(2023, 12, 14), + [], + ), + ( + {}, # wrong type + datetime(2023, 12, 14), + [], + ), + ( + "python3.7", + datetime(2024, 1, 9), + [ + ValidationError( + ( + "Runtime 'python3.7' was deprecated on " + "'2023-12-04'. Creation was disabled on " + "'2024-01-09' and update on '2025-02-28'. " + "Please consider updating to 'python3.12'" + ), + ) + ], + ), + ( + # will be caught by the update rule + "python3.7", + datetime(2025, 2, 28), + [], + ), + ( + # will be caught by the update rule + "nodejs", + datetime(2016, 10, 31), + [], + ), + ], +) +def test_lambda_runtime(instance, date, expected, rule, validator): + rule.current_date = date + errs = list(rule.validate(validator, "LambdaRuntime", instance, {})) + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_deprecated_runtime_eol.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_deprecated_runtime_eol.py new file mode 100644 index 0000000000000000000000000000000000000000..bb9c39a48c5fab517eb631754a7ccae9f8dbe3a8 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_deprecated_runtime_eol.py @@ -0,0 +1,69 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from datetime import datetime + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.lmbd.DeprecatedRuntimeEol import DeprecatedRuntimeEol + + +@pytest.fixture(scope="module") +def rule(): + rule = DeprecatedRuntimeEol() + yield rule + + +@pytest.mark.parametrize( + "instance,date,expected", + [ + ( + "nodejs16.x", + datetime(2023, 12, 14), + [], + ), + ( + "foo", # not existent runtime + datetime(2023, 12, 14), + [], + ), + ( + {}, # wrong type + datetime(2023, 12, 14), + [], + ), + ( + "python3.7", + datetime(2023, 12, 4), + [ + ValidationError( + ( + "Runtime 'python3.7' was deprecated on " + "'2023-12-04'. Creation was disabled on " + "'2024-01-09' and update on '2025-02-28'. " + "Please consider updating to 'python3.12'" + ), + ) + ], + ), + ( + # will be caught by the create rule + "python3.7", + datetime(2023, 1, 9), + [], + ), + ( + # will be caught by the update rule + "nodejs", + datetime(2016, 10, 31), + [], + ), + ], +) +def test_lambda_runtime(instance, date, expected, rule, validator): + rule.current_date = date + errs = list(rule.validate(validator, "LambdaRuntime", instance, {})) + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_deprecated_runtime_update.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_deprecated_runtime_update.py new file mode 100644 index 0000000000000000000000000000000000000000..281d3283c75cd8222cf337ff3b5dd0558a792fff --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_deprecated_runtime_update.py @@ -0,0 +1,72 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from datetime import datetime + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.lmbd.DeprecatedRuntimeUpdate import DeprecatedRuntimeUpdate + + +@pytest.fixture(scope="module") +def rule(): + rule = DeprecatedRuntimeUpdate() + yield rule + + +@pytest.mark.parametrize( + "instance,date,expected", + [ + ( + "nodejs16.x", + datetime(2023, 12, 14), + [], + ), + ( + "foo", # not existent runtime + datetime(2023, 12, 14), + [], + ), + ( + {}, # wrong type + datetime(2023, 12, 14), + [], + ), + ( + "python3.7", + datetime(2025, 2, 28), + [ + ValidationError( + ( + "Runtime 'python3.7' was deprecated on " + "'2023-12-04'. Creation was disabled on " + "'2024-01-09' and update on '2025-02-28'. " + "Please consider updating to 'python3.12'" + ), + ) + ], + ), + ( + # will be caught by the update rule + "nodejs", + datetime(2016, 10, 31), + [ + ValidationError( + ( + "Runtime 'nodejs' was deprecated on " + "'2016-10-31'. Creation was disabled on " + "'2016-10-31' and update on '2016-10-31'. " + "Please consider updating to 'nodejs20.x'" + ), + ) + ], + ), + ], +) +def test_lambda_runtime(instance, date, expected, rule, validator): + rule.current_date = date + errs = list(rule.validate(validator, "LambdaRuntime", instance, {})) + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_event_source_mapping_event_source_arn_sqs_exclusive.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_event_source_mapping_event_source_arn_sqs_exclusive.py new file mode 100644 index 0000000000000000000000000000000000000000..650f857f0823bbbd46eacfea4b9560f0b6bcb975 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_event_source_mapping_event_source_arn_sqs_exclusive.py @@ -0,0 +1,55 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.lmbd.EventSourceMappingEventSourceArnSqsExclusive import ( + EventSourceMappingEventSourceArnSqsExclusive, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = EventSourceMappingEventSourceArnSqsExclusive() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "EventSourceArn": "arn:aws:sqs:us-east-1:123456789012:sqs-arn", + }, + [], + ), + ( + [], # wrong type + [], + ), + ( + { + "EventSourceArn": "arn:aws:sqs:us-east-1:123456789012:sqs-arn", + "StartingPosition": "1", + }, + [ + ValidationError( + "Additional properties are not allowed ('StartingPosition')", + rule=EventSourceMappingEventSourceArnSqsExclusive(), + path=deque(["StartingPosition"]), + validator=None, + schema_path=deque(["then", "properties", "StartingPosition"]), + ) + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_event_source_mapping_event_source_arn_stream_inclusive.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_event_source_mapping_event_source_arn_stream_inclusive.py new file mode 100644 index 0000000000000000000000000000000000000000..f5337820488600d36e94d96f35b07578a68ed966 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_event_source_mapping_event_source_arn_stream_inclusive.py @@ -0,0 +1,55 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.lmbd.EventSourceMappingEventSourceArnStreamInclusive import ( # noqa: E501 + EventSourceMappingEventSourceArnStreamInclusive, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = EventSourceMappingEventSourceArnStreamInclusive() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "EventSourceArn": "arn:aws:kinesis:us-east-1:123456789012:kinesis-arn", + "StartingPosition": "1", + }, + [], + ), + ( + [], # wrong type + [], + ), + ( + { + "EventSourceArn": "arn:aws:kinesis:us-east-1:123456789012:kinesis-arn", + }, + [ + ValidationError( + "'StartingPosition' is a required property", + rule=EventSourceMappingEventSourceArnStreamInclusive(), + path=deque([]), + validator="required", + schema_path=deque(["then", "required"]), + ) + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_events_log_group_name.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_events_log_group_name.py new file mode 100644 index 0000000000000000000000000000000000000000..85ee0ac7251e1c3fd0f09d828245a852287a70f6 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_events_log_group_name.py @@ -0,0 +1,30 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.unit.rules import BaseRuleTestCase + +from cfnlint.rules.resources.lmbd.EventsLogGroupName import EventsLogGroupName + + +class TestEventsLogGroupName(BaseRuleTestCase): + """Test Lambda Trigger Events CloudWatchLogs Property Configuration""" + + def setUp(self): + """Setup""" + super(TestEventsLogGroupName, self).setUp() + self.collection.register(EventsLogGroupName()) + self.success_templates = [ + "test/fixtures/templates/good/some_logs_stream_lambda.yaml" + ] + + def test_file_positive(self): + """Test Positive""" + self.helper_file_positive() + + def test_file_negative(self): + """Test failure""" + self.helper_file_negative( + "test/fixtures/templates/bad/some_logs_stream_lambda.yaml", 1 + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_function_environment_keys.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_function_environment_keys.py new file mode 100644 index 0000000000000000000000000000000000000000..bad7695b21f46343fc7ff32783d7110f1d56a98f --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_function_environment_keys.py @@ -0,0 +1,109 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.lmbd.FunctionEnvironmentKeys import FunctionEnvironmentKeys + + +@pytest.fixture(scope="module") +def rule(): + rule = FunctionEnvironmentKeys() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + {"Foo": "Bar"}, + [], + ), + ( + {"AWS_REGION": "Bar"}, + [ + ValidationError( + ( + "'AWS_REGION' is a reserved variable name, one of " + "['_HANDLER', '_X_AMZN_TRACE_ID', 'AWS_DEFAULT_REGION', " + "'AWS_REGION', 'AWS_EXECUTION_ENV', " + "'AWS_LAMBDA_FUNCTION_NAME', " + "'AWS_LAMBDA_FUNCTION_MEMORY_SIZE', " + "'AWS_LAMBDA_FUNCTION_VERSION', " + "'AWS_LAMBDA_INITIALIZATION_TYPE', " + "'AWS_LAMBDA_LOG_GROUP_NAME', " + "'AWS_LAMBDA_LOG_STREAM_NAME', " + "'AWS_ACCESS_KEY', 'AWS_ACCESS_KEY_ID', " + "'AWS_SECRET_ACCESS_KEY', " + "'AWS_SESSION_TOKEN', 'AWS_LAMBDA_RUNTIME_API', " + "'LAMBDA_TASK_ROOT', 'LAMBDA_RUNTIME_DIR']" + ), + schema_path=deque(["propertyNames", "not"]), + path=deque(["AWS_REGION"]), + rule=FunctionEnvironmentKeys(), + validator="not", + ) + ], + ), + ( + { + "Foo": "Bar", + "AWS_REGION": "Bar", + "Bar": "Foo", + "AWS_ACCESS_KEY": "Foo", + }, + [ + ValidationError( + ( + "'AWS_REGION' is a reserved variable name, one of " + "['_HANDLER', '_X_AMZN_TRACE_ID', 'AWS_DEFAULT_REGION', " + "'AWS_REGION', 'AWS_EXECUTION_ENV', " + "'AWS_LAMBDA_FUNCTION_NAME', " + "'AWS_LAMBDA_FUNCTION_MEMORY_SIZE', " + "'AWS_LAMBDA_FUNCTION_VERSION', " + "'AWS_LAMBDA_INITIALIZATION_TYPE', " + "'AWS_LAMBDA_LOG_GROUP_NAME', " + "'AWS_LAMBDA_LOG_STREAM_NAME', " + "'AWS_ACCESS_KEY', 'AWS_ACCESS_KEY_ID', " + "'AWS_SECRET_ACCESS_KEY', " + "'AWS_SESSION_TOKEN', 'AWS_LAMBDA_RUNTIME_API', " + "'LAMBDA_TASK_ROOT', 'LAMBDA_RUNTIME_DIR']" + ), + schema_path=deque(["propertyNames", "not"]), + path=deque(["AWS_REGION"]), + rule=FunctionEnvironmentKeys(), + validator="not", + ), + ValidationError( + ( + "'AWS_ACCESS_KEY' is a reserved variable name, one of " + "['_HANDLER', '_X_AMZN_TRACE_ID', 'AWS_DEFAULT_REGION', " + "'AWS_REGION', 'AWS_EXECUTION_ENV', " + "'AWS_LAMBDA_FUNCTION_NAME', " + "'AWS_LAMBDA_FUNCTION_MEMORY_SIZE', " + "'AWS_LAMBDA_FUNCTION_VERSION', " + "'AWS_LAMBDA_INITIALIZATION_TYPE', " + "'AWS_LAMBDA_LOG_GROUP_NAME', " + "'AWS_LAMBDA_LOG_STREAM_NAME', " + "'AWS_ACCESS_KEY', 'AWS_ACCESS_KEY_ID', " + "'AWS_SECRET_ACCESS_KEY', " + "'AWS_SESSION_TOKEN', 'AWS_LAMBDA_RUNTIME_API', " + "'LAMBDA_TASK_ROOT', 'LAMBDA_RUNTIME_DIR']" + ), + schema_path=deque(["propertyNames", "not"]), + path=deque(["AWS_ACCESS_KEY"]), + rule=FunctionEnvironmentKeys(), + validator="not", + ), + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "LambdaRuntime", instance, {})) + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_function_zipfile_runtime_enum.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_function_zipfile_runtime_enum.py new file mode 100644 index 0000000000000000000000000000000000000000..cb4610389d7c564d0554aba46bd2ab6ad98a767d --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_function_zipfile_runtime_enum.py @@ -0,0 +1,58 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.lmbd.FunctionZipfileRuntimeEnum import ( + FunctionZipfileRuntimeEnum, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = FunctionZipfileRuntimeEnum() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + {"Code": {"ZipFile": "foo"}, "Runtime": "python3.10"}, + [], + ), + ( + [], # wrong type + [], + ), + ( + {"Code": {"ZipFile": "foo"}, "Runtime": {"Ref": "Runtime"}}, + [], + ), + ( + {"Code": {"ZipFile": "foo"}, "Runtime": "bar"}, + [ + ValidationError( + "'bar' does not match '^(nodejs.*|python.*)$'", + rule=FunctionZipfileRuntimeEnum(), + path=deque(["Runtime"]), + validator="pattern", + schema_path=deque(["then", "properties", "Runtime", "pattern"]), + ) + ], + ), + ( + {"Code": "../link/to/my/package.zip", "Runtime": "provided.al2023"}, + [], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_function_zipfile_runtime_exists.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_function_zipfile_runtime_exists.py new file mode 100644 index 0000000000000000000000000000000000000000..c82091432da67725b9798a9a0b7946546b45e935 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_function_zipfile_runtime_exists.py @@ -0,0 +1,57 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.lmbd.FunctionZipfileRuntimeExists import ( + FunctionZipfileRuntimeExists, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = FunctionZipfileRuntimeExists() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "Code": { + "ZipFile": "foo", + }, + "Runtime": "foo", + }, + [], + ), + ( + [], # wrong type + [], + ), + ( + { + "Code": {"ZipFile": "foo"}, + }, + [ + ValidationError( + "'Runtime' is a required property", + rule=FunctionZipfileRuntimeExists(), + path=deque([]), + validator="required", + schema_path=deque(["then", "required"]), + ) + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_permission_source_account.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_permission_source_account.py new file mode 100644 index 0000000000000000000000000000000000000000..9d370bcda6c537b120acf607215227c84f244b29 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_permission_source_account.py @@ -0,0 +1,178 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.lmbd.PermissionSourceAccount import PermissionSourceAccount + + +@pytest.fixture(scope="module") +def rule(): + rule = PermissionSourceAccount() + yield rule + + +@pytest.fixture +def template(): + return { + "AWSTemplateFormatVersion": "2010-09-09", + "Conditions": { + "IsUsEast1": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]}, + }, + "Resources": { + "Bucket": {"Type": "AWS::S3::Bucket"}, + "SQS": {"Type": "AWS::SQS::Queue"}, + }, + } + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "SourceArn": "arn:aws:s3:::bucket_name", + "SourceAccount": "123456789012", + }, + [], + ), + ( + {}, + [], + ), + ( + [], + [], + ), + ( + { + "SourceArn": [], + }, + [], + ), + ( + { + "SourceArn": "arn:aws:s3:::bucket_name", + }, + [ + ValidationError( + "'SourceAccount' is a required property", + validator="required", + rule=PermissionSourceAccount(), + ) + ], + ), + ( + { + "SourceArn": "arn:aws:sqs:us-east-1:123456789012:queue", + }, + [], + ), + ( + { + "SourceArn": { + "Fn::Sub": ( + "arn:${AWS::Partition}:sqs:" + "${AWS::Region}:${AWS::AccountId}:queue" + ) + }, + }, + [], + ), + ( + { + "SourceArn": {"Fn::Sub": "arn:${AWS::Partition}:s3:::bucket"}, + }, + [], + ), + ( + { + "SourceArn": {"Fn::GetAtt": ["Bucket", "Arn"]}, + "SourceAccount": {"Ref": "AWS::AccountId"}, + }, + [], + ), + ( + { + "SourceArn": {"Fn::GetAtt": ["Bucket", "Arn"]}, + }, + [ + ValidationError( + "'SourceAccount' is a required property", + validator="required", + rule=PermissionSourceAccount(), + ) + ], + ), + ( + { + "SourceArn": {"Fn::GetAtt": ["SQS", "Arn"]}, + "SourceAccount": {"Ref": "AWS::AccountId"}, + }, + [], + ), + ( + { + "SourceArn": {"Fn::GetAtt": ["SQS", "Arn"]}, + }, + [], + ), + ( + { + "SourceArn": {"Ref": "Foo"}, + }, + [], + ), + ( + { + "SourceArn": { + "Fn::If": [ + "IsUsEast1", + {"Fn::GetAtt": ["Bucket", "Arn"]}, + {"Fn::GetAtt": ["SQS", "Arn"]}, + ] + }, + "SourceAccount": { + "Fn::If": [ + "IsUsEast1", + {"Ref": "AWS::AccountId"}, + {"Ref": "AWS::NoValue"}, + ] + }, + }, + [], + ), + ( + { + "SourceArn": { + "Fn::If": [ + "IsUsEast1", + {"Fn::GetAtt": ["Bucket", "Arn"]}, + {"Fn::GetAtt": ["SQS", "Arn"]}, + ] + }, + "SourceAccount": { + "Fn::If": [ + "IsUsEast1", + {"Ref": "AWS::NoValue"}, + {"Ref": "AWS::AccountId"}, + ] + }, + }, + [ + ValidationError( + "'SourceAccount' is a required property", + validator="required", + rule=PermissionSourceAccount(), + ) + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_snapstart.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_snapstart.py new file mode 100644 index 0000000000000000000000000000000000000000..80461d2c9ee4106713a3b8537bc27761cdeecbfe --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_snapstart.py @@ -0,0 +1,108 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.context import Context, Path +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.lmbd.SnapStart import SnapStart + + +@pytest.fixture(scope="module") +def rule(): + rule = SnapStart() + yield rule + + +@pytest.fixture +def template(): + return { + "Resources": { + "GoodSnapStart": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Code": {"S3Bucket": "XXXXXX", "S3Key": "key"}, + "Handler": "handler", + "Role": "role", + "Runtime": "runtime", + "SnapStart": {"ApplyOn": "PublishedVersions"}, + }, + }, + "GoodSnapStartVersion": { + "Type": "AWS::Lambda::Version", + "Properties": {"FunctionName": {"Ref": "GoodSnapStart"}}, + }, + "BadSnapStart": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Code": {"S3Bucket": "XXXXXX", "S3Key": "key"}, + "Handler": "handler", + "Role": "role", + "Runtime": "runtime", + "SnapStart": {"ApplyOn": "PublishedVersions"}, + }, + }, + } + } + + +@pytest.mark.parametrize( + "name,instance,path,expected", + [ + ( + "None type should result in no errors", + "None", # Not + deque(["Resources", "BadSnapStart", "Properties", "SnapStart", "ApplyOn"]), + [], + ), + ( + "Wrong type should result in no errors", + [], # wrong type + deque(["Resources", "BadSnapStart", "Properties", "SnapStart", "ApplyOn"]), + [], + ), + ( + "Correctly associated version to lambda function", + "PublishedVersions", + deque(["Resources", "GoodSnapStart", "Properties", "SnapStart", "ApplyOn"]), + [], + ), + ( + "Lambda function doesn't have version attached", + "PublishedVersions", + deque(["Resources", "BadSnapStart", "Properties", "SnapStart", "ApplyOn"]), + [ + ValidationError( + ( + "'SnapStart' is enabled but an 'AWS::Lambda::Version' " + "resource is not attached" + ), + ) + ], + ), + ], +) +def test_validate(name, instance, path, expected, rule, validator): + validator = validator.evolve( + context=Context( + path=Path( + path=path, + cfn_path=deque( + [ + "Resources", + "AWS::Lambda::Function", + "Properties", + "SnapStart", + "ApplyOn", + ] + ), + ) + ) + ) + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"{name!r}: expected {expected!r} got {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_snapstart_enabled.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_snapstart_enabled.py new file mode 100644 index 0000000000000000000000000000000000000000..e64130344a805847b201fdba4ca73660b41f2406 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_snapstart_enabled.py @@ -0,0 +1,54 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.lmbd.SnapStartEnabled import SnapStartEnabled + + +@pytest.fixture(scope="module") +def rule(): + rule = SnapStartEnabled() + yield rule + + +@pytest.mark.parametrize( + "name,instance,expected", + [ + ( + "python doesn't need SnapStart", + "python3.11", + [], + ), + ( + "wrong type", + [], + [], + ), + ( + "java 8 doesn't need SnapStart", + "java8", + [], + ), + ( + "java 17 should have SnapStart", + "java17", + [ + ValidationError( + "'java17' runtime should consider using 'SnapStart'", + path=deque(["SnapStart", "ApplyOn"]), + rule=SnapStartEnabled(), + ) + ], + ), + ], +) +def test_validate(name, instance, expected, rule): + errs = list(rule.validate(instance)) + + assert errs == expected, f"{name!r}: expected {expected!r} got {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_snapstart_supported.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_snapstart_supported.py new file mode 100644 index 0000000000000000000000000000000000000000..8adb496c4cd7640dc3896b01fc539672790f6a57 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_snapstart_supported.py @@ -0,0 +1,160 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque +from unittest import mock + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.lmbd.SnapStartSupported import SnapStartSupported + + +@pytest.fixture(scope="module") +def rule(): + rule = SnapStartSupported() + yield rule + + +@pytest.mark.parametrize( + "name,instance,regions,add_child_rule,child_rule_called,expected", + [ + ( + "SnapStart enabled on appropriate java version", + { + "Runtime": "java17", + "SnapStart": { + "ApplyOn": "PublishedVersions", + }, + }, + ["us-east-1"], + True, + False, + [], + ), + ( + "SnapStart enabled with ref for runtime", + { + "Runtime": {"Ref": "Runtime"}, + "SnapStart": { + "ApplyOn": "PublishedVersions", + }, + }, + ["us-east-1"], + True, + False, + [], + ), + ( + "SnapStart not enabled in region that doesn't support it", + { + "Runtime": "java17", + "SnapStart": { + "ApplyOn": "PublishedVersions", + }, + }, + ["us-east-1", "foo-bar-1"], + True, + False, + [ + ValidationError( + "'SnapStart' enabled functions are not supported in ['foo-bar-1']", + path=deque(["SnapStart", "ApplyOn"]), + ) + ], + ), + ( + "SnapStart not enabled on non java runtime", + { + "Runtime": "python3.11", + }, + ["us-east-1"], + True, + True, + [], + ), + ( + "SnapStart not enabled on java runtime in a bad region", + { + "Runtime": "python3.11", + }, + ["foo-bar-1"], + True, + False, + [], + ), + ( + "SnapStart not enabled and no child rule", + { + "Runtime": "java17", + }, + ["us-east-1"], + False, + False, + [], + ), + ( + "SnapStart set off with Python runtime", + { + "Runtime": "python3.11", + "SnapStart": { + "ApplyOn": "None", + }, + }, + ["us-east-1"], + True, + False, + [], + ), + ( + "Snapstart should not be enabled for non java runtime", + { + "Runtime": "python3.11", + "SnapStart": { + "ApplyOn": "PublishedVersions", + }, + }, + ["us-east-1"], + True, + False, + [ + ValidationError( + "'python3.11' is not supported for 'SnapStart' enabled functions", + path=deque(["SnapStart", "ApplyOn"]), + ) + ], + ), + ], +) +def test_validate( + name, + instance, + regions, + add_child_rule, + child_rule_called, + expected, + rule, + validator, +): + validator = validator.evolve( + context=validator.context.evolve(regions=regions), + ) + + child_rule = mock.MagicMock() + if add_child_rule: + rule.child_rules["I2530"] = child_rule + else: + rule.child_rules["I2530"] = None + + errs = list(rule.validate(validator, "", instance, {})) + + if child_rule_called: + child_rule.validate.assert_called_with( + instance.get("Runtime") + ), f"{name!r}: child rule not called" + else: + child_rule.validate.assert_not_called(), f"{name!r}: child rule called" + + assert errs == expected, f"{name!r}: expected {expected!r} got {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_zip_package_required_properties.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_zip_package_required_properties.py new file mode 100644 index 0000000000000000000000000000000000000000..d5a5c2ac39f36e486e5e43998fdc9b98cbc4ff81 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/lmbd/test_zip_package_required_properties.py @@ -0,0 +1,30 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.unit.rules import BaseRuleTestCase + +from cfnlint.rules.resources.lmbd.ZipPackageRequiredProperties import ( + ZipPackageRequiredProperties, +) + + +class TestZipPackageRequiredProperties(BaseRuleTestCase): + """Test required properties""" + + def setUp(self): + super(TestZipPackageRequiredProperties, self).setUp() + self.collection.register(ZipPackageRequiredProperties()) + self.success_templates = [ + "test/fixtures/templates/good/resources/lambda/required_properties.yaml" + ] + + def test_file_positive(self): + self.helper_file_positive() + + def test_file_negative(self): + self.helper_file_negative( + "test/fixtures/templates/bad/resources/lambda/required_properties.yaml", + err_count=3, + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_availability_zone.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_availability_zone.py new file mode 100644 index 0000000000000000000000000000000000000000..224ec2279c4ef3a4b6c1d64a07ba86388f729e22 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_availability_zone.py @@ -0,0 +1,170 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.context import Path, create_context_for_template +from cfnlint.helpers import FUNCTIONS +from cfnlint.jsonschema import CfnTemplateValidator, ValidationError +from cfnlint.rules.resources.properties.AvailabilityZone import ( + AvailabilityZone, # pylint: disable=E0401 +) +from cfnlint.template import Template + + +@pytest.fixture(scope="module") +def rule(): + rule = AvailabilityZone() + yield rule + + +@pytest.fixture +def template(): + return { + "Resources": { + "MySqs": { + "Type": "AWS::SQS::Queue", + } + } + } + + +@pytest.fixture(scope="module") +def validator_cdk(): + cfn = Template( + "", + { + "Resources": { + "MySqs": { + "Type": "AWS::SQS::Queue", + }, + "CDK": { + "Type": "AWS::CDK::Metadata", + }, + } + }, + ) + context = ( + create_context_for_template(cfn) + .evolve( + functions=FUNCTIONS, + path="Resources", + ) + .evolve(path="MySqs") + .evolve(path="Properties") + ) + yield CfnTemplateValidator(schema={}, context=context, cfn=cfn) + + +@pytest.mark.parametrize( + "name,instance,path,expected", + [ + ( + "Valid ref", + {"Ref": "AZ"}, + { + "path": deque(["Resources", "MySqs", "Properties"]), + }, + [], + ), + ( + "Valid list ref", + [{"Ref": "AZ"}], + { + "path": deque(["Resources", "MySqs", "Properties"]), + }, + [], + ), + ( + "Valid inside Ref", + "us-east-1a", + {"path": deque(["Ref"])}, + [], + ), + ( + "Valid GetAZs", + ["us-east-1a", "us-east-1b"], + {"path": deque(["Fn::GetAZs"])}, + [], + ), + ( + "Invalid type", + True, + { + "path": deque(["Resources", "MySqs", "Properties"]), + }, + [], + ), + ( + "Valid hardcoded all string", + "all", + { + "path": deque(["Resources", "MySqs", "Properties"]), + }, + [], + ), + ( + "Invalid hardcoded string", + "us-east-1a", + { + "path": deque(["Resources", "MySqs", "Properties"]), + }, + [ + ValidationError( + ("Avoid hardcoding availability zones 'us-east-1a'"), + rule=AvailabilityZone(), + ) + ], + ), + ( + "Invalid hardcoded array", + ["us-east-1a", "us-east-1b"], + { + "path": deque(["Resources", "MySqs", "Properties"]), + }, + [ + ValidationError( + ("Avoid hardcoding availability zones 'us-east-1a'"), + rule=AvailabilityZone(), + ), + ValidationError( + ("Avoid hardcoding availability zones 'us-east-1b'"), + rule=AvailabilityZone(), + ), + ], + ), + ], + indirect=["path"], +) +def test_validate(name, instance, path, expected, rule, validator): + errors = list(rule.validate(validator, False, instance, {})) + # we use error counts in this one as the instance types are + # always changing so we aren't going to hold ourselves up by that + assert errors == expected, f"Test {name!r} got {errors!r}" + + +@pytest.mark.parametrize( + "name,instance,path,expected", + [ + ( + "Valid hardcoded string because CDK", + "us-east-1a", + deque(["Resources", "MySqs", "Properties"]), + [], + ), + ], +) +def test_validate_for_cdk(name, instance, path, expected, rule, validator_cdk): + validator = validator_cdk.evolve( + context=validator_cdk.context.evolve( + path=Path(path=path), + ) + ) + errors = list(rule.validate(validator, False, instance, {})) + # we use error counts in this one as the instance types are + # always changing so we aren't going to hold ourselves up by that + assert errors == expected, f"Test {name!r} got {errors!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_availability_zone_cdk.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_availability_zone_cdk.py new file mode 100644 index 0000000000000000000000000000000000000000..1aed58e7ceb13fd75c56a277c97e9196a65e4efd --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_availability_zone_cdk.py @@ -0,0 +1,53 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.rules.resources.properties.AvailabilityZone import ( + AvailabilityZone, # pylint: disable=E0401 +) + + +@pytest.fixture(scope="module") +def rule(): + rule = AvailabilityZone() + yield rule + + +@pytest.fixture +def template(): + return { + "Resources": { + "MySqs": { + "Type": "AWS::SQS::Queue", + }, + "CDK": { + "Type": "AWS::CDK::Metadata", + }, + } + } + + +@pytest.mark.parametrize( + "name,instance,path,expected", + [ + ( + "Valid hardcoded string because CDK", + "us-east-1a", + { + "path": deque(["Resources", "MySqs", "Properties"]), + }, + [], + ), + ], + indirect=["path"], +) +def test_validate(name, instance, path, expected, rule, validator): + errors = list(rule.validate(validator, False, instance, {})) + # we use error counts in this one as the instance types are + # always changing so we aren't going to hold ourselves up by that + assert errors == expected, f"Test {name!r} got {errors!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_enum.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_enum.py new file mode 100644 index 0000000000000000000000000000000000000000..f423c3a60c4a07ca3be4cb03140730a23508c7ac --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_enum.py @@ -0,0 +1,145 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.parameters.Enum import Enum as ParameterEnum +from cfnlint.rules.resources.properties.Enum import Enum + + +@pytest.fixture +def rule(): + rule = Enum() + rule.child_rules["W2030"] = ParameterEnum() + yield Enum() + + +@pytest.fixture +def template(): + return { + "Parameters": { + "MyString": { + "Type": "String", + "Default": "a", + "AllowedValues": ["a", "b"], + }, + }, + "Resources": {}, + } + + +@pytest.mark.parametrize( + "name,instance,enums,path,expected", + [ + ( + "Validate the standard enum", + "a", + ["a"], + {}, + [], + ), + ( + "Validate the standard enum", + "a", + ["a"], + {"value_path": ["Parameters", "MyString", "AllowedValues", 0]}, + [], + ), + ( + "Invalid with the standard enum", + "a", + ["b"], + {}, + [ + ValidationError( + ("'a' is not one of ['b']"), + path=deque([]), + schema_path=deque([]), + path_override=deque([]), + ), + ], + ), + ( + "Invalid with the standard enum from parameter", + "a", + ["b"], + {"value_path": ["Parameters", "MyString", "AllowedValues", 0]}, + [ + ValidationError( + ("'a' is not one of ['b']"), + path=deque([]), + schema_path=deque([]), + rule=ParameterEnum(), + path_override=deque(["Parameters", "MyString", "AllowedValues", 0]), + ), + ], + ), + ], + indirect=["path"], +) +def test_validate_enum(name, instance, enums, expected, rule, validator): + errs = list(rule.enum(validator, enums, instance, {})) + + assert errs == expected, f"Test {name!r} got {errs!r}" + + +@pytest.mark.parametrize( + "name,instance,enums,path,expected", + [ + ( + "Validate the standard enum", + "a", + ["A"], + {}, + [], + ), + ( + "Validate the standard enum", + "a", + ["A"], + {"value_path": ["Parameters", "MyString", "AllowedValues", 0]}, + [], + ), + ( + "Invalid with the standard enum", + "a", + ["B"], + {}, + [ + ValidationError( + ("'a' is not one of ['b'] (case-insensitive)"), + path=deque([]), + schema_path=deque([]), + path_override=deque([]), + ), + ], + ), + ( + "Invalid with the standard enum from parameter", + "a", + ["B"], + {"value_path": ["Parameters", "MyString", "AllowedValues", 0]}, + [ + ValidationError( + ("'a' is not one of ['b'] (case-insensitive)"), + path=deque([]), + schema_path=deque([]), + rule=ParameterEnum(), + path_override=deque(["Parameters", "MyString", "AllowedValues", 0]), + ), + ], + ), + ], + indirect=["path"], +) +def test_validate_enum_case_insensitive( + name, instance, enums, expected, rule, validator +): + errs = list(rule.enumCaseInsensitive(validator, enums, instance, {})) + + assert errs == expected, f"Test {name!r} got {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_image_id.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_image_id.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fbb2385bc054dc4edd78d81346d8784353b994 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_image_id.py @@ -0,0 +1,69 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.properties.ImageId import ImageId + + +@pytest.fixture(scope="module") +def rule(): + rule = ImageId() + yield rule + + +@pytest.fixture +def template(): + return { + "Parameters": { + "MyImageId": { + "Type": "AWS::EC2::Image::Id", + }, + "MyString": { + "Type": "String", + }, + }, + "Resources": {}, + } + + +@pytest.mark.parametrize( + "name,instance,expected", + [ + ( + "Valid Ref to a paraemter", + {"Ref": "MyImageId"}, + [], + ), + ( + "Valid Ref to a Pseudo-Parameter", + {"Ref": "AWS::Region"}, + [], + ), + ( + "Invalid Ref to a parameter of the wrong type", + {"Ref": "MyString"}, + [ + ValidationError( + ( + "'String' is not one of ['AWS::EC2::Image::Id'" + ", 'AWS::SSM::Parameter::Value']" + ), + path=deque([]), + schema_path=deque(["enum"]), + validator="enum", + rule=ImageId(), + path_override=deque(["Parameters", "MyString", "Type"]), + ), + ], + ), + ], +) +def test_validate(name, instance, expected, rule, validator): + errs = list(rule.validate(validator, {}, instance, {})) + assert errs == expected, f"Test {name!r} got {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_number_range.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_number_range.py new file mode 100644 index 0000000000000000000000000000000000000000..9fd14fe613382776bfebdaaff0022972ec6616a2 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_number_range.py @@ -0,0 +1,103 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.context import Path +from cfnlint.rules.parameters.NumberRange import NumberRange as ParamaterNumberRange +from cfnlint.rules.resources.properties.NumberRange import NumberRange + + +@pytest.fixture +def rule(): + rule = NumberRange() + rule.child_rules["W3034"] = ParamaterNumberRange() + yield NumberRange() + + +def test_minimum(rule, validator): + assert len(list(rule.minimum(validator, 1, 1, {}))) == 0 + assert len(list(rule.minimum(validator, 1, 0, {}))) == 1 + + evolved = validator.evolve( + context=validator.context.evolve( + path=Path( + path=deque(["Ref"]), + value_path=deque(["Parameters", "MyParameter", "MinValue"]), + ) + ) + ) + errs = list(rule.minimum(evolved, 1, 0, {})) + assert len(errs) == 1 + assert errs[0].rule.id == ParamaterNumberRange.id + + rule.child_rules["W3034"] = None + errs = list(rule.minimum(evolved, 1, 0, {})) + assert len(errs) == 0 + + +def test_maximum(rule, validator): + assert len(list(rule.maximum(validator, 1, 1, {}))) == 0 + assert len(list(rule.maximum(validator, 1, 2, {}))) == 1 + + evolved = validator.evolve( + context=validator.context.evolve( + path=Path( + path=deque(["Ref"]), + value_path=deque(["Parameters", "MyParameter", "MinValue"]), + ), + ) + ) + errs = list(rule.maximum(evolved, 1, 2, {})) + assert len(errs) == 1 + assert errs[0].rule.id == ParamaterNumberRange.id + + rule.child_rules["W3034"] = None + errs = list(rule.maximum(evolved, 1, 2, {})) + assert len(errs) == 0 + + +def test_exclusive_minimum(rule, validator): + assert len(list(rule.exclusiveMinimum(validator, 1, 2, {}))) == 0 + assert len(list(rule.exclusiveMinimum(validator, 1, 1, {}))) == 1 + + evolved = validator.evolve( + context=validator.context.evolve( + path=Path( + path=deque(["Ref"]), + value_path=deque(["Parameters", "MyParameter", "MinValue"]), + ), + ) + ) + errs = list(rule.exclusiveMinimum(evolved, 1, 1, {})) + assert len(errs) == 1 + assert errs[0].rule.id == ParamaterNumberRange.id + + rule.child_rules["W3034"] = None + errs = list(rule.exclusiveMinimum(evolved, 1, 1, {})) + assert len(errs) == 0 + + +def test_exlusive_maximum(rule, validator): + assert len(list(rule.exclusiveMaximum(validator, 1, 0, {}))) == 0 + assert len(list(rule.exclusiveMaximum(validator, 1, 1, {}))) == 1 + + evolved = validator.evolve( + context=validator.context.evolve( + path=Path( + path=deque(["Ref"]), + value_path=deque(["Parameters", "MyParameter", "MinValue"]), + ), + ) + ) + errs = list(rule.exclusiveMaximum(evolved, 1, 1, {})) + assert len(errs) == 1 + assert errs[0].rule.id == ParamaterNumberRange.id + + rule.child_rules["W3034"] = None + errs = list(rule.exclusiveMaximum(evolved, 1, 1, {})) + assert len(errs) == 0 diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_onlyone.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_onlyone.py new file mode 100644 index 0000000000000000000000000000000000000000..fade8aa202756737074d87ab444b63dd396c8131 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_onlyone.py @@ -0,0 +1,10 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.unit.rules import BaseRuleTestCase + + +class TestPropertyOnlyOne(BaseRuleTestCase): + """Test OnlyOne Property Configuration""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_password.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_password.py new file mode 100644 index 0000000000000000000000000000000000000000..5cb3353e9fca75953086a38799221165e9e365ac --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_password.py @@ -0,0 +1,32 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.unit.rules import BaseRuleTestCase + +from cfnlint.rules.resources.properties.Password import ( + Password, # pylint: disable=E0401 +) + + +class TestPropertyPassword(BaseRuleTestCase): + """Test Password Property Configuration""" + + def setUp(self): + """Setup""" + super(TestPropertyPassword, self).setUp() + self.collection.register(Password()) + self.success_templates = [ + "test/fixtures/templates/good/resources/properties/password.yaml" + ] + + def test_file_positive(self): + """Test Positive""" + self.helper_file_positive() + + def test_file_negative(self): + """Test failure""" + self.helper_file_negative( + "test/fixtures/templates/bad/properties_password.yaml", 3 + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_pattern.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_pattern.py new file mode 100644 index 0000000000000000000000000000000000000000..12620ca76ea3a32e8c6704e24010156d70bea287 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_pattern.py @@ -0,0 +1,55 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.context import Path +from cfnlint.rules.parameters.ValuePattern import ValuePattern as ParameterPattern +from cfnlint.rules.resources.properties.Pattern import Pattern + + +@pytest.fixture(scope="module") +def rule(): + rule = Pattern() + rule.child_rules["W2031"] = ParameterPattern() + yield rule + + +def test_validate(rule, validator): + assert len(list(rule.pattern(validator, ".*", "foo", {}))) == 0 + assert len(list(rule.pattern(validator, "foo", "bar", {}))) == 1 + + evolved = validator.evolve( + context=validator.context.evolve( + path=Path(path=deque(["Fn::Sub"])), + ) + ) + errs = list(rule.pattern(evolved, "bar", "bar", {})) + assert len(errs) == 0 + + evolved = validator.evolve( + context=validator.context.evolve( + path=Path( + path=deque(["Ref"]), + value_path=deque(["Parameters", "MyParameter", "Default"]), + ), + ) + ) + errs = list(rule.pattern(evolved, "foo", "bar", {})) + assert len(errs) == 1 + assert errs[0].rule.id == ParameterPattern.id + + rule.child_rules["W2031"] = None + errs = list(rule.pattern(evolved, "foo", "bar", {})) + assert len(errs) == 0 + + +def test_pattern_exceptions(rule, validator): + rule.configure({"exceptions": ["AWS::"]}) + + assert len(list(rule.pattern(validator, "foo", "Another AWS::Instance", {}))) == 1 + assert len(list(rule.pattern(validator, "foo", "AWS::Dummy::Resource", {}))) == 0 diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_pattern_ssm.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_pattern_ssm.py new file mode 100644 index 0000000000000000000000000000000000000000..6836cc18a4ed487fd7fac3675b75ed51fb335d4c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_pattern_ssm.py @@ -0,0 +1,70 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.parameters.ValuePattern import ValuePattern as ParameterPattern +from cfnlint.rules.resources.properties.Pattern import Pattern + + +@pytest.fixture(scope="module") +def rule(): + rule = Pattern() + rule.child_rules["W2031"] = ParameterPattern() + yield rule + + +@pytest.fixture +def template(): + return { + "Transform": ["AWS::Serverless-2016-10-31"], + "Parameters": { + "SSMParameter": { + "Type": "AWS::SSM::Parameter::Value", + "Default": "foo", + }, + "Parameter": { + "Type": "String", + "Default": "bar", + }, + }, + } + + +@pytest.mark.parametrize( + "name,instance,pattern,expected", + [ + ( + "Valid because SSM parameter default value", + "foo", + "bar", + [], + ), + ( + "Invalid because not the SSM parameter", + "bar", + "foo", + [ + ValidationError( + message="'bar' does not match 'foo'", + ) + ], + ), + ( + "Invalid an unrelated to the parameters", + "foobar", + "foofoo", + [ + ValidationError( + message="'foobar' does not match 'foofoo'", + ) + ], + ), + ], +) +def test_validate(name, instance, pattern, expected, rule, validator): + errs = list(rule.pattern(validator, pattern, instance, {})) + assert errs == expected, f"{name} got errors {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_properties.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_properties.py new file mode 100644 index 0000000000000000000000000000000000000000..bffae12066b2acc18a2261764d37779ff6e3ac4c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_properties.py @@ -0,0 +1,89 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque +from unittest.mock import MagicMock, patch + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.properties.Properties import Properties +from cfnlint.schema._schema import Schema + + +@pytest.fixture(scope="module") +def rule(): + rule = Properties() + yield rule + + +@pytest.mark.parametrize( + "name,instance,patches,expected", + [ + ( + "Valid results", + { + "Type": "MyType", + }, + [(["us-east-1"], Schema({"typeName": "MyType", "properties": {}}))], + [], + ), + ( + "Invalid type for Type", + { + "Type": {}, + }, + [], + [], + ), + ( + "Valid type but no required fields", + { + "Type": "MyType", + }, + [(["us-east-1"], Schema({"typeName": "MyType", "required": ["Name"]}))], + [ + ValidationError( + "'Name' is a required property", + validator="required", + path=deque(["Properties"]), + schema_path=deque(["required"]), + ) + ], + ), + ( + "Invalid with Ref AWS::NoValue", + {"Type": "MyType", "Properties": {"Ref": "AWS::NoValue"}}, + [], + [ + ValidationError( + "{'Ref': 'AWS::NoValue'} is not of type object", + validator="type", + path=deque(["Properties", "Ref"]), + rule=None, + ) + ], + ), + ], +) +def test_validate(name, instance, patches, expected, rule, validator): + schema_manager = MagicMock() + schema_manager.get_resource_schemas_by_regions.return_value = patches + + with patch( + "cfnlint.rules.resources.properties.Properties.PROVIDER_SCHEMA_MANAGER", + schema_manager, + ): + errs = list(rule.validate(validator, {}, instance, {})) + + assert errs == expected, f"Test {name!r} got {errs!r}" + + if patches: + schema_manager.get_resource_schemas_by_regions.assert_called_once() + schema_manager.get_resource_schemas_by_regions.assert_called_with( + instance.get("Type"), ["us-east-1"] + ) + else: + schema_manager.get_resource_schemas_by_regions.assert_not_called() diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_properties_templated.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_properties_templated.py new file mode 100644 index 0000000000000000000000000000000000000000..2e95748deab07c8d2c6210c18f20a4722d06344b --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_properties_templated.py @@ -0,0 +1,66 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.context import Path +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.properties.PropertiesTemplated import PropertiesTemplated +from cfnlint.template import Template + + +@pytest.fixture(scope="module") +def rule(): + rule = PropertiesTemplated() + yield rule + + +@pytest.fixture +def path(): + return Path( + path=deque(["Resources/AWS::CloudFormation::Template/Properties/TemplateURL"]) + ) + + +@pytest.mark.parametrize( + "name,instance,transforms,expected", + [ + ( + "A s3 string should be fine", + "s3://my-bucket/key/value.yaml", + [], + [], + ), + ( + "An object isn't a string so we skip", + {"foo": "bar"}, + [], + [], + ), + ( + "A transform will result in non failure", + "./folder", + "AWS::Serverless-2016-10-31", + [], + ), + ( + "String with no transform", + "./folder", + [], + [ + ValidationError( + ("This code may only work with 'package' cli command"), + ) + ], + ), + ], +) +def test_validate(name, instance, transforms, expected, rule, validator): + validator = validator.evolve(cfn=Template("", {"Transform": transforms})) + + errs = list(rule.validate(validator, {}, instance, {})) + assert errs == expected, f"Test {name!r} got {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_read_only.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_read_only.py new file mode 100644 index 0000000000000000000000000000000000000000..e3497d3c96a0f9c3baf89824cf56aa5217b3d525 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_read_only.py @@ -0,0 +1,90 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque +from unittest import mock + +import pytest + +from cfnlint.context import Path +from cfnlint.jsonschema import CfnTemplateValidator, ValidationError +from cfnlint.rules.resources.properties.ReadOnly import ReadOnly +from cfnlint.schema.resolver import RefResolutionError + + +@pytest.fixture(scope="module") +def rule(): + yield ReadOnly() + + +@pytest.fixture(scope="module") +def validator(): + yield CfnTemplateValidator( + schema={ + "properties": {"Id": {"type": "string"}}, + "type": "object", + "readOnlyProperties": ["/properties/Id"], + "typeName": "Test", + } + ) + + +@pytest.mark.parametrize( + "name,path,side_effect,expected", + [ + ( + "Not using read only property", + deque(["Resources", "Test", "Properties", "Name"]), + None, + [], + ), + ( + "Not in outputs", + deque(["Outputs"]), + None, + [], + ), + ( + "Not in resource properties", + deque(["Resources"]), + None, + [], + ), + ( + "Not in resource properties", + deque(["Resources", "*", "Metadata"]), + None, + [], + ), + ( + "Setting a read only property", + deque(["Resources", "Test", "Properties", "Id"]), + None, + [ValidationError("Read only properties are not allowed ('Id')")], + ), + ( + "No readonlyProperties in schema", + deque(["Resources", "Test", "Properties", "Id"]), + RefResolutionError("not found"), + [], + ), + ], +) +def test_validate(name, path, side_effect, expected, rule, validator): + validator = validator.evolve( + context=validator.context.evolve( + path=Path( + cfn_path=path, + ) + ), + ) + + if side_effect: + validator.resolver = mock.MagicMock() + validator.resolver.resolve_from_url.side_effect = side_effect + + errs = list(rule.validate(validator, "", "", {})) + + assert errs == expected, f"{name} got errors {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_required.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_required.py new file mode 100644 index 0000000000000000000000000000000000000000..e20a94be5752a0b9b7a30dd103a3d2d93f3e642b --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_required.py @@ -0,0 +1,10 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.unit.rules import BaseRuleTestCase + + +class TestResourceConfiguration(BaseRuleTestCase): + """Test Resource Properties""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_string_length.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_string_length.py new file mode 100644 index 0000000000000000000000000000000000000000..77a3e55aab72e78e9f18092221158795acbf020d --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_string_length.py @@ -0,0 +1,83 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import datetime + +import pytest + +from cfnlint.rules.resources.properties.StringLength import StringLength + + +@pytest.fixture(scope="module") +def rule(): + yield StringLength() + + +@pytest.mark.parametrize( + "instance,mL,schema,expected", + [ + ("foo", 2, {}, 0), + ("foo", 4, {}, 1), + ({"Fn::Sub": "foo"}, 2, {}, 0), + ({"Fn::Sub": "foo"}, 4, {}, 1), + ({"Fn::Sub": ["foo", {}]}, 2, {}, 0), + ({"Fn::Sub": ["foo", {}]}, 4, {}, 1), + ({"Fn::Sub": ["foo", {}, {}]}, 2, {}, 0), + ({"foo": "bar"}, 10, {"type": "object"}, 0), + ({"foo": "bar"}, 20, {"type": "object"}, 1), + ({"foo": datetime.datetime.now()}, 10, {"type": "object"}, 0), + ({"foo": datetime.datetime.now()}, 40, {"type": "object"}, 1), + ({"foo": ["bar"]}, 10, {"type": "object"}, 0), + ({"foo": ["bar"]}, 20, {"type": "object"}, 1), + ({"foo": 1, "bar": {"Ref": "Parameter"}}, 10, {"type": "object"}, 0), + ({"foo": 1, "bar": {"Ref": "Parameter"}}, 20, {"type": "object"}, 1), + ({"foo": 1, "bar": {"Fn::Sub": "2"}}, 10, {"type": "object"}, 0), + ({"foo": 1, "bar": {"Fn::Sub": "2"}}, 20, {"type": "object"}, 1), + ({"foo": 1, "bar": {"Fn::Sub": ["2", {}]}}, 10, {"type": "object"}, 0), + ({"foo": 1, "bar": {"Fn::Sub": ["2", {}]}}, 20, {"type": "object"}, 1), + ( + {"foo": 1, "bar": {"Fn::Sub": ["2", {}]}}, + 20, + {"type": ["string", "object"]}, + 1, + ), + ], +) +def test_min_length(instance, mL, expected, rule, schema, validator): + assert len(list(rule.minLength(validator, mL, instance, schema))) == expected + + +@pytest.mark.parametrize( + "instance,mL,schema,expected", + [ + ("foo", 4, {}, 0), + ("foo", 2, {}, 1), + ({"Fn::Sub": "foo"}, 4, {}, 0), + ({"Fn::Sub": "foo"}, 2, {}, 1), + ({"Fn::Sub": ["foo", {}]}, 4, {}, 0), + ({"Fn::Sub": ["foo", {}]}, 2, {}, 1), + ({"Fn::Sub": ["foo", {}, {}]}, 2, {}, 0), + ({"foo": "bar"}, 20, {"type": "object"}, 0), + ({"foo": "bar"}, 2, {"type": "object"}, 1), + ({"foo": datetime.datetime.now()}, 40, {"type": "object"}, 0), + ({"foo": datetime.datetime.now()}, 2, {"type": "object"}, 1), + ({"foo": ["bar"]}, 20, {"type": "object"}, 0), + ({"foo": ["bar"]}, 2, {"type": "object"}, 1), + ({"foo": 1, "bar": {"Ref": "Parameter"}}, 20, {"type": "object"}, 0), + ({"foo": 1, "bar": {"Ref": "Parameter"}}, 4, {"type": "object"}, 1), + ({"foo": 1, "bar": {"Fn::Sub": "2"}}, 20, {"type": "object"}, 0), + ({"foo": 1, "bar": {"Fn::Sub": "2"}}, 4, {"type": "object"}, 1), + ({"foo": 1, "bar": {"Fn::Sub": ["2", {}]}}, 20, {"type": "object"}, 0), + ({"foo": 1, "bar": {"Fn::Sub": ["2", {}]}}, 4, {"type": "object"}, 1), + ( + {"foo": 1, "bar": {"Fn::Sub": ["2", {}]}}, + 4, + {"type": ["string", "object"]}, + 1, + ), + ], +) +def test_max_length(instance, mL, expected, rule, schema, validator): + assert len(list(rule.maxLength(validator, mL, instance, schema))) == expected diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_tagging.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_tagging.py new file mode 100644 index 0000000000000000000000000000000000000000..73acaad2486ec69208f38f77aca8255c5cc13a7f --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_tagging.py @@ -0,0 +1,143 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.properties.Tagging import Tagging + + +@pytest.fixture(scope="module") +def rule(): + rule = Tagging() + yield rule + + +@pytest.mark.parametrize( + "name,instance,schema,expected", + [ + ( + "Valid tag by array", + {"Tags": [{"Key": "Foo", "Value": "Bar"}]}, + {"taggable": True}, + [], + ), + ( + "Valid tag by key/value", + {"Tags": {"Foo": "Bar"}}, + {"taggable": True}, + [], + ), + ( + "Duplicate key", + {"Tags": [{"Key": "Foo", "Value": "Bar"}, {"Key": "Foo", "Value": "Bar"}]}, + {"taggable": True}, + [ + ValidationError( + ( + "[{'Key': 'Foo', 'Value': 'Bar'}, " + "{'Key': 'Foo', 'Value': 'Bar'}] " + "has non-unique elements for keys ['Key']" + ), + path=deque(["Tags"]), + schema_path=deque(["properties", "Tags", "uniqueKeys"]), + validator="tagging", + ) + ], + ), + ( + "Value is too long", + { + "Tags": [ + {"Key": "Foo", "Value": "a" * 257}, + ] + }, + {"taggable": True}, + [ + ValidationError( + f"{'a'*257!r} is longer than 256", + path=deque(["Tags", 0, "Value"]), + schema_path=deque( + [ + "properties", + "Tags", + "items", + "properties", + "Value", + "maxLength", + ] + ), + validator="tagging", + ), + ], + ), + ( + "Value is too long in object", + { + "Tags": {"Foo": "a" * 257}, + }, + {"taggable": True}, + [ + ValidationError( + f"{'a'*257!r} is longer than 256", + path=deque(["Tags", "Foo"]), + schema_path=deque( + [ + "properties", + "Tags", + "patternProperties", + "^(?!aws:).+$", + "maxLength", + ] + ), + validator="tagging", + ), + ], + ), + ( + "AWS key name in array", + { + "Tags": [ + {"Key": "aws:Foo", "Value": "Bar"}, + ], + }, + {"taggable": True}, + [ + ValidationError( + ("'aws:Foo' does not match " "'^(?!aws:).+$'"), + path=deque(["Tags", 0, "Key"]), + schema_path=deque( + ["properties", "Tags", "items", "properties", "Key", "pattern"] + ), + validator="tagging", + ), + ], + ), + ( + "AWS key name in object", + { + "Tags": {"aws:Foo": "Bar"}, + }, + {"taggable": True}, + [ + ValidationError( + ( + "'aws:Foo' does not match any of " + "the regexes: " + "'^(?!aws:).+$'" + ), + path=deque(["Tags", "aws:Foo"]), + schema_path=deque(["properties", "Tags", "additionalProperties"]), + validator="tagging", + ), + ], + ), + ], +) +def test_validate(name, instance, schema, expected, rule, validator): + errs = list(rule.tagging(validator, schema, instance, {})) + assert errs == expected, f"Test {name!r} got {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_unique_items.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_unique_items.py new file mode 100644 index 0000000000000000000000000000000000000000..2417b3eb662e42a8c9880ed3750437b7bd02acd3 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_unique_items.py @@ -0,0 +1,35 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import pytest + +from cfnlint.rules.resources.properties.UniqueItems import UniqueItems +from cfnlint.rules.resources.properties.UniqueItemsAllowed import UniqueItemsAllowed + + +@pytest.fixture(scope="module") +def rule(): + rule = UniqueItems() + rule.child_rules["I3037"] = UniqueItemsAllowed() + yield rule + + +@pytest.mark.parametrize( + "instance,uI,schema,expected", + [ + (["foo", "bar"], True, {}, None), + (["foo", "bar"], False, {}, None), + (["foo", "foo"], False, {}, "I3037"), + (["foo", "foo"], True, {}, "E3037"), + ], +) +def test_unique_items_fails(instance, uI, expected, rule, schema, validator): + errs = list(rule.uniqueItems(validator, uI, instance, schema)) + if expected is None: + assert not errs + else: + assert len(errs) == 1 + if expected != "E3037": + assert errs[0].rule.id == expected diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_value_primitive_type.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_value_primitive_type.py new file mode 100644 index 0000000000000000000000000000000000000000..48624206c5033155f328f314a540632c8a8ec9b1 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/properties/test_value_primitive_type.py @@ -0,0 +1,69 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.unit.rules import BaseRuleTestCase + +from cfnlint.jsonschema import CfnTemplateValidator + +# ruff: noqa: E501 +from cfnlint.rules.resources.properties.Type import Type + + +class TestType(BaseRuleTestCase): + """Test Primitive Value Types for Json Schema non strict""" + + def setUp(self): + """Setup""" + self.rule = Type() + self.rule.config["strict"] = False + self.validator = CfnTemplateValidator() + + def check_args(self, types, instance, extra_args): + errs = list(self.rule.type(self.validator, types, instance, {})) + self.assertEqual(len(errs), 1) + self.assertDictEqual( + errs[0].extra_args, + extra_args, + ) + + def test_validation_non_strict(self): + self.rule.config["strict"] = False + # sub is a string boolean + self.check_args( + types="integer", + instance="A", + extra_args={ + "actual_type": "string", + "expected_type": "integer", + }, + ) + self.check_args( + types=["number", "integer"], + instance="A", + extra_args={ + "actual_type": "string", + "expected_type": "number", + }, + ) + + def test_validation_strict(self): + self.rule.config["strict"] = True + # sub is a string boolean + self.check_args( + types="integer", + instance="1", + extra_args={ + "actual_type": "string", + "expected_type": "integer", + }, + ) + self.check_args( + types=["string", "boolean"], + instance=1, + extra_args={ + "actual_type": "integer", + "expected_type": "string", + }, + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_aurora.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_aurora.py new file mode 100644 index 0000000000000000000000000000000000000000..f8c2279aa79ea33a117919663b6368a24c0de550 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_aurora.py @@ -0,0 +1,91 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.rds.DbClusterAurora import DbClusterAurora + + +@pytest.fixture(scope="module") +def rule(): + rule = DbClusterAurora() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "Engine": "aurora-mysql", + }, + [], + ), + ( + {"Engine": "aurora-mysql", "StorageType": "aurora"}, + [], + ), + ( + {"Engine": "aurora-mysql", "StorageType": "io1"}, + [ + ValidationError( + ("'io1' is not one of ['aurora', 'aurora-iopt1']"), + rule=DbClusterAurora(), + path=deque(["StorageType"]), + validator="enum", + schema_path=deque( + ["then", "properties", "StorageType", "then", "enum"] + ), + ), + ], + ), + ( + { + "Engine": "aurora-mysql", + "AllocatedStorage": 100, + "DBClusterInstanceClass": "foo", + "Iops": 100, + }, + [ + ValidationError( + ( + "Additional properties are not allowed " + "'AllocatedStorage' when creating Aurora cluster" + ), + rule=DbClusterAurora(), + path=deque(["AllocatedStorage"]), + validator=None, + schema_path=deque(["then", "properties", "AllocatedStorage"]), + ), + ValidationError( + ( + "Additional properties are not allowed " + "'DBClusterInstanceClass' when creating Aurora cluster" + ), + rule=DbClusterAurora(), + path=deque(["DBClusterInstanceClass"]), + schema_path=deque(["then", "properties", "DBClusterInstanceClass"]), + validator=None, + ), + ValidationError( + ( + "Additional properties are not allowed 'Iops' " + "when creating Aurora cluster" + ), + rule=DbClusterAurora(), + path=deque(["Iops"]), + schema_path=deque(["then", "properties", "Iops"]), + validator=None, + ), + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_aurora_warning.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_aurora_warning.py new file mode 100644 index 0000000000000000000000000000000000000000..bd90896e2f353cb32db8a49476c468e60eda137d --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_aurora_warning.py @@ -0,0 +1,67 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.rds.DbClusterAuroraWarning import DbClusterAuroraWarning + + +@pytest.fixture(scope="module") +def rule(): + rule = DbClusterAuroraWarning() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + {"Engine": "aurora-mysql", "EngineMode": "serverless"}, + [], + ), + ( + { + "Engine": "aurora-mysql", + "EngineMode": "provisioned", + "PerformanceInsightsEnabled": True, + }, + [], + ), + ( + { + "Engine": "aurora-mysql", + "PerformanceInsightsEnabled": True, + }, + [], + ), + ( + { + "Engine": "aurora-mysql", + "EngineMode": "serverless", + "PerformanceInsightsEnabled": True, + }, + [ + ValidationError( + ( + "Additional properties are not allowed " + "'PerformanceInsightsEnabled' when creating Aurora cluster" + ), + rule=DbClusterAuroraWarning(), + path=deque(["PerformanceInsightsEnabled"]), + validator=None, + schema_path=deque( + ["then", "properties", "PerformanceInsightsEnabled"] + ), + ), + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_engine_version.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_engine_version.py new file mode 100644 index 0000000000000000000000000000000000000000..f1fde4a1575c43d7f78e1f1e52ccaea199a810d0 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_engine_version.py @@ -0,0 +1,90 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.rds.DbClusterEngineVersion import DbClusterEngineVersion + + +@pytest.fixture(scope="module") +def rule(): + rule = DbClusterEngineVersion() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "Engine": "mysql", + }, + [], + ), + ( + { + "Engine": "mysql", + "EngineVersion": "5.7.44", + }, + [], + ), + ( + { + "Engine": {"Ref": "Engine"}, + "EngineVersion": {"Ref": "EngineVersion"}, + }, + [], + ), + ( + { + "Engine": "mysql", + "EngineVersion": {"Ref": "EngineVersion"}, + }, + [], + ), + ( + {"Engine": "foo"}, + [ + ValidationError( + ( + "'foo' is not one of ['aurora-mysql', 'aurora-postgresql', " + "'mysql', 'postgres']" + ), + rule=DbClusterEngineVersion(), + path=deque(["Engine"]), + validator="enum", + schema_path=deque( + ["allOf", 0, "then", "properties", "Engine", "enum"] + ), + ) + ], + ), + ( + {"Engine": "mysql", "EngineVersion": "foo"}, + [ + ValidationError( + ( + "'foo' is not one of ['5.7.44', '5.7.44-rds.20240408', " + "'5.7.44-rds.20240529', '5.7.44-rds.20240808', " + "'8.0.32', '8.0.33', '8.0.34', " + "'8.0.35', '8.0.36', '8.0.37', '8.0.39']" + ), + rule=DbClusterEngineVersion(), + path=deque(["EngineVersion"]), + validator="enum", + schema_path=deque( + ["allOf", 3, "then", "properties", "EngineVersion", "enum"] + ), + ) + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_instance_class_enum.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_instance_class_enum.py new file mode 100644 index 0000000000000000000000000000000000000000..57a77c171445b65cca46a0ff571288625d1b4fe6 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_instance_class_enum.py @@ -0,0 +1,103 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.rds.DbClusterInstanceClassEnum import ( + DbClusterInstanceClassEnum, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = DbClusterInstanceClassEnum() + rule._schema = { + "us-east-1": { + "allOf": [ + { + "if": { + "properties": { + "DBClusterInstanceClass": {"type": "string"}, + "Engine": {"const": "mysql"}, + }, + "required": ["Engine", "DBClusterInstanceClass"], + }, + "then": { + "properties": { + "DBClusterInstanceClass": { + "enum": [ + "db.m5d.12xlarge", + "db.m5d.16xlarge", + ] + } + } + }, + } + ] + } + } + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + {"Engine": "mysql", "DBClusterInstanceClass": "db.m5d.12xlarge"}, + [], + ), + ( + {"Engine": "aurora-mysql", "DBClusterInstanceClass": "a"}, + [], + ), + ( + { + "Engine": {"Ref": "Engine"}, + "DBClusterInstanceClass": {"Ref": "DBInstanceClass"}, + }, + [], + ), + ( + { + "Engine": "mysql", + "DBClusterInstanceClass": {"Ref": "DBInstanceClass"}, + }, + [], + ), + ( + { + "Engine": "mysql", + "DBClusterInstanceClass": "a", + }, + [ + ValidationError( + ( + "'a' is not one of ['db.m5d.12xlarge', " + "'db.m5d.16xlarge'] in 'us-east-1'" + ), + rule=DbClusterInstanceClassEnum(), + path=deque(["DBClusterInstanceClass"]), + validator="enum", + schema_path=deque( + [ + "allOf", + 0, + "then", + "properties", + "DBClusterInstanceClass", + "enum", + ] + ), + ) + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_monitoring.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_monitoring.py new file mode 100644 index 0000000000000000000000000000000000000000..7c40360a5bdd3180056c05204547455bb61ee004 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_monitoring.py @@ -0,0 +1,95 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.rds.DbClusterMonitoring import DbClusterMonitoring + + +@pytest.fixture(scope="module") +def rule(): + rule = DbClusterMonitoring() + yield rule + + +@pytest.mark.parametrize( + "name,instance,expected", + [ + ( + "Valid monitoring configuration", + { + "MonitoringInterval": 1, + "MonitoringRoleArn": "arn", + }, + [], + ), + ( + "Valid empty monitoring", + {}, + [], + ), + ( + "Invalid with just monitoringInterval", + {"MonitoringInterval": "1"}, + [ + ValidationError( + ( + "You must have 'MonitoringRoleArn' specified " + "with 'MonitoringInterval' greater than 0" + ), + rule=DbClusterMonitoring(), + path=deque([]), + schema_path=deque(["else", "then", "required"]), + validator="required", + ) + ], + ), + ( + "Invalid with just monitoringRoleArn", + { + "MonitoringRoleArn": "arn", + }, + [ + ValidationError( + ( + "You must have 'MonitoringRoleArn' specified " + "with 'MonitoringInterval' greater than 0" + ), + rule=DbClusterMonitoring(), + path=deque([]), + schema_path=deque(["then", "required"]), + validator="required", + ) + ], + ), + ( + "Invalid with MonitoringInterval is 0", + { + "MonitoringRoleArn": "arn", + "MonitoringInterval": "0", + }, + [ + ValidationError( + ( + "You must have 'MonitoringRoleArn' specified " + "with 'MonitoringInterval' greater than 0" + ), + rule=DbClusterMonitoring(), + path=deque(["MonitoringInterval"]), + schema_path=deque( + ["then", "properties", "MonitoringInterval", "exclusiveMinimum"] + ), + validator="exclusiveMinimum", + ) + ], + ), + ], +) +def test_validate(name, instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + assert errs == expected, f"Test {name!r} for expected {expected!r} got {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_multiaz.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_multiaz.py new file mode 100644 index 0000000000000000000000000000000000000000..59bb177f98609625fee393a0aba53fbaca2b13d5 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_multiaz.py @@ -0,0 +1,132 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.rds.DbClusterMultiAz import DbClusterMultiAz + + +@pytest.fixture(scope="module") +def rule(): + rule = DbClusterMultiAz() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "Engine": "mysql", + "AllocatedStorage": 100, + "DBClusterInstanceClass": "foo", + "Iops": 100, + "StorageType": "io1", + }, + [], + ), + ( + { + "Engine": "aurora-mysql", + "AllocatedStorage": 100, + "DBClusterInstanceClass": "foo", + "Iops": 100, + }, + [], + ), + ( + { + "Engine": {"Ref": "Engine"}, + "AllocatedStorage": 100, + "DBClusterInstanceClass": "foo", + "Iops": 100, + }, + [], + ), + ( + { + "Engine": "mysql", + "AllocatedStorage": 100, + "DBClusterInstanceClass": "foo", + "Iops": 100, + "StorageType": "aurora", + }, + [ + ValidationError( + ("'aurora' is not one of ['io1', 'io2', 'gp3']"), + rule=DbClusterMultiAz(), + path=deque(["StorageType"]), + validator="enum", + schema_path=deque( + ["then", "properties", "StorageType", "then", "enum"] + ), + ), + ], + ), + ( + { + "Engine": "mysql", + }, + [ + ValidationError( + ("'AllocatedStorage' is a required property"), + rule=DbClusterMultiAz(), + path=deque([]), + validator="required", + schema_path=deque(["then", "required"]), + ), + ValidationError( + ("'DBClusterInstanceClass' is a required property"), + rule=DbClusterMultiAz(), + path=deque([]), + validator="required", + schema_path=deque(["then", "required"]), + ), + ValidationError( + ("'Iops' is a required property"), + rule=DbClusterMultiAz(), + path=deque([]), + validator="required", + schema_path=deque(["then", "required"]), + ), + ValidationError( + ("'StorageType' is a required property"), + rule=DbClusterMultiAz(), + path=deque([]), + validator="required", + schema_path=deque(["then", "required"]), + ), + ], + ), + ( + { + "Engine": "mysql", + "Domain": "Foo", + "AllocatedStorage": 100, + "DBClusterInstanceClass": "foo", + "Iops": 100, + "StorageType": "io1", + }, + [ + ValidationError( + ( + "Additional properties are not allowed 'Domain' " + "when creating Multi-AZ cluster" + ), + rule=DbClusterMultiAz(), + path=deque(["Domain"]), + validator=None, + schema_path=deque(["then", "properties", "Domain"]), + ), + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_serverless_exclusive.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_serverless_exclusive.py new file mode 100644 index 0000000000000000000000000000000000000000..cc82627b367adc990959f577a1f711ab26032d00 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_serverless_exclusive.py @@ -0,0 +1,102 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.rds.DbClusterServerlessExclusive import ( + DbClusterServerlessExclusive, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = DbClusterServerlessExclusive() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "EngineMode": "serverless", + }, + [], + ), + ( + { + "EngineMode": "Serverless", + }, + [], + ), + ( + {"EngineMode": "serverless", "ServerlessV2ScalingConfiguration": "foo"}, + [ + ValidationError( + ( + "EngineMode 'serverless' doesn't allow additional " + "properties 'ServerlessV2ScalingConfiguration'" + ), + rule=DbClusterServerlessExclusive(), + path=deque(["ServerlessV2ScalingConfiguration"]), + validator=None, + schema_path=deque( + [ + "allOf", + 1, + "then", + "properties", + "ServerlessV2ScalingConfiguration", + ] + ), + ) + ], + ), + ( + {"EngineMode": "provisioned", "ScalingConfiguration": "foo"}, + [ + ValidationError( + ( + "EngineMode 'provisioned' doesn't allow " + "additional properties 'ScalingConfiguration'" + ), + rule=DbClusterServerlessExclusive(), + path=deque(["ScalingConfiguration"]), + validator=None, + schema_path=deque( + ["allOf", 0, "then", "properties", "ScalingConfiguration"] + ), + ) + ], + ), + ( + {"ServerlessV2ScalingConfiguration": "foo"}, + [], + ), + ( + {"ScalingConfiguration": "foo"}, + [ + ValidationError( + ( + "Additional properties are not allowed " + "('ScalingConfiguration')" + ), + rule=DbClusterServerlessExclusive(), + path=deque(["ScalingConfiguration"]), + validator=None, + schema_path=deque( + ["allOf", 2, "then", "properties", "ScalingConfiguration"] + ), + ) + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_snapshotidentifier.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_snapshotidentifier.py new file mode 100644 index 0000000000000000000000000000000000000000..70f0278c14635661b9fea57b6b5a77ee17856b36 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_snapshotidentifier.py @@ -0,0 +1,53 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.rds.DbClusterSnapshotIdentifier import ( + DbClusterSnapshotIdentifier, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = DbClusterSnapshotIdentifier() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "SnapshotIdentifier": "foo", + }, + [], + ), + ( + { + "SnapshotIdentifier": "foo", + }, + [], + ), + ( + {"SnapshotIdentifier": "foo", "MasterUsername": "foo"}, + [ + ValidationError( + "Additional properties are ignored ('MasterUsername')", + rule=DbClusterSnapshotIdentifier(), + path=deque(["MasterUsername"]), + validator=None, + schema_path=deque(["then", "properties", "MasterUsername"]), + ) + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_sourcedbclusteridentifier.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_sourcedbclusteridentifier.py new file mode 100644 index 0000000000000000000000000000000000000000..52d9959861155c351b84cd7ef17d548f4da8117f --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_cluster_sourcedbclusteridentifier.py @@ -0,0 +1,54 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.rds.DbClusterSourceDBClusterIdentifier import ( + DbClusterSourceDBClusterIdentifier, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = DbClusterSourceDBClusterIdentifier() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "SourceDBClusterIdentifier": "foo", + }, + [], + ), + ( + {}, + [], + ), + ( + {"SourceDBClusterIdentifier": "foo", "MasterUsername": "foo"}, + [ + ValidationError( + ( + "Additional properties are ignored ('MasterUsername', " + "'MasterUserPassword', 'StorageEncrypted')" + ), + rule=DbClusterSourceDBClusterIdentifier(), + path=deque(["MasterUsername"]), + validator=None, + schema_path=deque(["then", "properties", "MasterUsername"]), + ) + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_instance_aurora_exclusive.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_instance_aurora_exclusive.py new file mode 100644 index 0000000000000000000000000000000000000000..873be2b3eff3b27b852bf08cfe0d8d0a20c83f7c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_instance_aurora_exclusive.py @@ -0,0 +1,107 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.rds.DbInstanceAuroraExclusive import ( + DbInstanceAuroraExclusive, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = DbInstanceAuroraExclusive() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "Engine": "aurora", + }, + [], + ), + ( + { + "Engine": "Auora", + }, + [], + ), + ( + {"MasterUserPassword": "Test"}, + [], + ), + ( + { + "Engine": "aurora", + "DeletionProtection": True, + }, + [ + ValidationError( + "Additional properties are not allowed (['DeletionProtection'])", + rule=DbInstanceAuroraExclusive(), + path=deque([]), + instance={"Engine": "aurora", "DeletionProtection": True}, + validator="not", + schema_path=deque(["then", "not"]), + ) + ], + ), + ( + { + "Engine": "Aurora", + "DeletionProtection": True, + }, + [ + ValidationError( + "Additional properties are not allowed (['DeletionProtection'])", + rule=DbInstanceAuroraExclusive(), + path=deque([]), + instance={"Engine": "aurora", "DeletionProtection": True}, + validator="not", + schema_path=deque(["then", "not"]), + ) + ], + ), + ( + { + "Engine": "aurora", + "DeletionProtection": True, + "CopyTagsToSnapshot": True, + }, + [ + ValidationError( + ( + "Additional properties are not " + "allowed (['DeletionProtection', " + "'CopyTagsToSnapshot'])" + ), + rule=DbInstanceAuroraExclusive(), + path=deque([]), + instance={ + "Engine": "aurora", + "DeletionProtection": True, + "CopyTagsToSnapshot": True, + }, + validator="not", + schema_path=deque(["then", "not"]), + ) + ], + ), + ( + [], + [], + ), + ], +) +def test_backup_lifecycle(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_instance_db_instance_class_enum.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_instance_db_instance_class_enum.py new file mode 100644 index 0000000000000000000000000000000000000000..ce02f3ef8ffea5c23b366e2d9bf35ff0d989fc4d --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_instance_db_instance_class_enum.py @@ -0,0 +1,110 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import pytest + +from cfnlint.rules.resources.rds.DbInstanceDbInstanceClassEnum import ( + DbInstanceDbInstanceClassEnum, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = DbInstanceDbInstanceClassEnum() + yield rule + + +@pytest.mark.parametrize( + "name,instance,regions,err_count", + [ + ( + "Valid version", + {"DBInstanceClass": "db.x2iedn.8xlarge", "Engine": "mysql"}, + ["us-east-1"], + 0, + ), + ( + "Valid but wrong type", + [], + ["us-east-1"], + 0, + ), + ( + "Valid but wrong type for Engine", + {"Engine": []}, + ["us-east-1"], + 0, + ), + ( + "No error ref value", + { + "DBInstanceClass": "notanappropriatetype", + "Engine": "sqlserver-se", + "LicenseModel": {"Ref": "License"}, + }, + ["us-east-1"], + 0, + ), + ( + "Bad instance type with no license", + {"DBInstanceClass": "db.m4.xlarge", "Engine": "aurora-mysql"}, + ["us-east-1"], + 1, + ), + ( + "Bad value on bring your own license", + { + "DBInstanceClass": "db.x2e.xlarge", + "Engine": "oracle-se2", + "LicenseModel": "bring-your-own-license", + }, + ["us-east-1"], + 1, + ), + ( + "Bad value on bring your own license", + { + "DBInstanceClass": "db.x2e.xlarge", + "Engine": "oracle-se2", + "LicenseModel": "bring-your-own-license", + }, + ["us-east-1"], + 1, + ), + ( + "Bad value on license included", + { + "DBInstanceClass": "db.x1e.xlarge", + "Engine": "oracle-se2", + "LicenseModel": "license-included", + }, + ["us-east-1"], + 1, + ), + ( + "Bad value on license included and uppser case Engine", + { + "DBInstanceClass": "db.x1e.xlarge", + "Engine": "Oracle-SE2", + "LicenseModel": "license-included", + }, + ["us-east-1"], + 1, + ), + ( + "Instance type invalid in one region", + {"DBInstanceClass": "db.x2iedn.8xlarge", "Engine": "mysql"}, + ["us-east-1", "ca-west-1"], + 1, + ), + ], +) +def test_validate(name, instance, regions, err_count, rule, validator): + validator = validator.evolve(context=validator.context.evolve(regions=regions)) + errors = list(rule.validate(validator, "", instance, {})) + + # we use error counts in this one as the instance types are + # always changing so we aren't going to hold ourselves up by that + assert len(errors) == err_count, f"Test {name!r} got {errors!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_instance_engine_version.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_instance_engine_version.py new file mode 100644 index 0000000000000000000000000000000000000000..2d660d8512284408377649b63fa096340e38f64e --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/rds/test_db_instance_engine_version.py @@ -0,0 +1,99 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.rds.DbInstanceEngineVersion import DbInstanceEngineVersion + + +@pytest.fixture(scope="module") +def rule(): + rule = DbInstanceEngineVersion() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "Engine": "mysql", + }, + [], + ), + ( + [], + [], + ), + ( + { + "Engine": "MySqL", # API converts it appropriately + }, + [], + ), + ( + {"Engine": {"Ref": "Engine"}}, + [], + ), + ( + {"Engine": {"Ref": "Engine"}, "EngineVeresion": {"Ref": "EngineVersion"}}, + [], + ), + ( + { + "Engine": "MySqL", # API converts it appropriately + "EngineVeresion": {"Ref": "EngineVersion"}, + }, + [], + ), + ( + {"Engine": "foo"}, + [ + ValidationError( + ( + "'foo' is not one of ['aurora-mysql', 'aurora-postgresql', " + "'custom-oracle-ee', 'custom-oracle-ee-cdb', " + "'custom-sqlserver-ee', 'custom-sqlserver-se', " + "'custom-sqlserver-web', 'db2-ae', 'db2-se', 'mariadb', " + "'mysql', 'oracle-ee', 'oracle-ee-cdb', 'oracle-se2', " + "'oracle-se2-cdb', 'postgres', 'sqlserver-ee', " + "'sqlserver-ex', 'sqlserver-se', 'sqlserver-web']" + ), + rule=DbInstanceEngineVersion(), + path=deque(["Engine"]), + validator="enum", + schema_path=deque( + ["allOf", 0, "then", "properties", "Engine", "enum"] + ), + ) + ], + ), + ( + {"Engine": "mysql", "EngineVersion": "foo"}, + [ + ValidationError( + ( + "'foo' is not one of ['5.7.44', '5.7.44-rds.20240408', " + "'5.7.44-rds.20240529', '5.7.44-rds.20240808', " + "'8.0.32', '8.0.33', '8.0.34', '8.0.35', " + "'8.0.36', '8.0.37', '8.0.39']" + ), + rule=DbInstanceEngineVersion(), + path=deque(["EngineVersion"]), + validator="enum", + schema_path=deque( + ["allOf", 9, "then", "properties", "EngineVersion", "enum"] + ), + ) + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/route53/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/route53/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/route53/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/route53/test_health_check_health_check_config_type_inclusive.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/route53/test_health_check_health_check_config_type_inclusive.py new file mode 100644 index 0000000000000000000000000000000000000000..7ace6a7dae6495ff32aecc5c996b7aaa49b8ffce --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/route53/test_health_check_health_check_config_type_inclusive.py @@ -0,0 +1,58 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.route53.HealthCheckHealthCheckConfigTypeInclusive import ( + HealthCheckHealthCheckConfigTypeInclusive, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = HealthCheckHealthCheckConfigTypeInclusive() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + {"Type": "CLOUDWATCH_METRIC", "AlarmIdentifier": "Foo"}, + [], + ), + ( + { + "Type": {"Ref": "AWS::Region"}, + }, + [], + ), + ( + [], + [], + ), + ( + { + "Type": "CLOUDWATCH_METRIC", + }, + [ + ValidationError( + "'AlarmIdentifier' is a required property", + rule=HealthCheckHealthCheckConfigTypeInclusive(), + path=deque([]), + validator="required", + schema_path=deque(["then", "required"]), + ) + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/route53/test_recordset_alias.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/route53/test_recordset_alias.py new file mode 100644 index 0000000000000000000000000000000000000000..2711ff1be6f130db073cbf9baf4c91fb31603176 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/route53/test_recordset_alias.py @@ -0,0 +1,62 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.route53.RecordSetAlias import RecordSetAlias + + +@pytest.fixture(scope="module") +def rule(): + rule = RecordSetAlias() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "AliasTarget": [], + "TTL": 10, + }, + [], + ), + ( + { + "TTL": 10, + }, + [], + ), + ( + { + "AliasTarget": ["Foo"], + "TTL": 10, + }, + [ + ValidationError( + "Additional properties are not allowed ('TTL' was unexpected)", + rule=RecordSetAlias(), + path=deque(["TTL"]), + validator=None, + schema_path=deque( + [ + "then", + "properties", + "TTL", + ] + ), + ) + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/route53/test_recordset_name.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/route53/test_recordset_name.py new file mode 100644 index 0000000000000000000000000000000000000000..c324368721efb834f54ee88589f6eef0b113598e --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/route53/test_recordset_name.py @@ -0,0 +1,92 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.route53.RecordSetName import RecordSetName + + +@pytest.fixture(scope="module") +def rule(): + rule = RecordSetName() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "HostedZoneName": "bar.", + "Name": "foo.bar", + }, + [], + ), + ( + { + "HostedZoneName": "bar.", + "Name": "bar", + }, + [], + ), + ( + { + "HostedZoneName": "bar.", + "Name": {"Ref": "pName"}, + }, + [], + ), + ( + { + "HostedZoneName": {"Ref": "pHostedZoneName"}, + "Name": "foo.bar", + }, + [], + ), + ( + { + "HostedZoneName": "bar", + "Name": "foo.bar.", + }, + [ + ValidationError( + "'bar' must end in a dot", + path=deque(["HostedZoneName"]), + ) + ], + ), + ( + { + "HostedZoneName": "bar.", + "Name": "bar.foo.", + }, + [ + ValidationError( + "'bar.foo.' must be a subdomain of or equal to 'bar.'", + path=deque(["Name"]), + ) + ], + ), + ( + { + "HostedZoneName": "bar.", + "Name": "foobar.", + }, + [ + ValidationError( + "'foobar.' must be a subdomain of or equal to 'bar.'", + path=deque(["Name"]), + ) + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/route53/test_recordsets.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/route53/test_recordsets.py new file mode 100644 index 0000000000000000000000000000000000000000..af86f05e29954ff5dc581da4dd7eef0521bbc499 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/route53/test_recordsets.py @@ -0,0 +1,524 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.route53.RecordSet import RecordSet + + +@pytest.fixture(scope="module") +def rule(): + rule = RecordSet() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "Type": "A", + "ResourceRecords": ["127.0.0.1"], + }, + [], + ), + ( + { + "Type": "A", + "ResourceRecords": ["domain.local"], + }, + [ + ValidationError( + "'domain.local' is not a 'ipv4'", + rule=RecordSet(), + path=deque(["ResourceRecords", 0]), + validator="format", + schema_path=deque( + [ + "allOf", + 0, + "then", + "properties", + "ResourceRecords", + "items", + "format", + ] + ), + ) + ], + ), + ( + { + "Type": "TXT", + "ResourceRecords": [ + '"MS=ms123123"', + # 255 "a" characters + quotes + '"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"', + # 255 "a" characters and 255 "b" characters + '"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa""bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"', + # 255 "a" characters and 255 "b" characters and + # 255 "c" characters with a space between b and c + '"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa""bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"', # noqa: E501 + ], + }, + [], + ), + ( + { + "Type": "TXT", + "ResourceRecords": [ + # 256 "a" characters - too long + '"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"', + # 256 "b" characters in a second record - too long + '"a""bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"', + '"MS=ms123123"', + # No quotation + "test2", + ], + }, + [ + ValidationError( + '\'"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\' does not match \'^("[^"]{1,255}" *)*"[^"]{1,255}"$\'', # noqa: E501 + rule=RecordSet(), + path=deque(["ResourceRecords", 0]), + validator="pattern", + schema_path=deque( + [ + "allOf", + 12, + "then", + "properties", + "ResourceRecords", + "items", + "pattern", + ] + ), + ), + ValidationError( + '\'"a""bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"\' does not match \'^("[^"]{1,255}" *)*"[^"]{1,255}"$\'', # noqa: E501 + rule=RecordSet(), + path=deque(["ResourceRecords", 1]), + validator="pattern", + schema_path=deque( + [ + "allOf", + 12, + "then", + "properties", + "ResourceRecords", + "items", + "pattern", + ] + ), + ), + ValidationError( + '\'test2\' does not match \'^("[^"]{1,255}" *)*"[^"]{1,255}"$\'', + rule=RecordSet(), + path=deque(["ResourceRecords", 3]), + validator="pattern", + schema_path=deque( + [ + "allOf", + 12, + "then", + "properties", + "ResourceRecords", + "items", + "pattern", + ] + ), + ), + ], + ), + ( + { + "Type": "AAAA", + "ResourceRecords": [ + "2001:0db8:85a3:0:0:8a2e:0370:7334", + "2001:0db8:3c4d:0015:0000:0000:1a2f:1a2b", + "0:0:0:0:0:0:A00:1", + ], + }, + [], + ), + ( + { + "Type": "AAAA", + "ResourceRecords": [ + # IPv4 address + "127.0.0.1", + # Invalid data + "XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:1.2.3.4", + # Spaces + "2001:0db8: 85a3:0:0:8a2e:0370:7334", + # Missing components + "1111:2222:3333:4444:5555:6666:7777", + # Too much components + "1111:2222:3333:4444:5555:6666:7777:8888::", + ], + }, + [ + ValidationError( + "'127.0.0.1' is not a 'ipv6'", + rule=RecordSet(), + path=deque(["ResourceRecords", 0]), + validator="format", + schema_path=deque( + [ + "allOf", + 1, + "then", + "properties", + "ResourceRecords", + "items", + "format", + ] + ), + ), + ValidationError( + "'XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:1.2.3.4' is not a 'ipv6'", + rule=RecordSet(), + path=deque(["ResourceRecords", 1]), + validator="format", + schema_path=deque( + [ + "allOf", + 1, + "then", + "properties", + "ResourceRecords", + "items", + "format", + ] + ), + ), + ValidationError( + "'2001:0db8: 85a3:0:0:8a2e:0370:7334' is not a 'ipv6'", + rule=RecordSet(), + path=deque(["ResourceRecords", 2]), + validator="format", + schema_path=deque( + [ + "allOf", + 1, + "then", + "properties", + "ResourceRecords", + "items", + "format", + ] + ), + ), + ValidationError( + "'1111:2222:3333:4444:5555:6666:7777' is not a 'ipv6'", + rule=RecordSet(), + path=deque(["ResourceRecords", 3]), + validator="format", + schema_path=deque( + [ + "allOf", + 1, + "then", + "properties", + "ResourceRecords", + "items", + "format", + ] + ), + ), + ValidationError( + "'1111:2222:3333:4444:5555:6666:7777:8888::' is not a 'ipv6'", + rule=RecordSet(), + path=deque(["ResourceRecords", 4]), + validator="format", + schema_path=deque( + [ + "allOf", + 1, + "then", + "properties", + "ResourceRecords", + "items", + "format", + ] + ), + ), + ], + ), + ( + { + "Type": "CAA", + "ResourceRecords": [ + '0 issue "amazontrust.com;"', + '0 issue "awstrust.com;"', + '0 issue "amazonaws.com;"', + ], + }, + [], + ), + ( + { + "Type": "CAA", + "ResourceRecords": [ + # No 3 items + "127.0.0.1", + # Missing quotes around the value + "0 issue amazon.com; henk", + ], + }, + [ + ValidationError( + ( + "'127.0.0.1' does not match " + "'^(0|128)\\\\s([a-zA-Z0-9]+)\\\\s(\".+\")$'" + ), + rule=RecordSet(), + path=deque(["ResourceRecords", 0]), + validator="pattern", + schema_path=deque( + [ + "allOf", + 2, + "then", + "properties", + "ResourceRecords", + "items", + "pattern", + ] + ), + ), + ValidationError( + ( + "'0 issue amazon.com; henk' does not match " + "'^(0|128)\\\\s([a-zA-Z0-9]+)\\\\s(\".+\")$'" + ), + rule=RecordSet(), + path=deque(["ResourceRecords", 1]), + validator="pattern", + schema_path=deque( + [ + "allOf", + 2, + "then", + "properties", + "ResourceRecords", + "items", + "pattern", + ] + ), + ), + ], + ), + ( + { + "Type": "CNAME", + "ResourceRecords": [ + "hostname.example.com", + ], + }, + [], + ), + ( + { + "Type": "CNAME", + "ResourceRecords": [ + "_x2.acm-validations.aws.", + ], + }, + [], + ), + ( + { + "Type": "CNAME", + "ResourceRecords": [ + "cname1.example.com", + "foo√bar", + ], + }, + [ + ValidationError( + "'foo√bar' is not valid under any of the given schemas", + rule=RecordSet(), + path=deque(["ResourceRecords", 1]), + validator="anyOf", + context=deque( + [ + ValidationError( + ( + "'foo√bar' does not match " + "'^[a-zA-Z0-9\\\\!\"\\\\#\\\\$\\\\%\\\\&\\\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,-\\\\/\\\\:\\\\;\\\\<\\\\=\\\\>\\\\?\\\\@\\\\[\\\\\\\\\\\\]\\\\^\\\\_\\\\`\\\\{\\\\|\\\\}\\\\~\\\\.]+$'" + ), # noqa: E501 + path=deque([]), + validator="pattern", + schema_path=deque([0, "pattern"]), + rule=RecordSet(), + ), + ValidationError( + ( + "'foo√bar' does not match " + "'^.*\\\\.acm-validations\\\\.aws\\\\.?$'" + ), + path=deque([]), + validator="pattern", + schema_path=deque([1, "pattern"]), + rule=RecordSet(), + ), + ] + ), + schema_path=deque( + [ + "allOf", + 3, + "then", + "properties", + "ResourceRecords", + "items", + "anyOf", + ] + ), + ), + ValidationError( + "['cname1.example.com', 'foo√bar'] is too long (1)", + rule=RecordSet(), + path=deque(["ResourceRecords"]), + validator="maxItems", + schema_path=deque( + [ + "allOf", + 3, + "then", + "properties", + "ResourceRecords", + "maxItems", + ] + ), + ), + ], + ), + ( + { + "Type": "CNAME", + "ResourceRecords": [ + # No valid domain name + "No valid domain name" + ], + }, + [ + ValidationError( + ( + "'No valid domain name' is not valid " + "under any of the given schemas" + ), + rule=RecordSet(), + path=deque(["ResourceRecords", 0]), + validator="anyOf", + context=deque( + [ + ValidationError( + ( + "'No valid domain name' does not match " + "'^[a-zA-Z0-9\\\\!\"\\\\#\\\\$\\\\%\\\\&\\\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,-\\\\/\\\\:\\\\;\\\\<\\\\=\\\\>\\\\?\\\\@\\\\[\\\\\\\\\\\\]\\\\^\\\\_\\\\`\\\\{\\\\|\\\\}\\\\~\\\\.]+$'" # noqa: E501 + ), + path=deque([]), + validator="pattern", + schema_path=deque([0, "pattern"]), + rule=RecordSet(), + ), + ValidationError( + ( + "'No valid domain name' does not match " + "'^.*\\\\.acm-validations\\\\.aws\\\\.?$'" + ), + path=deque([]), + validator="pattern", + schema_path=deque([1, "pattern"]), + rule=RecordSet(), + ), + ] + ), + schema_path=deque( + [ + "allOf", + 3, + "then", + "properties", + "ResourceRecords", + "items", + "anyOf", + ] + ), + ), + ], + ), + ( + { + "Type": "MX", + "ResourceRecords": [ + "0 mx.example.com", + "65535 mx2.example.com", + ], + }, + [], + ), + ( + { + "Type": "MX", + "ResourceRecords": [ + "127.0.0.1", + "10 my domain", + ], + }, + [ + ValidationError( + ( + "'127.0.0.1' does not match " + "'^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{1-3}|65[0-4][0-9]{1-2}|655[0-2][0-9]|6553[0-5])\\\\s[a-zA-Z0-9\\\\!\"\\\\#\\\\$\\\\%\\\\&\\\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,-\\\\/\\\\:\\\\;\\\\<\\\\=\\\\>\\\\?\\\\@\\\\[\\\\\\\\\\\\]\\\\^\\\\_\\\\`\\\\{\\\\|\\\\}\\\\~\\\\.]+$'" + ), + rule=RecordSet(), + path=deque(["ResourceRecords", 0]), + validator="pattern", + schema_path=deque( + [ + "allOf", + 5, + "then", + "properties", + "ResourceRecords", + "items", + "pattern", + ] + ), + ), + ValidationError( + ( + "'10 my domain' does not match " + "'^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{1-3}|65[0-4][0-9]{1-2}|655[0-2][0-9]|6553[0-5])\\\\s[a-zA-Z0-9\\\\!\"\\\\#\\\\$\\\\%\\\\&\\\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,-\\\\/\\\\:\\\\;\\\\<\\\\=\\\\>\\\\?\\\\@\\\\[\\\\\\\\\\\\]\\\\^\\\\_\\\\`\\\\{\\\\|\\\\}\\\\~\\\\.]+$'" + ), + rule=RecordSet(), + path=deque(["ResourceRecords", 1]), + validator="pattern", + schema_path=deque( + [ + "allOf", + 5, + "then", + "properties", + "ResourceRecords", + "items", + "pattern", + ] + ), + ), + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/s3/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/s3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/s3/test_access_control_obsolete.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/s3/test_access_control_obsolete.py new file mode 100644 index 0000000000000000000000000000000000000000..aa9cabc550f4895ace7dd27987e72ac5ecb9f467 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/s3/test_access_control_obsolete.py @@ -0,0 +1,52 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.s3.AccessControlObsolete import AccessControlObsolete + + +@pytest.fixture(scope="module") +def rule(): + rule = AccessControlObsolete() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "AccessControl": "AuthenticatedRead", + }, + [ + ValidationError( + ( + "'AccessControl' is a legacy property. " + "Consider using 'AWS::S3::BucketPolicy' instead" + ), + path=deque(["AccessControl"]), + ) + ], + ), + ( + { + "AccessControl": {"Ref": "AWS::NoValue"}, + }, + [], + ), + ( + {}, + [], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/s3/test_access_control_ownership.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/s3/test_access_control_ownership.py new file mode 100644 index 0000000000000000000000000000000000000000..5f7d6e5cd13321b7d0c26293235718d670cde951 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/s3/test_access_control_ownership.py @@ -0,0 +1,115 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.s3.AccessControlOwnership import AccessControlOwnership + + +@pytest.fixture(scope="module") +def rule(): + rule = AccessControlOwnership() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + {}, + [], + ), + ( + {"AccessControl": "Private"}, + [], + ), + ( + { + "AccessControl": {"Ref": "AWS::NoValue"}, + }, + [], + ), + ( + { + "AccessControl": "AuthenticatedRead", + "OwnershipControls": {"Rules": [{"ObjectOwnership": "BucketOwner"}]}, + }, + [], + ), + ( + { + "AccessControl": "AuthenticatedRead", + }, + [ + ValidationError( + ( + "A bucket with 'AccessControl' set should also " + "have at least one 'OwnershipControl' configured" + ), + path=deque([]), + validator="required", + schema_path=deque(["then", "required"]), + rule=AccessControlOwnership(), + ) + ], + ), + ( + { + "AccessControl": "AuthenticatedRead", + "OwnershipControls": {}, + }, + [ + ValidationError( + ( + "A bucket with 'AccessControl' set should also " + "have at least one 'OwnershipControl' configured" + ), + path=deque(["OwnershipControls"]), + validator="required", + schema_path=deque( + ["then", "properties", "OwnershipControls", "required"] + ), + rule=AccessControlOwnership(), + ) + ], + ), + ( + { + "AccessControl": "AuthenticatedRead", + "OwnershipControls": { + "Rules": [], + }, + }, + [ + ValidationError( + ( + "A bucket with 'AccessControl' set should also " + "have at least one 'OwnershipControl' configured" + ), + path=deque(["OwnershipControls", "Rules"]), + validator="minItems", + schema_path=deque( + [ + "then", + "properties", + "OwnershipControls", + "properties", + "Rules", + "minItems", + ] + ), + rule=AccessControlOwnership(), + ) + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/ssm/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/ssm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/stepfunctions/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/stepfunctions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/stepfunctions/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/stepfunctions/test_state_machine_definition.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/stepfunctions/test_state_machine_definition.py new file mode 100644 index 0000000000000000000000000000000000000000..954fd4a85de131f2d8573ac5c6fb4b4da5ed833c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/stepfunctions/test_state_machine_definition.py @@ -0,0 +1,707 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema.validators import ValidationError +from cfnlint.rules.resources.stepfunctions.StateMachineDefinition import ( + StateMachineDefinition, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = StateMachineDefinition() + yield rule + + +# These state machines for testing have long lines +# with lots of indentation +# ruff: noqa: E501 + + +@pytest.mark.parametrize( + "name,instance,expected", + [ + ( + "Valid string json", + { + "Definition": { + "Comment": ( + "An example of the Amazon States " + "Language for notification on an " + "AWS Batch job completion" + ), + "StartAt": "Submit Batch Job", + "TimeoutSeconds": 3600, + "States": { + "Submit Batch Job": { + "Type": "Task", + "Resource": "arn:aws:states:::batch:submitJob.sync", + "Parameters": { + "JobName": "BatchJobNotification", + "JobQueue": "arn:aws:batch:us-east-1:123456789012:job-queue/BatchJobQueue-7049d367474b4dd", + "JobDefinition": "arn:aws:batch:us-east-1:123456789012:job-definition/BatchJobDefinition-74d55ec34c4643c:1", + }, + "Next": "Notify Success", + "Catch": [ + { + "ErrorEquals": ["States.ALL"], + "Next": "Notify Failure", + } + ], + }, + "Notify Success": { + "Type": "Task", + "Resource": "arn:aws:states:::sns:publish", + "Parameters": { + "Message": "Batch job submitted through Step Functions succeeded", + "TopicArn": "arn:aws:sns:us-east-1:123456789012:batchjobnotificatiointemplate-SNSTopic-1J757CVBQ2KHM", + }, + "End": True, + }, + "Notify Failure": { + "Type": "Task", + "Resource": "arn:aws:states:::sns:publish", + "Parameters": { + "Message": "Batch job submitted through Step Functions failed", + "TopicArn": "arn:aws:sns:us-east-1:123456789012:batchjobnotificatiointemplate-SNSTopic-1J757CVBQ2KHM", + }, + "End": True, + }, + }, + } + }, + [], + ), + ( + "Fan out example", + { + "Definition": { + "Comment": "An example of the Amazon States Language for fanning out AWS Batch job", + "StartAt": "Generate batch job input", + "TimeoutSeconds": 3600, + "States": { + "Generate batch job input": { + "Type": "Task", + "Resource": "arn:aws:states:::lambda:invoke", + "OutputPath": "$.Payload", + "Parameters": { + "FunctionName": "" + }, + "Next": "Fan out batch jobs", + }, + "Fan out batch jobs": { + "Comment": "Start multiple executions of batch job depending on pre-processed data", + "Type": "Map", + "End": True, + "ItemsPath": "$", + "Parameters": {"BatchNumber.$": "$$.Map.Item.Value"}, + "ItemProcessor": { + "StartAt": "Submit Batch Job", + "States": { + "Submit Batch Job": { + "Type": "Task", + "Resource": "arn:aws:states:::batch:submitJob.sync", + "Parameters": { + "JobName": "BatchJobFanOut", + "JobQueue": "", + "JobDefinition": "", + }, + "End": True, + } + }, + }, + }, + }, + } + }, + [], + ), + ( + "Error handling", + { + "Definition": """ + { + "Comment": "An example of the Amazon States Language for notification on an AWS Batch job completion", + "StartAt": "Submit Batch Job", + "TimeoutSeconds": 3600, + "States": { + "Submit Batch Job": { + "Type": "Task", + "Resource": "arn:aws:states:::batch:submitJob.sync", + "Parameters": { + "JobName": "BatchJobNotification", + "JobQueue": "arn:aws:batch:us-west-2:123456789012:job-queue/BatchJobQueue-123456789abcdef", + "JobDefinition": "arn:aws:batch:us-west-2:123456789012:job-definition/BatchJobDefinition-123456789abcdef:1", + }, + "Next": "Notify Success", + "Retry": [ + { + "ErrorEquals": ["States.ALL"], + "IntervalSeconds": 30, + "MaxAttempts": 2, + "BackoffRate": 1.5, + } + ], + "Catch": [ + {"ErrorEquals": ["States.ALL"], "Next": "Notify Failure"} + ], + }, + "Notify Success": { + "Type": "Task", + "Resource": "arn:aws:states:::sns:publish", + "Parameters": { + "Message": "Batch job submitted through Step Functions succeeded", + "TopicArn": "arn:aws:sns:us-west-2:123456789012:StepFunctionsSample-BatchJobManagement12345678-9abc-def0-1234-567890abcdef-SNSTopic-A2B3C4D5E6F7G", + }, + "End": True, + }, + "Notify Failure": { + "Type": "Task", + "Resource": "arn:aws:states:::sns:publish", + "Parameters": { + "Message": "Batch job submitted through Step Functions failed", + "TopicArn": "arn:aws:sns:us-west-2:123456789012:StepFunctionsSample-BatchJobManagement12345678-9abc-def0-1234-567890abcdef-SNSTopic-A2B3C4D5E6F7G", + }, + "End": True, + } + } + } + """ + }, + [], + ), + ( + "Transfer data records", + { + "Definition": { + "Comment": "An example of the Amazon States Language for reading messages from a DynamoDB table and sending them to SQS", + "StartAt": "Seed the DynamoDB Table", + "TimeoutSeconds": 3600, + "States": { + "Seed the DynamoDB Table": { + "Type": "Task", + "Resource": "arn:aws:lambda:us-east-1:123456789012:function:sqsconnector-SeedingFunction-T3U43VYDU5OQ", + "ResultPath": "$.List", + "Next": "For Loop Condition", + }, + "For Loop Condition": { + "Type": "Choice", + "Choices": [ + { + "Not": { + "Variable": "$.List[0]", + "StringEquals": "DONE", + }, + "Next": "Read Next Message from DynamoDB", + } + ], + "Default": "Succeed", + }, + "Read Next Message from DynamoDB": { + "Type": "Task", + "Resource": "arn:aws:states:::dynamodb:getItem", + "Parameters": { + "TableName": "sqsconnector-DDBTable-1CAFOJWP8QD6I", + "Key": {"MessageId": {"S.$": "$.List[0]"}}, + }, + "ResultPath": "$.DynamoDB", + "Next": "Send Message to SQS", + }, + "Send Message to SQS": { + "Type": "Task", + "Resource": "arn:aws:states:::sqs:sendMessage", + "Parameters": { + "MessageBody.$": "$.DynamoDB.Item.Message.S", + "QueueUrl": "https://sqs.us-east-1.amazonaws.com/123456789012/sqsconnector-SQSQueue-QVGQBW134PWK", + }, + "ResultPath": "$.SQS", + "Next": "Pop Element from List", + }, + "Pop Element from List": { + "Type": "Pass", + "Parameters": {"List.$": "$.List[1:]"}, + "Next": "For Loop Condition", + }, + "Succeed": {"Type": "Succeed"}, + }, + } + }, + [], + ), + ( + "A map", + { + "Definition": { + "Comment": "An example of the Amazon States Language for reading messages from an SQS queue and iteratively processing each message.", + "StartAt": "Read messages from SQS Queue", + "States": { + "Read messages from SQS Queue": { + "Type": "Task", + "Resource": "arn:aws:states:::lambda:invoke", + "OutputPath": "$.Payload", + "Parameters": { + "FunctionName": "MapSampleProj-ReadFromSQSQueueLambda-1MY3M63RMJVA9" + }, + "Next": "Are there messages to process?", + }, + "Are there messages to process?": { + "Type": "Choice", + "Choices": [ + { + "Variable": "$", + "StringEquals": "No messages", + "Next": "Finish", + } + ], + "Default": "Process messages", + }, + "Process messages": { + "Type": "Map", + "Next": "Finish", + "ItemsPath": "$", + "Parameters": { + "MessageNumber.$": "$$.Map.Item.Index", + "MessageDetails.$": "$$.Map.Item.Value", + }, + "ItemProcessor": { + "StartAt": "Write message to DynamoDB", + "States": { + "Write message to DynamoDB": { + "Type": "Task", + "Resource": "arn:aws:states:::dynamodb:putItem", + "ResultPath": None, + "Parameters": { + "TableName": "MapSampleProj-DDBTable-YJDJ1MKIN6C5", + "ReturnConsumedCapacity": "TOTAL", + "Item": { + "MessageId": { + "S.$": "$.MessageDetails.MessageId" + }, + "Body": { + "S.$": "$.MessageDetails.Body" + }, + }, + }, + "Next": "Remove message from SQS queue", + }, + "Remove message from SQS queue": { + "Type": "Task", + "Resource": "arn:aws:states:::lambda:invoke", + "InputPath": "$.MessageDetails", + "ResultPath": None, + "Parameters": { + "FunctionName": "MapSampleProj-DeleteFromSQSQueueLambda-198J2839ZO5K2", + "Payload": { + "ReceiptHandle.$": "$.ReceiptHandle" + }, + }, + "Next": "Publish message to SNS topic", + }, + "Publish message to SNS topic": { + "Type": "Task", + "Resource": "arn:aws:states:::sns:publish", + "InputPath": "$.MessageDetails", + "Parameters": { + "Subject": "Message from Step Functions!", + "Message.$": "$.Body", + "TopicArn": "arn:aws:sns:us-east-1:012345678910:MapSampleProj-SNSTopic-1CQO4HQ3IR1KN", + }, + "End": True, + }, + }, + }, + }, + "Finish": {"Type": "Succeed"}, + }, + } + }, + [], + ), + ( + "Test functions", + { + "Definition": { + "StartAt": "Task1", + "States": { + "Task1": { + "Type": "Task", + "Credentials": { + "Data": "input data", + "Algorithm": "SHA-1", + }, + "Resource": "arn:aws:states:::batch:submitJob.sync", + "End": True, + }, + }, + } + }, + [], + ), + ( + "Choices", + { + "Definition": { + "StartAt": "ChoiceStateX", + "States": { + "ChoiceStateX": { + "Type": "Choice", + "Choices": [ + { + "Not": { + "Variable": "$.type", + "StringEquals": "Private", + }, + "Next": "Public", + }, + { + "Variable": "$.value", + "NumericEquals": 0, + "Next": "ValueIsZero", + }, + { + "And": [ + { + "Variable": "$.value", + "NumericGreaterThanEquals": 20, + }, + {"Variable": "$.value", "NumericLessThan": 30}, + ], + "Next": "ValueInTwenties", + }, + { + "Variable": "$.value", + "NumericLessThan": 0, + "Next": "ValueIsNegative", + }, + ], + "Default": "DefaultState", + }, + "Public": { + "Type": "Task", + "Resource": "arn:aws:lambda:us-east-1:123456789012:function:Foo", + "Next": "NextState", + }, + "ValueIsZero": { + "Type": "Task", + "Resource": "arn:aws:lambda:us-east-1:123456789012:function:Zero", + "Next": "NextState", + }, + "ValueInTwenties": { + "Type": "Task", + "Resource": "arn:aws:lambda:us-east-1:123456789012:function:Bar", + "Next": "NextState", + }, + "ValueIsNegative": { + "Type": "Succeed", + }, + "DefaultState": {"Type": "Fail", "Cause": "No Matches!"}, + }, + } + }, + [], + ), + ( + "Invalid configuration", + { + "Definition": { + "StartAt": "SampleChoice", + "States": { + "NoType": {}, + "SampleChoice": { + "Default": "__SucceedEntryPoint__", + "Type": "Choice", + }, + "__SucceedEntryPoint__": {"Type": "Pass"}, + }, + } + }, + [ + ValidationError( + "'Type' is a required property", + rule=StateMachineDefinition(), + validator="required", + schema_path=deque( + [ + "properties", + "States", + "patternProperties", + "^.{1,128}$", + "required", + ] + ), + path=deque(["Definition", "States", "NoType"]), + ), + ValidationError( + "'Choices' is a required property", + rule=StateMachineDefinition(), + validator="required", + schema_path=deque( + [ + "properties", + "States", + "patternProperties", + "^.{1,128}$", + "allOf", + 0, + "then", + "required", + ] + ), + path=deque(["Definition", "States", "SampleChoice"]), + ), + ValidationError( + "Only one of ['Next', 'End'] is a required property", + rule=StateMachineDefinition(), + validator="requiredXor", + schema_path=deque( + [ + "properties", + "States", + "patternProperties", + "^.{1,128}$", + "allOf", + 3, + "then", + "requiredXor", + ] + ), + path=deque(["Definition", "States", "__SucceedEntryPoint__"]), + ), + ], + ), + ( + "Invalid string definition", + { + "Definition": """ + { + "States": { + "NoType": {} + } + } + """ + }, + [ + ValidationError( + "'Type' is a required property at 'States/NoType'", + rule=StateMachineDefinition(), + validator="required", + schema_path=deque( + [ + "properties", + "States", + "patternProperties", + "^.{1,128}$", + "required", + ] + ), + path=deque(["Definition", "States", "NoType"]), + ), + ValidationError( + "'StartAt' is a required property", + rule=StateMachineDefinition(), + validator="required", + schema_path=deque( + [ + "required", + ] + ), + path=deque(["Definition"]), + ), + ], + ), + ( + "Valid string json with definition substitution", + { + "DefinitionSubstitutions": {"jobqueue": {"Ref": "MyJob"}}, + "Definition": { + "Comment": ( + "An example of the Amazon States " + "Language for notification on an " + "AWS Batch job completion" + ), + "StartAt": "Submit Batch Job", + "TimeoutSeconds": 3600, + "States": { + "Submit Batch Job": { + "Type": "Task", + "Resource": "${jobqueue}", + "Parameters": { + "JobName": "BatchJobNotification", + "JobQueue": "arn:aws:batch:us-east-1:123456789012:job-queue/BatchJobQueue-7049d367474b4dd", + "JobDefinition": "arn:aws:batch:us-east-1:123456789012:job-definition/BatchJobDefinition-74d55ec34c4643c:1", + }, + "Next": "Notify Success", + "Catch": [ + { + "ErrorEquals": ["States.ALL"], + "Next": "Notify Failure", + } + ], + }, + "Notify Success": { + "Type": "Task", + "Resource": "${invalid}", + "Parameters": { + "Message": "Batch job submitted through Step Functions succeeded", + "TopicArn": "arn:aws:sns:us-east-1:123456789012:batchjobnotificatiointemplate-SNSTopic-1J757CVBQ2KHM", + }, + "End": True, + }, + "Notify Failure": { + "Type": "Task", + "Resource": [], + "Parameters": { + "Message": "Batch job submitted through Step Functions failed", + "TopicArn": "arn:aws:sns:us-east-1:123456789012:batchjobnotificatiointemplate-SNSTopic-1J757CVBQ2KHM", + }, + "End": True, + }, + }, + }, + }, + [ + ValidationError( + ( + "'${invalid}' does not match " + "'^arn:aws:([a-z]|-)+:([a-z]|[0-9]|-)*:[0-9]*:([a-z]|-)+:[a-zA-Z0-9-_.]+(:(\\\\$LATEST|[a-zA-Z0-9-_\\\\.]+))?$'" + ), + rule=StateMachineDefinition(), + validator="pattern", + schema_path=deque( + [ + "properties", + "States", + "patternProperties", + "^.{1,128}$", + "allOf", + 5, + "then", + "properties", + "Resource", + "pattern", + ] + ), + path=deque(["Definition", "States", "Notify Success", "Resource"]), + ), + ValidationError( + ("[] is not of type 'string'"), + rule=StateMachineDefinition(), + validator="type", + schema_path=deque( + [ + "properties", + "States", + "patternProperties", + "^.{1,128}$", + "allOf", + 5, + "then", + "properties", + "Resource", + "type", + ] + ), + path=deque(["Definition", "States", "Notify Failure", "Resource"]), + ), + ], + ), + ( + "Valid string json", + { + "DefinitionSubstitutions": "jobqueue", + "Definition": { + "Comment": ( + "An example of the Amazon States " + "Language for notification on an " + "AWS Batch job completion" + ), + "StartAt": "Submit Batch Job", + "TimeoutSeconds": 3600, + "States": { + "Submit Batch Job": { + "Type": "Task", + "Resource": "${jobqueue}", + "Parameters": { + "JobName": "BatchJobNotification", + "JobQueue": "arn:aws:batch:us-east-1:123456789012:job-queue/BatchJobQueue-7049d367474b4dd", + "JobDefinition": "arn:aws:batch:us-east-1:123456789012:job-definition/BatchJobDefinition-74d55ec34c4643c:1", + }, + "Next": "Notify Success", + "Catch": [ + { + "ErrorEquals": ["States.ALL"], + "Next": "Notify Failure", + } + ], + }, + "Notify Success": { + "Type": "Task", + "Resource": "arn:aws:states:::sns:publish", + "Parameters": { + "Message": "Batch job submitted through Step Functions succeeded", + "TopicArn": "arn:aws:sns:us-east-1:123456789012:batchjobnotificatiointemplate-SNSTopic-1J757CVBQ2KHM", + }, + "End": True, + }, + "Notify Failure": { + "Type": "Task", + "Resource": "arn:aws:states:::sns:publish", + "Parameters": { + "Message": "Batch job submitted through Step Functions failed", + "TopicArn": "arn:aws:sns:us-east-1:123456789012:batchjobnotificatiointemplate-SNSTopic-1J757CVBQ2KHM", + }, + "End": True, + }, + }, + }, + }, + [ + ValidationError( + ( + "'${jobqueue}' does not match " + "'^arn:aws:([a-z]|-)+:([a-z]|[0-9]|-)*:[0-9]*:([a-z]|-)+:[a-zA-Z0-9-_.]+(:(\\\\$LATEST|[a-zA-Z0-9-_\\\\.]+))?$'" + ), + rule=StateMachineDefinition(), + validator="pattern", + schema_path=deque( + [ + "properties", + "States", + "patternProperties", + "^.{1,128}$", + "allOf", + 5, + "then", + "properties", + "Resource", + "pattern", + ] + ), + path=deque( + ["Definition", "States", "Submit Batch Job", "Resource"] + ), + ), + ], + ), + ( + "Using a function", + {"Definition": {"Fn::Join": ["\n", []]}}, + [], + ), + ], +) +def test_validate( + name, + instance, + expected, + rule, + validator, +): + errs = list(rule.validate(validator, {}, instance, {})) + assert errs == expected, f"{name!r} test failed with {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_circular_dependency.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_circular_dependency.py new file mode 100644 index 0000000000000000000000000000000000000000..f939a4e39f4a75a6e326a3e9ea5ecba919a92251 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_circular_dependency.py @@ -0,0 +1,46 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.unit.rules import BaseRuleTestCase + +from cfnlint.rules.resources.CircularDependency import ( + CircularDependency, # pylint: disable=E0401 +) + + +class TestRulesRefCircular(BaseRuleTestCase): + """Test Rules Get Att""" + + def setUp(self): + """Setup""" + super(TestRulesRefCircular, self).setUp() + self.collection.register(CircularDependency()) + + def test_file_positive(self): + """Test Positive""" + self.helper_file_positive() + + def test_file_negative(self): + """Test failure""" + err_count = 6 + self.helper_file_negative( + "test/fixtures/templates/bad/resources_circular_dependency.yaml", err_count + ) + + def test_file_negative_fngetatt(self): + """Test failure""" + err_count = 9 + self.helper_file_negative( + "test/fixtures/templates/bad/resources_circular_dependency_2.yaml", + err_count, + ) + + def test_file_negative_dependson(self): + """Test failure with DependsOn""" + err_count = 2 + self.helper_file_negative( + "test/fixtures/templates/bad/resources_circular_dependency_dependson.yaml", + err_count, + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_configurations.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_configurations.py new file mode 100644 index 0000000000000000000000000000000000000000..e207f21d9e0c3df0445d2d64d9899357603ebe75 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_configurations.py @@ -0,0 +1,76 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque +from test.unit.rules import BaseRuleTestCase + +from cfnlint.jsonschema import CfnTemplateValidator, ValidationError +from cfnlint.rules.resources.Configuration import Configuration + + +class TestResourceConfiguration(BaseRuleTestCase): + """Test AWS Types""" + + def setUp(self): + """Setup""" + super(TestResourceConfiguration, self).setUp() + self.rule = Configuration() + + def test_configurations(self): + validator = CfnTemplateValidator({}) + errors = list( + self.rule.validate(validator, "cfnResources", {"foo": {"Type": "bar"}}, {}) + ) + self.assertListEqual( + errors, + [], + errors, + ) + + errors = list(self.rule.validate(validator, "cfnResources", {"foo": []}, {})) + + self.assertListEqual( + errors, + [ + ValidationError( + "[] is not of type 'object'", + rule=Configuration(), + path=deque(["foo"]), + schema_path=deque(["patternProperties", "^[a-zA-Z0-9]+$", "type"]), + validator="type", + validator_value="object", + instance=[], + ), + ], + errors, + ) + + errors = list( + self.rule.validate(validator, "cfnResources", {"foo": {"Type": []}}, {}) + ) + + self.assertListEqual( + errors, + [ + ValidationError( + "[] is not of type 'string'", + rule=Configuration(), + path=deque(["foo", "Type"]), + schema_path=deque( + [ + "patternProperties", + "^[a-zA-Z0-9]+$", + "properties", + "Type", + "type", + ] + ), + validator="type", + validator_value="string", + instance=[], + ), + ], + errors, + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_creationpolicy.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_creationpolicy.py new file mode 100644 index 0000000000000000000000000000000000000000..047d712fc786fd8842137a9975c8faf545404696 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_creationpolicy.py @@ -0,0 +1,180 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.CreationPolicy import CreationPolicy + + +@pytest.fixture +def rule(): + return CreationPolicy() + + +@pytest.fixture +def template(): + return { + "Resources": { + "MyInstance": { + "Type": "AWS::EC2::Instance", + }, + "MyWaitCondition": { + "Type": "AWS::CloudFormation::WaitCondition", + }, + "MyAutoScalingGroup": { + "Type": "AWS::AutoScaling::AutoScalingGroup", + }, + "MyAppStreamFleet": { + "Type": "AWS::AppStream::Fleet", + }, + "MyLambdaFunction": { + "Type": "AWS::Lambda::Function", + }, + } + } + + +@pytest.mark.parametrize( + "name, instance, path, expected", + [ + ( + "Correct for app stream", + {"StartFleet": {"Type": True}}, + { + "path": deque(["Resources", "MyAppStreamFleet", "CreationPolicy"]), + }, + [], + ), + ( + "Bad type for app stream", + { + "StartFleet": { + "Type": {}, + } + }, + { + "path": deque(["Resources", "MyAppStreamFleet", "CreationPolicy"]), + }, + [ + ValidationError( + "{} is not of type 'boolean'", + rule=CreationPolicy(), + path=deque(["StartFleet", "Type"]), + schema_path=deque( + ["properties", "StartFleet", "properties", "Type", "type"] + ), + validator="type", + ) + ], + ), + ( + "Valid ASG", + { + "AutoScalingCreationPolicy": {"MinSuccessfulInstancesPercent": 100}, + "ResourceSignal": {"Count": 1, "Timeout": "60"}, + }, + { + "path": deque(["Resources", "MyAutoScalingGroup", "CreationPolicy"]), + }, + [], + ), + ( + "Invalid ASG", + { + "AutoScalingCreationPolicy": {"MinSuccessfulInstancesPercent": 100}, + "ResourceSignal": {"Count": "one", "Timeout": "60"}, + }, + { + "path": deque(["Resources", "MyAutoScalingGroup", "CreationPolicy"]), + }, + [ + ValidationError( + "'one' is not of type 'integer'", + rule=CreationPolicy(), + path=deque(["ResourceSignal", "Count"]), + schema_path=deque( + ["properties", "ResourceSignal", "properties", "Count", "type"] + ), + validator="type", + ) + ], + ), + ( + "Valid Wait Condition", + {"ResourceSignal": {"Timeout": "PT15M", "Count": "5"}}, + { + "path": deque(["Resources", "MyWaitCondition", "CreationPolicy"]), + }, + [], + ), + ( + "Invalid Wait Condition", + {"ResourceSignal": {"Timeout": "PT15M", "Count": "five"}}, + { + "path": deque(["Resources", "MyWaitCondition", "CreationPolicy"]), + }, + [ + ValidationError( + "'five' is not of type 'integer'", + rule=CreationPolicy(), + path=deque(["ResourceSignal", "Count"]), + schema_path=deque( + ["properties", "ResourceSignal", "properties", "Count", "type"] + ), + validator="type", + ) + ], + ), + ( + "Valid instance", + {"ResourceSignal": {"Timeout": "PT15M", "Count": "5"}}, + { + "path": deque(["Resources", "MyWaitCondition", "CreationPolicy"]), + }, + [], + ), + ( + "Invalid Instance", + {"Foo": {"Bar"}}, + { + "path": deque(["Resources", "MyInstance", "CreationPolicy"]), + }, + [], + ), + ( + "Wait condition ignored on wrong type", + {"Foo": {"Bar"}}, + { + "path": deque(["Resources", "MyLambdaFunction", "CreationPolicy"]), + }, + [], + ), + ( + "Invalid but integer name ", + {"ResourceSignal": {"Timeout": "PT15M", "Count": "five"}}, + { + "path": deque(["Resources", 1, "CreationPolicy"]), + }, + [], + ), + ], + indirect=["path"], +) +def test_deletion_policy(name, instance, expected, rule, validator): + + rule = CreationPolicy() + errors = list( + rule.validate( + validator=validator, + dP="creationpolicy", + instance=instance, + schema={}, + ) + ) + + assert errors == expected, f"{name}: {errors} != {expected}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_deletionpolicy.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_deletionpolicy.py new file mode 100644 index 0000000000000000000000000000000000000000..ff23f7ae28a5f1cd6d230e03470c3eb2bc0858d8 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_deletionpolicy.py @@ -0,0 +1,88 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.context import Context, Path +from cfnlint.context.context import Parameter, Resource +from cfnlint.jsonschema import CfnTemplateValidator, ValidationError +from cfnlint.rules.resources.DeletionPolicy import DeletionPolicy + + +@pytest.mark.parametrize( + "name, instance, path, expected", + [ + ("Correct type", "Snapshot", deque(["Resources", "MyVolume"]), []), + ( + "Incorrect type", + {"Foo": "Bar"}, + deque(["Resources", "MyVolume"]), + [ + ValidationError( + "{'Foo': 'Bar'} is not of type 'string'", + schema_path=deque(["type"]), + validator="type", + rule=DeletionPolicy(), + ), + ValidationError( + ( + "{'Foo': 'Bar'} is not one of ['Delete', 'Retain', " + "'RetainExceptOnCreate', 'Snapshot']" + ), + schema_path=deque(["enum"]), + validator="enum", + rule=DeletionPolicy(), + ), + ], + ), + ( + "Snapshot not supported", + "Snapshot", + deque(["Resources", "MyInstance"]), + [ + ValidationError( + ( + "'Snapshot' is not one of ['Delete', 'Retain', " + "'RetainExceptOnCreate']" + ), + schema_path=deque(["enum"]), + validator="enum", + rule=DeletionPolicy(), + ), + ], + ), + ( + "Success on a valid function", + {"Ref": "MyParameter"}, + deque(["Resources", "MyInstance"]), + [], + ), + ], +) +def test_deletion_policy(name, instance, path, expected): + context = Context( + regions=["us-east-1"], + path=Path(path=path), + resources={ + "MyVolume": Resource({"Type": "AWS::EC2::Volume"}), + "MyInstance": Resource({"Type": "AWS::EC2::Instance"}), + }, + parameters={"MyParameter": Parameter({"Type": "String"})}, + ) + validator = CfnTemplateValidator(context=context) + + rule = DeletionPolicy() + errors = list( + rule.validate( + validator=validator, + dP="deletionpolicy", + instance=instance, + schema={}, + ) + ) + + assert errors == expected diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_deletionpolicy_stateful_resources.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_deletionpolicy_stateful_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..1d78bb599ece5ee86aaa41f2aa88c6e71c4e8c72 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_deletionpolicy_stateful_resources.py @@ -0,0 +1,81 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError + +# ruff: noqa: E501 +from cfnlint.rules.resources.UpdateReplacePolicyDeletionPolicyOnStatefulResourceTypes import ( + UpdateReplacePolicyDeletionPolicyOnStatefulResourceTypes, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = UpdateReplacePolicyDeletionPolicyOnStatefulResourceTypes() + yield rule + + +@pytest.mark.parametrize( + "instance,expected", + [ + ( + { + "Type": "AWS::EC2::VPC", + }, + [], + ), + ( + { + "Type": ["AWS::EC2::VPC"], + }, + [], + ), + ( + { + "Type": "AWS::SQS::Queue", + "DeletionPolicy": "Foo", + "UpdateReplacePolicy": "Foo", + }, + [], + ), + ( + { + "Type": "AWS::SQS::Queue", + }, + [ + ValidationError( + ( + "'DeletionPolicy' is a required property (The default " + "action when replacing/removing a resource is to delete " + "it. Set explicit values for stateful resource)" + ), + rule=UpdateReplacePolicyDeletionPolicyOnStatefulResourceTypes(), + path=deque([]), + validator="required", + schema_path=deque(["required"]), + ), + ValidationError( + ( + "'UpdateReplacePolicy' is a required property (The default " + "action when replacing/removing a resource is to delete " + "it. Set explicit values for stateful resource)" + ), + rule=UpdateReplacePolicyDeletionPolicyOnStatefulResourceTypes(), + path=deque([]), + validator="required", + schema_path=deque(["required"]), + ), + ], + ), + ], +) +def test_validate(instance, expected, rule, validator): + errs = list(rule.validate(validator, "", instance, {})) + + assert errs == expected, f"Expected {expected} got {errs}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_dependson.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_dependson.py new file mode 100644 index 0000000000000000000000000000000000000000..d4aaec466c0d9c819fb334206ca2906c27c221ca --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_dependson.py @@ -0,0 +1,162 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.context import Path +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.DependsOn import DependsOn # noqa: E501 + + +@pytest.fixture(scope="module") +def rule(): + rule = DependsOn() + yield rule + + +@pytest.fixture +def template(): + return { + "Conditions": { + "IsUsEast1": { + "Fn::Equals": [ + {"Ref": "AWS::Region"}, + "us-east-1", + ] + } + }, + "Resources": { + "ParentBucket": { + "Type": "AWS::S3::Bucket", + }, + "ChildBucket": { + "Type": "AWS::S3::Bucket", + "DependsOn": "ParentBucket", + }, + "ParentBucketWithGoodCondition": { + "Condition": "IsUsEast1", + "Type": "AWS::S3::Bucket", + }, + "ChildBucketWithGoodCondition": { + "Condition": "IsUsEast1", + "DependsOn": "ParentBucketWithGoodCondition", + }, + "ParentBucketWithBadCondition": { + "Condition": "IsUsEast1", + "Type": "AWS::S3::Bucket", + }, + "ChildBucketWithBadCondition": { + "Type": "AWS::S3::Bucket", + "DependsOn": "ParentBucketWithBadCondition", + }, + "ToMySelf": { + "Type": "AWS::S3::Bucket", + "DependsOn": "ToMySelf", + }, + }, + } + + +@pytest.mark.parametrize( + "name,instance,path,expected", + [ + ( + "Valid depends on", + "ParentBucket", + deque(["Resources", "ChildBucket", "DependsOn"]), + [], + ), + ( + "Invalid depends on but low path", + "Foo", + deque([]), + [ + ValidationError( + ( + "'Foo' is not one of ['ParentBucket', " + "'ChildBucket', " + "'ParentBucketWithGoodCondition', " + "'ParentBucketWithBadCondition', " + "'ChildBucketWithBadCondition', 'ToMySelf']" + ), + ) + ], + ), + ( + "Valid depends on with conditions", + "ParentBucketWithGoodCondition", + deque(["Resources", "ChildBucketWithGoodCondition", "DependsOn"]), + [], + ), + ( + "Invalid type isn't validated by this rule", + {"Ref": "MyResource"}, + deque(["Resources", "ChildBucket", "DependsOn"]), + [], + ), + ( + "Invalid depends on", + "Foo", + deque(["Resources", "ChildBucket", "DependsOn"]), + [ + ValidationError( + ( + "'Foo' is not one of ['ParentBucket', " + "'ParentBucketWithGoodCondition', " + "'ParentBucketWithBadCondition', " + "'ChildBucketWithBadCondition', 'ToMySelf']" + ), + ) + ], + ), + ( + "Invalid depends on with conditions", + "ParentBucketWithBadCondition", + deque(["Resources", "ChildBucketWithBadCondition", "DependsOn"]), + [ + ValidationError( + ( + "'ParentBucketWithBadCondition' will not exist when condition " + "'IsUsEast1' is False" + ), + ) + ], + ), + ( + "Invalid depends on relying on itself", + "ToMySelf", + deque(["Resources", "ToMySelf", "DependsOn"]), + [ + ValidationError( + ( + "'ToMySelf' is not one of ['ParentBucket', 'ChildBucket', " + "'ParentBucketWithGoodCondition', " + "'ParentBucketWithBadCondition', 'ChildBucketWithBadCondition']" + ), + ) + ], + ), + ], +) +def test_validate(name, instance, path, expected, rule, validator): + + validator = validator.evolve(context=validator.context.evolve(path=Path(path))) + errs = list(rule.validate(validator, False, instance, {})) + + assert errs == expected, f"Test {name!r} got {errs!r}" + + +def test_validate_with_no_cfn(rule, validator): + validator = validator.evolve( + context=validator.context.evolve( + path=Path(path=deque(["Resources", "ChildBucket", "DependsOn"])) + ) + ) + validator.cfn = None + errs = list(rule.validate(validator, False, "ParentBucketWithBadCondition", {})) + + assert errs == [], f"Test without cfn got {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_dependson_obsolete.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_dependson_obsolete.py new file mode 100644 index 0000000000000000000000000000000000000000..ccc0c777da75025a43626bb899785c1ed88fc298 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_dependson_obsolete.py @@ -0,0 +1,97 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.context import Path +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.DependsOnObsolete import DependsOnObsolete + + +@pytest.fixture(scope="module") +def rule(): + rule = DependsOnObsolete() + yield rule + + +@pytest.fixture +def template(): + return { + "Resources": { + "Parent1Bucket": { + "Type": "AWS::S3::Bucket", + }, + "Parent2Bucket": { + "Type": "AWS::S3::Bucket", + }, + "ChildBucket": { + "Type": "AWS::S3::Bucket", + "Properties": { + "BucketName": {"Ref": "Parent1Bucket"}, + }, + }, + }, + } + + +@pytest.fixture +def path(): + return Path( + path=deque(["Resources", "ChildBucket", "DependsOn"]), + ) + + +@pytest.mark.parametrize( + "name,instance,expected", + [ + ( + "Valid depends on", + "Parent2Bucket", + [], + ), + ( + "Valid but wrong type", + {}, + [], + ), + ( + "Obsolete depends on", + "Parent1Bucket", + [ + ValidationError( + ( + "'Parent1Bucket' dependency already " + "enforced by a 'Ref' at " + "'Resources/ChildBucket/Properties/BucketName'" + ), + ) + ], + ), + ], +) +def test_validate(name, instance, expected, rule, validator): + errs = list(rule.validate(validator, False, instance, {})) + + assert errs == expected, f"Test {name!r} got {errs!r}" + + +@pytest.mark.parametrize( + "name,instance,expected", + [ + ( + "Obsolete depends on", + "Parent1Bucket", + [], + ), + ], +) +def test_validate_no_cfn_graph(name, instance, expected, rule, validator): + + validator.cfn.graph = None + errs = list(rule.validate(validator, False, instance, {})) + + assert errs == expected, f"Test {name!r} got {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_hardcodedarnproperties.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_hardcodedarnproperties.py new file mode 100644 index 0000000000000000000000000000000000000000..2e2663d347c55d9ed949217dc7fd3a8d77906fdd --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_hardcodedarnproperties.py @@ -0,0 +1,109 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.unit.rules import BaseRuleTestCase + +from cfnlint import ConfigMixIn +from cfnlint.rules.resources.HardCodedArnProperties import ( + HardCodedArnProperties, # pylint: disable=E0401 +) + + +class TestHardCodedArnProperties(BaseRuleTestCase): + """Test template parameter configurations""" + + def setUp(self): + """Setup""" + super(TestHardCodedArnProperties, self).setUp() + self.collection.register(HardCodedArnProperties()) + self.success_templates = [ + "test/fixtures/templates/good/resources/properties/hard_coded_arn_properties.yaml", + "test/fixtures/templates/good/resources/properties/hard_coded_arn_properties_sam.yaml", + ] + + def test_file_positive(self): + """Test Positive""" + # By default, a set of "correct" templates are checked + self.helper_file_positive() + + def test_file_positive_with_config(self): + self.helper_file_negative( + "test/fixtures/templates/good/resources/properties/hard_coded_arn_properties.yaml", + 0, + ConfigMixIn( + [], + include_experimental=True, + include_checks=[ + "I", + ], + configure_rules={ + "I3042": { + "partition": True, + "region": True, + "accountId": True, + } + }, + ), + ) + + def test_file_negative_partition(self): + self.helper_file_negative( + "test/fixtures/templates/bad/hard_coded_arn_properties.yaml", + 2, + ConfigMixIn( + [], + include_experimental=True, + include_checks=[ + "I", + ], + configure_rules={ + "I3042": { + "partition": True, + "region": False, + "accountId": False, + } + }, + ), + ) + + def test_file_negative_region(self): + self.helper_file_negative( + "test/fixtures/templates/bad/hard_coded_arn_properties.yaml", + 4, + ConfigMixIn( + [], + include_experimental=True, + include_checks=[ + "I", + ], + configure_rules={ + "I3042": { + "partition": False, + "region": True, + "accountId": False, + } + }, + ), + ) + + def test_file_negative_accountid(self): + self.helper_file_negative( + "test/fixtures/templates/bad/hard_coded_arn_properties.yaml", + 1, + ConfigMixIn( + [], + include_experimental=True, + include_checks=[ + "I", + ], + configure_rules={ + "I3042": { + "partition": False, + "region": False, + "accountId": True, + } + }, + ), + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_modules.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..40c84bc06c0e73e145d1fdf34dc508605a004bbb --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_modules.py @@ -0,0 +1,46 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.unit.rules import BaseRuleTestCase + +from cfnlint.rules.resources.Modules import Modules + + +class TestModules(BaseRuleTestCase): + def setUp(self): + """Setup""" + super(TestModules, self).setUp() + self.collection.register(Modules()) + self.success_templates = [ + "test/fixtures/templates/good/modules/minimal.yaml", + ] + + def test_file_positive(self): + """Test Positive""" + self.helper_file_positive() + + def test_cannot_have_update_policy(self): + """Test failure""" + self.helper_file_negative( + "test/fixtures/templates/bad/modules/bad_has_update_policy.yaml", 1 + ) + + def test_cannot_have_create_policy(self): + """Test failure""" + self.helper_file_negative( + "test/fixtures/templates/bad/modules/bad_has_create_policy.yaml", 1 + ) + + def test_cannot_use_special_metadata_keyword(self): + """Test failure""" + self.helper_file_negative( + "test/fixtures/templates/bad/modules/bad_uses_module_metadata.yaml", 1 + ) + + def test_cannot_use_tags(self): + """Test failure""" + self.helper_file_negative( + "test/fixtures/templates/bad/modules/bad_has_tags.yaml", 1 + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_previous_generation_instance_type.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_previous_generation_instance_type.py new file mode 100644 index 0000000000000000000000000000000000000000..53f6cf82f02b2b6fb2c710eb6fa267a2bb4445fa --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_previous_generation_instance_type.py @@ -0,0 +1,24 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.unit.rules import BaseRuleTestCase + +from cfnlint.rules.resources.PreviousGenerationInstanceType import ( + PreviousGenerationInstanceType, # pylint: disable=E0401 +) + + +class TestPreviousGenerationInstanceType(BaseRuleTestCase): + def setUp(self): + super(TestPreviousGenerationInstanceType, self).setUp() + self.collection.register(PreviousGenerationInstanceType()) + + def test_file_positive(self): + self.helper_file_positive() + + def test_file_negative(self): + self.helper_file_negative( + "test/fixtures/templates/bad/previous_generation_instances.yaml", 4 + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_retentionperiod_rds.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_retentionperiod_rds.py new file mode 100644 index 0000000000000000000000000000000000000000..85e5d6f4863bc18f64466e59ac03f3968278ec1a --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_retentionperiod_rds.py @@ -0,0 +1,80 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.context import Path +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.RetentionPeriodOnResourceTypesWithAutoExpiringContent import ( # noqa: E501 + RetentionPeriodOnResourceTypesWithAutoExpiringContent, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = RetentionPeriodOnResourceTypesWithAutoExpiringContent() + yield rule + + +@pytest.fixture +def template(): + return { + "Resources": { + "MyRdsDbInstance": { + "Type": "AWS::RDS::DBInstance", + } + } + } + + +@pytest.fixture +def path(): + return Path( + path=deque(["Resources", "MyRdsDbInstance", "Properties"]), + cfn_path=deque(["Resources", "AWS::RDS::DBInstance", "Properties"]), + ) + + +@pytest.mark.parametrize( + "name,instance,expected", + [ + ( + "Valid retention period", + {"MessageRetentionPeriod": "90"}, + [], + ), + ( + "Valid with SourceDBInstanceIdentifier", + {"SourceDBInstanceIdentifier": "source-db"}, + [], + ), + ( + "Invalid when not specified", + { + "Engine": "mysql", + }, + [ + ValidationError( + ( + "'BackupRetentionPeriod' is a required property (The " + "default retention period will delete the data after " + "a pre-defined time. Set an explicit values to avoid " + "data loss on resource)" + ), + rule=RetentionPeriodOnResourceTypesWithAutoExpiringContent(), + schema_path=deque(["then", "required"]), + validator="required", + validator_value=["BackupRetentionPeriod"], + ) + ], + ), + ], +) +def test_validate(name, instance, expected, rule, validator): + errs = list(rule.validate(validator, False, instance, {})) + + assert errs == expected, f"Test {name!r} got {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_unique_names.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_unique_names.py new file mode 100644 index 0000000000000000000000000000000000000000..221da09d74e4eec63cbb3b5457837532f622bcf9 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_unique_names.py @@ -0,0 +1,22 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from test.unit.rules import BaseRuleTestCase + +from cfnlint.rules.resources.UniqueNames import UniqueNames # pylint: disable=E0401 + + +class TestUniqueNames(BaseRuleTestCase): + def setUp(self): + super(TestUniqueNames, self).setUp() + self.collection.register(UniqueNames()) + + def test_file_positive(self): + self.helper_file_positive() + + def test_file_negative(self): + self.helper_file_negative( + "test/fixtures/templates/bad/resources/uniqueNames.yaml", 1 + ) diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_updatereplacepolicy.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_updatereplacepolicy.py new file mode 100644 index 0000000000000000000000000000000000000000..66934254af60573848f6e99706a2d9ca9d289815 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/test_updatereplacepolicy.py @@ -0,0 +1,97 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.context import Context, Path +from cfnlint.context.context import Parameter, Resource +from cfnlint.jsonschema import CfnTemplateValidator, ValidationError +from cfnlint.rules.resources.UpdateReplacePolicy import UpdateReplacePolicy + + +@pytest.mark.parametrize( + "name, instance, path, expected", + [ + ("Correct type", "Snapshot", deque(["Resources", "MyVolume"]), []), + ( + "Incorrect type", + {"Foo": "Bar"}, + deque(["Resources", "MyVolume"]), + [ + ValidationError( + "{'Foo': 'Bar'} is not of type 'string'", + schema_path=deque(["type"]), + validator="type", + validator_value="string", + rule=UpdateReplacePolicy(), + ), + ValidationError( + "{'Foo': 'Bar'} is not one of ['Delete', 'Retain', 'Snapshot']", + schema_path=deque(["enum"]), + validator="enum", + validator_value=[ + "Delete", + "Retain", + "Snapshot", + ], + rule=UpdateReplacePolicy(), + ), + ], + ), + ( + "Snapshot not supported", + "Snapshot", + deque(["Resources", "MyInstance"]), + [ + ValidationError( + "'Snapshot' is not one of ['Delete', 'Retain']", + schema_path=deque(["enum"]), + validator="enum", + validator_value=[ + "Delete", + "Retain", + ], + rule=UpdateReplacePolicy(), + ), + ], + ), + ( + "Success on a valid function", + {"Ref": "MyParameter"}, + deque(["Resources", "MyInstance"]), + [], + ), + ], +) +def test_deletion_policy(name, instance, path, expected): + context = Context( + regions=["us-east-1"], + path=Path(path=path), + resources={ + "MyVolume": Resource({"Type": "AWS::EC2::Volume"}), + "MyInstance": Resource({"Type": "AWS::EC2::Instance"}), + }, + parameters={"MyParameter": Parameter({"Type": "String"})}, + ) + validator = CfnTemplateValidator(context=context) + + rule = UpdateReplacePolicy() + errors = list( + rule.validate( + validator=validator, + dP="deletionpolicy", + instance=instance, + schema={ + "awsType": "cfnresourceupdatereplacepolicy", + }, + ) + ) + + assert len(errors) == len(expected), name + for i, error in enumerate(expected): + error.instance = instance + assert errors[i] == error, name diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/updatepolicy/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/updatepolicy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58049dc7358b55e33e093a8f6bb86d81121b78c --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/updatepolicy/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/updatepolicy/test_configuration.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/updatepolicy/test_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..7bf9d39e4f61f050fd664a0a7b5fe821c5cfa476 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/resources/updatepolicy/test_configuration.py @@ -0,0 +1,129 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.resources.updatepolicy.Configuration import Configuration + + +@pytest.fixture(scope="module") +def rule(): + rule = Configuration() + yield rule + + +@pytest.mark.parametrize( + "name,instance,expected", + [ + ("Valid with a non updatable type", {"Type": "AWS::Foo::Bar"}, []), + ( + "Invalid with autoscaling group wrong type", + {"Type": "AWS::AutoScaling::AutoScalingGroup", "UpdatePolicy": []}, + [ + ValidationError( + "[] is not of type 'object'", + path=["UpdatePolicy"], + rule=Configuration(), + instance=[], + validator="type", + validator_value="object", + schema_path=[ + "allOf", + 0, + "then", + "properties", + "UpdatePolicy", + "type", + ], + ) + ], + ), + ( + "Invalid with autoscaling group wrong property", + { + "Type": "AWS::AutoScaling::AutoScalingGroup", + "UpdatePolicy": {"Foo": "Bar"}, + }, + [ + ValidationError( + "Additional properties are not allowed ('Foo' was unexpected)", + path=["UpdatePolicy", "Foo"], + rule=Configuration(), + instance={"Foo": "Bar"}, + validator="additionalProperties", + validator_value=False, + schema_path=[ + "allOf", + 0, + "then", + "properties", + "UpdatePolicy", + "additionalProperties", + ], + ) + ], + ), + ( + "Valid with autoscaling group", + { + "Type": "AWS::AutoScaling::AutoScalingGroup", + "UpdatePolicy": { + "AutoScalingReplacingUpdate": { + "WillReplace": True, + }, + "AutoScalingRollingUpdate": { + "MaxBatchSize": 1, + "MinInstancesInService": "1", # also allows strings + "MinSuccessfulInstancesPercent": 100, + "PauseTime": "PT1M", + "WaitOnResourceSignals": True, + "SuspendProcesses": ["AZRebalance"], + }, + "AutoScalingScheduledAction": { + "IgnoreUnmodifiedGroupSizeProperties": True, + }, + }, + }, + [], + ), + ( + "Valid with lambda function", + { + "Type": "AWS::Lambda::Alias", + "UpdatePolicy": { + "CodeDeployLambdaAliasUpdate": { + "AfterAllowTrafficHook": "Foo", + "ApplicationName": "Foo", + "BeforeAllowTrafficHook": "Foo", + "DeploymentGroupName": "Foo", + } + }, + }, + [], + ), + ( + "Valid with search resource", + { + "Type": "AWS::Elasticsearch::Domain", + "UpdatePolicy": { + "EnableVersionUpgrade": True, + }, + }, + [], + ), + ( + "Valid with ElastiCache resource", + { + "Type": "AWS::ElastiCache::ReplicationGroup", + "UpdatePolicy": {"UseOnlineResharding": True}, + }, + [], + ), + ], +) +def test_update_policy_configuration(name, instance, expected, rule, validator): + errors = list(rule.validate(validator, {}, instance, {})) + assert errors == expected, f"Test {name!r} got {errors!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/rules/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/rules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/rules/test_configuration.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/rules/test_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..793b09d48101dde2d67207074ef407ff6134dd7f --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/rules/test_configuration.py @@ -0,0 +1,95 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from collections import deque + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.rules.Configuration import Configuration + + +@pytest.fixture(scope="module") +def rule(): + rule = Configuration() + yield rule + + +@pytest.mark.parametrize( + "name,instance,expected", + [ + ( + "Empty is okay", + {}, + [], + ), + ( + "wrong type", + [], + [ + ValidationError( + "[] is not of type 'object'", + validator="type", + schema_path=deque(["type"]), + rule=Configuration(), + ) + ], + ), + ( + "Wrong type of rule", + { + "Rule1": [], + }, + [ + ValidationError( + "[] is not of type 'object'", + validator="type", + schema_path=deque(["patternProperties", "^[A-Za-z0-9]+$", "type"]), + path=deque(["Rule1"]), + rule=Configuration(), + ) + ], + ), + ( + "Empty rule", + { + "Rule1": {}, + }, + [ + ValidationError( + "'Assertions' is a required property", + validator="required", + schema_path=deque( + ["patternProperties", "^[A-Za-z0-9]+$", "required"] + ), + path=deque(["Rule1"]), + rule=Configuration(), + ) + ], + ), + ( + "Valid rule with RuleCondition and Assertions", + { + "Rule1": { + "RuleCondition": {"Fn::Equals": ["a", "b"]}, + "Assertions": [ + { + "Assert": {"Fn::Equals": ["a", "b"]}, + "AssertDescription": "a is equal to b", + }, + { + "Assert": {"Fn::Equals": ["a", "b"]}, + }, + ], + }, + }, + [], + ), + ], +) +def test_validate(name, instance, expected, rule, validator): + errs = list(rule.validate(validator, {}, instance, {})) + + assert errs == expected, f"Test {name!r} got {errs!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/templates/test_limitsize_description_approaching.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/templates/test_limitsize_description_approaching.py new file mode 100644 index 0000000000000000000000000000000000000000..5e30e742d13ffab81a7f4a17580f2e318d138819 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/templates/test_limitsize_description_approaching.py @@ -0,0 +1,43 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +import pytest + +from cfnlint.jsonschema import ValidationError +from cfnlint.rules.templates.ApproachingLimitDescription import ( + ApproachingLimitDescription, +) + + +@pytest.fixture(scope="module") +def rule(): + rule = ApproachingLimitDescription() + yield rule + + +@pytest.mark.parametrize( + "name,instance,expected", + [ + ( + "Valid description", + "a" * 18, + [], + ), + ( + "Too long", + "a" * 19, + [ + ValidationError( + f"'{'a'*19}' is approaching the max length of 20", + rule=ApproachingLimitDescription(), + ) + ], + ), + ], +) +def test_validate(name, instance, expected, rule, validator): + errors = list(rule.maxLength(validator, 20, instance, {})) + + assert errors == expected, f"Test {name!r} got {errors!r}" diff --git a/testbed/aws-cloudformation__cfn-lint/test/unit/rules/transforms/__init__.py b/testbed/aws-cloudformation__cfn-lint/test/unit/rules/transforms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-cloudformation__cfn-lint/tox.ini b/testbed/aws-cloudformation__cfn-lint/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6489cccf49408c69385bc6fef40806a3c5f97127 --- /dev/null +++ b/testbed/aws-cloudformation__cfn-lint/tox.ini @@ -0,0 +1,19 @@ +[tox] +envlist = py{38,39,310,311,312,313},style +isolated_build = true + +[testenv] +skip_install = True +commands = + pip install -e .[full] + coverage run -m pytest {posargs:test} + coverage xml +deps = + pytest + coverage>=7.2.1 + coverage[toml] + pydot + defusedxml +setenv = + LANG=en_US.UTF-8 + AWS_DEFAULT_REGION=us-east-1 diff --git a/testbed/aws-powertools__powertools-lambda-python/.chglog/CHANGELOG.tpl.md b/testbed/aws-powertools__powertools-lambda-python/.chglog/CHANGELOG.tpl.md new file mode 100644 index 0000000000000000000000000000000000000000..beb340ad6455b6621c46ae1999741f3c7fbaa2d1 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.chglog/CHANGELOG.tpl.md @@ -0,0 +1,67 @@ + + + +{{ if .Versions -}} + +# Unreleased + +{{ if .Unreleased.CommitGroups -}} +{{ range .Unreleased.CommitGroups -}} +## {{ .Title }} + +{{ range .Commits -}} +{{ if and (not (hasPrefix .Subject "changelog rebuild")) (not (hasPrefix .Subject "layer docs update")) (not (hasPrefix .Subject "bump version to")) -}} +* {{ if .Scope }}**{{ .Scope }}:** {{ end }}{{ .Subject }} +{{ end -}} +{{ end }} +{{ end -}} +{{ end -}} +{{ end -}} + +{{ range .Versions }} + +## {{ if .Tag.Previous }}[{{ .Tag.Name }}]{{ else }}{{ .Tag.Name }}{{ end }} - {{ datetime "2006-01-02" .Tag.Date }} +{{ range .CommitGroups -}} + +## {{ .Title }} + +{{ range .Commits -}} +{{ if and (not (hasPrefix .Subject "changelog rebuild")) (not (hasPrefix .Subject "layer docs update")) (not (hasPrefix .Subject "bump version to")) -}} +* {{ if .Scope }}**{{ .Scope }}:** {{ end }}{{ .Subject }} +{{ end -}} +{{ end }} +{{ end -}} + +{{- if .RevertCommits -}} +## Reverts +{{ range .RevertCommits -}} +* {{ .Revert.Header }} +{{ end }} +{{ end -}} + +{{- if .MergeCommits -}} +## Pull Requests + +{{ range .MergeCommits -}} +* {{ .Header }} +{{ end }} +{{ end -}} + +{{- if .NoteGroups -}} +{{ range .NoteGroups -}} +## {{ .Title }} +{{ range .Notes }} +{{ .Body }} +{{ end }} +{{ end -}} +{{ end -}} +{{ end -}} + +{{- if .Versions }} +[Unreleased]: {{ .Info.RepositoryURL }}/compare/{{ $latest := index .Versions 0 }}{{ $latest.Tag.Name }}...HEAD +{{ range .Versions -}} +{{ if .Tag.Previous -}} +[{{ .Tag.Name }}]: {{ $.Info.RepositoryURL }}/compare/{{ .Tag.Previous.Name }}...{{ .Tag.Name }} +{{ end -}} +{{ end -}} +{{ end -}} diff --git a/testbed/aws-powertools__powertools-lambda-python/.chglog/config.yml b/testbed/aws-powertools__powertools-lambda-python/.chglog/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..9ec1c8ef31e1edc212acaf9c2c2d5e7cc805791f --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.chglog/config.yml @@ -0,0 +1,37 @@ +style: github +template: CHANGELOG.tpl.md +info: + title: CHANGELOG + repository_url: https://github.com/aws-powertools/powertools-lambda-python +options: + commits: + filters: + Type: + - feat + - fix + - perf + - refactor + - docs + - chore + - revert + commit_groups: + title_maps: + feat: Features + fix: Bug Fixes + perf: Performance Improvements + refactor: Code Refactoring + docs: Documentation + chore: Maintenance + revert: Regression + header: + pattern: "^(\\w*)(?:\\(([\\w\\$\\.\\-\\*\\s]*)\\))?\\:\\s(.*)$" + pattern_maps: + - Type + - Scope + - Subject + notes: + keywords: + - BREAKING CHANGE + # issues: + # prefix: + # - # diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/CODEOWNERS b/testbed/aws-powertools__powertools-lambda-python/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..1062320f5b16c288b628c0e69190129a116a6598 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/CODEOWNERS @@ -0,0 +1,3 @@ +# https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners + +* @aws-powertools/lambda-python-core diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/bug_report.yml b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000000000000000000000000000000000000..3ca04a2bca40b1a3fb8e11834d43278968661954 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,93 @@ +name: Bug report +description: Report a reproducible bug to help us improve +title: "Bug: TITLE" +labels: ["bug", "triage"] +body: + - type: markdown + attributes: + value: | + Thank you for submitting a bug report. Please add as much information as possible to help us reproduce, and remove any potential sensitive data. + + Please become familiar with [our definition of bug](https://github.com/aws-powertools/powertools-lambda-python/blob/develop/MAINTAINERS.md#is-that-a-bug). + - type: textarea + id: expected_behaviour + attributes: + label: Expected Behaviour + description: Please share details on the behaviour you expected + validations: + required: true + - type: textarea + id: current_behaviour + attributes: + label: Current Behaviour + description: Please share details on the current issue + validations: + required: true + - type: textarea + id: code_snippet + attributes: + label: Code snippet + description: Please share a code snippet to help us reproduce the issue + render: python + validations: + required: true + - type: textarea + id: solution + attributes: + label: Possible Solution + description: If known, please suggest a potential resolution + validations: + required: false + - type: textarea + id: steps + attributes: + label: Steps to Reproduce + description: Please share how we might be able to reproduce this issue + validations: + required: true + - type: input + id: version + attributes: + label: Powertools for AWS Lambda (Python) version + placeholder: "latest, 1.25.6" + value: latest + validations: + required: true + - type: dropdown + id: runtime + attributes: + label: AWS Lambda function runtime + options: + - "3.8" + - "3.9" + - "3.10" + - "3.11" + - "3.12" + - "3.13" + validations: + required: true + - type: dropdown + id: packaging + attributes: + label: Packaging format used + options: + - Lambda Layers + - Serverless Application Repository (SAR) App + - PyPi + multiple: true + validations: + required: true + - type: textarea + id: logs + attributes: + label: Debugging logs + description: If available, please share [debugging logs](https://docs.powertools.aws.dev/lambda/python/#debug-mode) + render: python + validations: + required: false + - type: markdown + attributes: + value: | + --- + + **Disclaimer**: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful. diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/config.yml b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..8acf5081f3b58ced0f8f5a02e5db194cf0edbace --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Ask a question + url: https://github.com/aws-powertools/powertools-lambda-python/discussions/new + about: Ask a general question about Lambda Powertools diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/documentation_improvements.yml b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/documentation_improvements.yml new file mode 100644 index 0000000000000000000000000000000000000000..e750d51923f39c1e639555e599173b025f9e136d --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/documentation_improvements.yml @@ -0,0 +1,50 @@ +name: Documentation improvements +description: Suggest a documentation update to improve everyone's experience +title: "Docs: TITLE" +labels: ["documentation", "triage"] +body: + - type: markdown + attributes: + value: | + Thank you for helping us improve everyone's experience. We review documentation updates on a case by case basis. + - type: textarea + id: search_area + attributes: + label: What were you searching in the docs? + description: Please help us understand how you looked for information that was either unclear or not available + validations: + required: true + - type: input + id: area + attributes: + label: Is this related to an existing documentation section? + description: Please share a link, if applicable + validations: + required: false + - type: textarea + id: idea + attributes: + label: How can we improve? + description: Please share your thoughts on how we can improve this experience + validations: + required: true + - type: textarea + id: suggestion + attributes: + label: Got a suggestion in mind? + description: Please suggest a proposed update + validations: + required: false + - type: checkboxes + id: acknowledgment + attributes: + label: Acknowledgment + options: + - label: I understand the final update might be different from my proposed suggestion, or refused. + required: true + - type: markdown + attributes: + value: | + --- + + **Disclaimer**: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful. diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/feature_request.yml b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000000000000000000000000000000000000..a39fb211ac106602dba49f9f44380a4ed4a483cc --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,48 @@ +name: Feature request +description: Suggest an idea for Powertools for AWS Lambda (Python) +title: "Feature request: TITLE" +labels: ["feature-request", "triage"] +body: + - type: markdown + attributes: + value: | + Thank you for taking the time to suggest an idea to the Powertools for AWS Lambda (Python) project. + + *Future readers*: Please react with 👍 and your use case to help us understand customer demand. + - type: textarea + id: problem + attributes: + label: Use case + description: Please help us understand your use case or problem you're facing + validations: + required: true + - type: textarea + id: suggestion + attributes: + label: Solution/User Experience + description: Please share what a good solution would look like to this use case + validations: + required: true + - type: textarea + id: alternatives + attributes: + label: Alternative solutions + description: Please describe what alternative solutions to this use case, if any + render: markdown + validations: + required: false + - type: checkboxes + id: acknowledgment + attributes: + label: Acknowledgment + options: + - label: This feature request meets [Powertools for AWS Lambda (Python) Tenets](https://docs.powertools.aws.dev/lambda/python/latest/#tenets) + required: true + - label: Should this be considered in other Powertools for AWS Lambda languages? i.e. [Java](https://github.com/aws-powertools/powertools-lambda-java/), [TypeScript](https://github.com/aws-powertools/powertools-lambda-typescript/), and [.NET](https://github.com/aws-powertools/powertools-lambda-dotnet/) + required: false + - type: markdown + attributes: + value: | + --- + + **Disclaimer**: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful. diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/maintenance.yml b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/maintenance.yml new file mode 100644 index 0000000000000000000000000000000000000000..bbc3ff3b3d8422799fce0759cea2842e9c73522e --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/maintenance.yml @@ -0,0 +1,65 @@ +name: Maintenance +description: Suggest an activity to help address governance and anything internal +title: "Maintenance: TITLE" +labels: ["internal", "triage"] +body: + - type: markdown + attributes: + value: | + Thank you for taking the time to help us improve operational excellence. + + *Future readers*: Please react with 👍 and your use case to help us understand customer demand. + - type: textarea + id: importance + attributes: + label: Why is this needed? + description: Please help us understand the value so we can prioritize it accordingly + validations: + required: true + - type: dropdown + id: area + attributes: + label: Which area does this relate to? + multiple: true + options: + - Tests + - Static typing + - Tracer + - Logger + - Metrics + - Event Handler - REST API + - Event Handler - GraphQL API + - Middleware factory + - Parameters + - Batch processing + - Validation + - Event Source Data Classes + - Parser + - Idempotency + - Feature flags + - JMESPath functions + - Streaming + - Automation + - Other + - type: textarea + id: suggestion + attributes: + label: Solution + description: If available, please share what a good solution would look like + validations: + required: false + - type: checkboxes + id: acknowledgment + attributes: + label: Acknowledgment + options: + - label: This request meets [Powertools for AWS Lambda (Python) Tenets](https://docs.powertools.aws.dev/lambda/python/latest/#tenets) + required: true + - label: Should this be considered in other Powertools for AWS Lambda languages? i.e. [Java](https://github.com/aws-powertools/powertools-lambda-java/), [TypeScript](https://github.com/aws-powertools/powertools-lambda-typescript/), and [.NET](https://github.com/aws-powertools/powertools-lambda-dotnet/) + required: false + - type: markdown + attributes: + value: | + --- + + **Disclaimer**: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful. diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/rfc.yml b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/rfc.yml new file mode 100644 index 0000000000000000000000000000000000000000..31d8d7fe0c66737927ecc9b0894acf538564b048 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/rfc.yml @@ -0,0 +1,109 @@ +name: Request for Comments (RFC) +description: Feature design and detailed proposals +title: "RFC: TITLE" +labels: ["RFC", "triage"] +body: + - type: markdown + attributes: + value: | + Thank you for submitting a RFC. Please add as many details as possible to help further enrich this design. + - type: input + id: relation + attributes: + label: Is this related to an existing feature request or issue? + description: Please share a link, if applicable + - type: dropdown + id: area + attributes: + label: Which Powertools for AWS Lambda (Python) utility does this relate to? + options: + - Tracer + - Logger + - Metrics + - Event Handler - REST API + - Event Handler - GraphQL API + - Middleware factory + - Parameters + - Batch processing + - Typing + - Validation + - Event Source Data Classes + - Parser + - Idempotency + - Feature flags + - JMESPath functions + - Other + validations: + required: true + - type: textarea + id: summary + attributes: + label: Summary + description: Please provide an overview in one or two paragraphs + validations: + required: true + - type: textarea + id: problem + attributes: + label: Use case + description: Please share the use case and motivation behind this proposal + validations: + required: true + - type: textarea + id: proposal + attributes: + label: Proposal + description: Please explain the design in detail, so anyone familiar with the project could implement it + placeholder: What the user experience looks like before and after this design? + validations: + required: true + - type: textarea + id: scope + attributes: + label: Out of scope + description: Please explain what should be considered out of scope in your proposal + validations: + required: true + - type: textarea + id: challenges + attributes: + label: Potential challenges + description: Nothing is perfect. Please share what common challenges, edge cases, unresolved areas, and suggestions on how to mitigate them + validations: + required: true + - type: textarea + id: integrations + attributes: + label: Dependencies and Integrations + description: If applicable, please share whether this feature has additional dependencies, and how it might integrate with other utilities available + validations: + required: false + - type: textarea + id: alternatives + attributes: + label: Alternative solutions + description: Please describe what alternative solutions to this use case, if any + render: markdown + validations: + required: false + - type: checkboxes + id: acknowledgment + attributes: + label: Acknowledgment + options: + - label: This feature request meets [Powertools for AWS Lambda (Python) Tenets](https://docs.powertools.aws.dev/lambda/python/latest/#tenets) + required: true + - label: Should this be considered in other Powertools for AWS Lambda languages? i.e. [Java](https://github.com/aws-powertools/powertools-lambda-java/), [TypeScript](https://github.com/aws-powertools/powertools-lambda-typescript/), and [.NET](https://github.com/aws-powertools/powertools-lambda-dotnet/) + required: false + - type: markdown + attributes: + value: | + --- + + **Disclaimer**: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful. + + Metadata information for admin purposes, please leave them empty. + + * RFC PR: + * Approved by: '' + * Reviewed by: '' diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/share_your_work.yml b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/share_your_work.yml new file mode 100644 index 0000000000000000000000000000000000000000..e4e4ed601be53fa8981d82ef41a24bd133fee2ea --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/share_your_work.yml @@ -0,0 +1,56 @@ +name: I Made This (showcase your work) +description: Share what you did with Powertools for AWS Lambda (Python) 💞💞. Blog post, workshops, presentation, sample apps, etc. +title: "[I Made This]: " +labels: ["community-content"] +body: + - type: markdown + attributes: + value: Thank you for helping spread the word out on Powertools, truly! + - type: input + id: content + attributes: + label: Link to your material + description: | + Please share the original link to your material. + + *Note: Short links will be expanded when added to Powertools for AWS Lambda (Python) documentation* + validations: + required: true + - type: textarea + id: description + attributes: + label: Description + description: Describe in one paragraph what's in it for them (readers) + validations: + required: true + - type: input + id: author + attributes: + label: Preferred contact + description: What's your preferred contact? We'll list it next to this content + validations: + required: true + - type: input + id: author-social + attributes: + label: (Optional) Social Network + description: If different from preferred contact, what's your preferred contact for social interactions? + validations: + required: false + - type: textarea + id: notes + attributes: + label: (Optional) Additional notes + description: | + Any notes you might want to share with us related to this material. + + *Note: These notes are explicitly to Powertools for AWS Lambda (Python) maintainers. It will not be added to the community resources page.* + validations: + required: false + - type: checkboxes + id: acknowledgment + attributes: + label: Acknowledgment + options: + - label: I understand this content may be removed from Powertools for AWS Lambda (Python) documentation if it doesn't conform with the [Code of Conduct](https://aws.github.io/code-of-conduct) + required: true diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/static_typing.yml b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/static_typing.yml new file mode 100644 index 0000000000000000000000000000000000000000..35856589a2bd646cd4351243af1cedd52a862b7c --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/static_typing.yml @@ -0,0 +1,71 @@ +name: Static typing mismatch report +description: Report a static type mismatch caught by a static type checker +title: "Static typing: TITLE" +labels: ["typing", "triage"] +body: + - type: markdown + attributes: + value: | + Thank you for submitting a static typing report. Please add as much information as possible to help us reproduce. + + Our preferred static type checker is [Mypy](https://mypy.readthedocs.io/en/stable/) using the following [configuration](https://github.com/aws-powertools/powertools-lambda-python/blob/develop/mypy.ini). + - type: dropdown + id: tool + attributes: + label: Static type checker used + options: + - mypy (project's standard) + - pyright/pylance + - pyre + - pytype + validations: + required: true + - type: dropdown + id: runtime + attributes: + label: AWS Lambda function runtime + options: + - "3.8" + - "3.9" + - "3.10" + - "3.11" + - "3.12" + - "3.13" + validations: + required: true + - type: input + id: version + attributes: + label: Powertools for AWS Lambda (Python) version + placeholder: "latest, 1.25.6" + value: latest + validations: + required: true + - type: textarea + id: output + attributes: + label: Static type checker info + description: Please share your static type checker's output, its configuration, and how you typically run it + validations: + required: true + - type: textarea + id: code_snippet + attributes: + label: Code snippet + description: Please share a code snippet to help us reproduce the issue + render: python + validations: + required: true + - type: textarea + id: solution + attributes: + label: Possible Solution + description: If known, please suggest a potential resolution + validations: + required: false + - type: markdown + attributes: + value: | + --- + + **Disclaimer**: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful. diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/support_powertools.yml b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/support_powertools.yml new file mode 100644 index 0000000000000000000000000000000000000000..c2c5f33676cb302d08d70b897ec465e32ca76681 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/support_powertools.yml @@ -0,0 +1,64 @@ +name: Support Powertools for AWS Lambda (Python) (become a reference) +description: Add your organization's name or logo to the Powertools for AWS Lambda (Python) documentation +title: "[Support Powertools for AWS Lambda (Python)]: <your organization name>" +labels: ["customer-reference"] +body: + - type: markdown + attributes: + value: | + Thank you for becoming a reference customer. Your support means a lot to us. It also helps new customers to know who's using it. + + If you would like us to also display your organization's logo, please share a link in the `Company logo` field. + - type: input + id: organization + attributes: + label: Organization Name + description: Please share the name of your organization + placeholder: ACME + validations: + required: true + - type: input + id: name + attributes: + label: Your Name + description: Please share your name + validations: + required: true + - type: input + id: job + attributes: + label: Your current position + description: Please share your current position at your company + validations: + required: true + - type: input + id: logo + attributes: + label: (Optional) Company logo + description: Company logo you want us to display. You also allow us to resize for optimal placement in the documentation. + validations: + required: false + - type: textarea + id: use_case + attributes: + label: (Optional) Use case + description: How are you using Powertools for AWS Lambda (Python) today? *features, etc.* + validations: + required: false + - type: checkboxes + id: other_languages + attributes: + label: Also using other Powertools for AWS Lambda languages? + options: + - label: Java + required: false + - label: TypeScript + required: false + - label: .NET + required: false + - type: markdown + attributes: + value: | + *By raising a Support Powertools for AWS Lambda (Python) issue, you are granting AWS permission to use your company's name (and/or logo) for the limited purpose described here. You are also confirming that you have authority to grant such permission.* + + *You can opt-out at any time by commenting or reopening this issue.* diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/tech_debt.yml b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/tech_debt.yml new file mode 100644 index 0000000000000000000000000000000000000000..064c118ba20f9c75336c3a9039f351c8fd0eb842 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/ISSUE_TEMPLATE/tech_debt.yml @@ -0,0 +1,62 @@ +name: Technical debt +description: Suggest an activity to help address technical debt. +title: "Tech debt: TITLE" +labels: ["tech-debt", "triage"] +body: + - type: markdown + attributes: + value: Thank you for taking the time to help us proactively improve delivery velocity, safely. + - type: textarea + id: importance + attributes: + label: Why is this needed? + description: Please help us understand the value so we can prioritize it accordingly + validations: + required: true + - type: dropdown + id: area + attributes: + label: Which area does this relate to? + multiple: true + options: + - Tests + - Static typing + - Tracer + - Logger + - Metrics + - Event Handler - REST API + - Event Handler - GraphQL API + - Middleware factory + - Parameters + - Batch processing + - Validation + - Event Source Data Classes + - Parser + - Idempotency + - Feature flags + - JMESPath functions + - Streaming + - Automation + - Other + - type: textarea + id: suggestion + attributes: + label: Suggestion + description: If available, please share what a good solution would look like + validations: + required: false + - type: checkboxes + id: acknowledgment + attributes: + label: Acknowledgment + options: + - label: This request meets [Powertools for AWS Lambda (Python) Tenets](https://docs.powertools.aws.dev/lambda/python/latest/#tenets) + required: true + - label: Should this be considered in other Powertools for AWS Lambda languages? i.e. [Java](https://github.com/aws-powertools/powertools-lambda-java/), [TypeScript](https://github.com/aws-powertools/powertools-lambda-typescript/), and [.NET](https://github.com/aws-powertools/powertools-lambda-dotnet/) + required: false + - type: markdown + attributes: + value: | + --- + + **Disclaimer**: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful. diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/PULL_REQUEST_TEMPLATE.md b/testbed/aws-powertools__powertools-lambda-python/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000000000000000000000000000000000..5265d390063c519830953d679c18b0eb06099102 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,40 @@ +<!-- markdownlint-disable MD041 MD043 --> +**Issue number:** + +## Summary + +### Changes + +> Please provide a summary of what's being changed + +### User experience + +> Please share what the user experience looks like before and after this change + +## Checklist + +If your change doesn't seem to apply, please leave them unchecked. + +* [ ] [Meet tenets criteria](https://docs.powertools.aws.dev/lambda/python/#tenets) +* [ ] I have performed a self-review of this change +* [ ] Changes have been tested +* [ ] Changes are documented +* [ ] PR title follows [conventional commit semantics](https://github.com/aws-powertools/powertools-lambda-python/blob/develop/.github/semantic.yml) + +<details> +<summary>Is this a breaking change?</summary> + +**RFC issue number**: + +Checklist: + +* [ ] Migration process documented +* [ ] Implement warnings (if it can live side by side) + +</details> + +## Acknowledgment + +By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice. + +**Disclaimer**: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful. diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/actionlint.yaml b/testbed/aws-powertools__powertools-lambda-python/.github/actionlint.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c9597418e3f29fef5e56b19048ff4aa440c7676a --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/actionlint.yaml @@ -0,0 +1,3 @@ +self-hosted-runner: + labels: + - aws-powertools_ubuntu-latest_8-core diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/actions/create-pr/action.yml b/testbed/aws-powertools__powertools-lambda-python/.github/actions/create-pr/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..39ba6f60b1f594450efd940f2314e1b7151d7c70 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/actions/create-pr/action.yml @@ -0,0 +1,88 @@ +name: "Create PR custom action" +description: "Create a PR and a temporary branch, close duplicates" + +# PROCESS +# +# 1. Setup git client using Powertools for AWS Lambda (Python) bot username +# 2. Pushes staged files to a temporary branch +# 3. Creates a PR from temporary branch against a target branch (typically trunk: develop, main, etc.) +# 4. Searches for duplicate PRs with the same title +# 5. If duplicates are found, link to the most recent one, close and delete their branches so we keep a single PR +# 6. In the event of failure, we delete the now orphaned branch (if any), and propagate the failure + +# USAGE +# +# - name: Create PR +# id: create-pr +# uses: ./.github/actions/create-pr +# with: +# files: "CHANGELOG.md" +# temp_branch_prefix: "ci-changelog" +# pull_request_title: "chore(ci): changelog rebuild" +# github_token: ${{ secrets.GITHUB_TOKEN }} +# - name: Step to demonstrate how to access outputs (no need for this) +# run: | +# echo "PR number: ${PR_ID}" +# echo "Branch: ${BRANCH}" +# env: +# PR_ID: ${{ steps.create-pr.outputs.pull_request_id}} +# BRANCH: ${{ steps.create-pr.outputs.temp_branch}} + +inputs: + files: + description: "Files to add separated by space" + required: true + temp_branch_prefix: + description: "Prefix for temporary git branch to be created, e.g, ci-docs" + required: true + pull_request_title: + description: "Pull Request title to use" + required: true + github_token: + description: "GitHub token for GitHub CLI" + required: true + target_branch: + description: "Branch to target when creating a PR against (develop, by default)" + required: false + default: develop + +outputs: + pull_request_id: + description: "Pull request ID created" + value: ${{ steps.create-pr.outputs.pull_request_id }} + temp_branch: + description: "Temporary branch created with staged changed" + value: ${{ steps.create-pr.outputs.temp_branch }} + +runs: + using: "composite" + steps: + - id: adjust-path + run: echo "${{ github.action_path }}" >> $GITHUB_PATH + shell: bash + - id: setup-git + name: Git client setup and refresh tip + run: | + git config user.name "Powertools for AWS Lambda (Python) bot" + git config user.email "151832416+aws-powertools-bot@users.noreply.github.com" + git config pull.rebase true + git config remote.origin.url >&- + shell: bash + - id: create-pr + working-directory: ${{ env.GITHUB_WORKSPACE }} + run: create_pr_for_staged_changes.sh "${FILES}" + env: + FILES: ${{ inputs.files }} + TEMP_BRANCH_PREFIX: ${{ inputs.temp_branch_prefix }} + PR_TITLE: ${{ inputs.pull_request_title }} + BASE_BRANCH: ${{ inputs.target_branch }} + GH_TOKEN: ${{ inputs.github_token }} + shell: bash + - id: cleanup + name: Cleanup orphaned branch + if: failure() + run: git push origin --delete "${TEMP_BRANCH_PREFIX}-${GITHUB_RUN_ID}" || echo "Must have failed before creating temporary branch; no cleanup needed." + env: + TEMP_BRANCH_PREFIX: ${{ inputs.temp_branch_prefix }} + GITHUB_RUN_ID: ${{ github.run_id }} + shell: bash diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/actions/create-pr/create_pr_for_staged_changes.sh b/testbed/aws-powertools__powertools-lambda-python/.github/actions/create-pr/create_pr_for_staged_changes.sh new file mode 100644 index 0000000000000000000000000000000000000000..f31217467ee0ef77dd413665970ba7c702a228f5 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/actions/create-pr/create_pr_for_staged_changes.sh @@ -0,0 +1,148 @@ +#!/bin/bash +set -uo pipefail # prevent accessing unset env vars, prevent masking pipeline errors to the next command + +#docs +#title :create_pr_for_staged_changes.sh +#description :This script will create a PR for staged changes, detect and close duplicate PRs. All PRs will be omitted from Release Notes and Changelogs +#author :@heitorlessa +#date :May 8th 2023 +#version :0.1 +#usage :bash create_pr_for_staged_changes.sh {git_staged_files_or_directories_separated_by_space} +#notes :Meant to use in GitHub Actions only. Temporary branch will be named $TEMP_BRANCH_PREFIX-$GITHUB_RUN_ID +#os_version :Ubuntu 22.04.2 LTS +#required_env_vars :PR_TITLE, TEMP_BRANCH_PREFIX, GH_TOKEN +#============================================================================== + +# Sets GitHub Action with error message to ease troubleshooting +function error() { + echo "::error file=${FILENAME}::$1" + exit 1 +} + +function debug() { + TIMESTAMP=$(date -u "+%FT%TZ") # 2023-05-10T07:53:59Z + echo ""${TIMESTAMP}" - $1" +} + +function notice() { + echo "::notice file=${FILENAME}::$1" +} + +function start_span() { + echo "::group::$1" +} + +function end_span() { + echo "::endgroup::" +} + +function has_required_config() { + start_span "Validating required config" + test -z "${TEMP_BRANCH_PREFIX}" && error "TEMP_BRANCH_PREFIX env must be set to create a PR" + test -z "${PR_TITLE}" && error "PR_TITLE env must be set" + test -z "${GH_TOKEN}" && error "GH_TOKEN env must be set for GitHub CLI" + + # Default GitHub Actions Env Vars: https://docs.github.com/en/actions/learn-github-actions/variables#default-environment-variables + debug "Are we running in GitHub Action environment?" + test -z "${GITHUB_RUN_ID}" && error "GITHUB_RUN_ID env must be set to trace Workflow Run ID back to PR" + test -z "${GITHUB_SERVER_URL}" && error "GITHUB_SERVER_URL env must be set to trace Workflow Run ID back to PR" + test -z "${GITHUB_REPOSITORY}" && error "GITHUB_REPOSITORY env must be set to trace Workflow Run ID back to PR" + + debug "Config validated successfully!" + set_environment_variables + end_span +} + +function set_environment_variables() { + start_span "Setting environment variables" + export readonly WORKFLOW_URL="${GITHUB_SERVER_URL}"/"${GITHUB_REPOSITORY}"/actions/runs/"${GITHUB_RUN_ID}" # e.g., heitorlessa/aws-lambda-powertools-test/actions/runs/4913570678 + export readonly TEMP_BRANCH="${TEMP_BRANCH_PREFIX}"-"${GITHUB_RUN_ID}" # e.g., ci-changelog-4894658712 + export readonly BASE_BRANCH="${BASE_BRANCH:-develop}" # e.g., main, defaults to develop if missing + export readonly PR_BODY="This is an automated PR created from the following workflow" + export readonly FILENAME=".github/scripts/$(basename "$0")" + export readonly NO_DUPLICATES_MESSAGE="No duplicated PRs found" + export readonly SKIP_LABEL="skip-changelog" + + end_span +} + +function has_anything_changed() { + start_span "Validating git staged files" + HAS_ANY_SOURCE_CODE_CHANGED="$(git status --porcelain)" + + test -z "${HAS_ANY_SOURCE_CODE_CHANGED}" && debug "Nothing to update; exitting early" && exit 0 + end_span +} + +function create_temporary_branch_with_changes() { + start_span "Creating temporary branch: "${TEMP_BRANCH}"" + git checkout -b "${TEMP_BRANCH}" + + debug "Committing staged files: $*" + echo "$@" | xargs -n1 git add || error "Failed to add staged changes: "$@"" + git commit -m "${PR_TITLE}" + + git push origin "${TEMP_BRANCH}" || error "Failed to create new temporary branch" + end_span +} + +function create_pr() { + start_span "Creating PR against ${TEMP_BRANCH} branch" + # TODO: create label + NEW_PR_URL=$(gh pr create --title "${PR_TITLE}" --body "${PR_BODY}: ${WORKFLOW_URL}" --base "${BASE_BRANCH}" --label "${SKIP_LABEL}" || error "Failed to create PR") # e.g, https://github.com/aws-powertools/powertools-lambda-python/pull/13 + + # greedy remove any string until the last URL path, including the last '/'. https://opensource.com/article/17/6/bash-parameter-expansion + debug "Extracing PR Number from PR URL: "${NEW_PR_URL}"" + NEW_PR_ID="${NEW_PR_URL##*/}" # 13 + export NEW_PR_URL + export NEW_PR_ID + end_span +} + +function close_duplicate_prs() { + start_span "Searching for duplicate PRs" + DUPLICATE_PRS=$(gh pr list --search "${PR_TITLE}" --json number --jq ".[] | select(.number != ${NEW_PR_ID}) | .number") # e.g, 13\n14 + + if [ -z "${DUPLICATE_PRS}" ]; then + debug "No duplicate PRs found" + DUPLICATE_PRS="${NO_DUPLICATES_MESSAGE}" + else + debug "Closing duplicated PRs: "${DUPLICATE_PRS}"" + echo "${DUPLICATE_PRS}" | xargs -L1 gh pr close --delete-branch --comment "Superseded by #${NEW_PR_ID}" + fi + + export readonly DUPLICATE_PRS + end_span +} + +function report_job_output() { + start_span "Updating job outputs" + echo pull_request_id="${NEW_PR_ID}" >>"$GITHUB_OUTPUT" + echo temp_branch="${TEMP_BRANCH}" >>"$GITHUB_OUTPUT" + end_span +} + +function report_summary() { + start_span "Creating job summary" + echo "### Pull request created successfully :rocket: ${NEW_PR_URL} <br/><br/> Closed duplicated PRs: ${DUPLICATE_PRS}" >>"$GITHUB_STEP_SUMMARY" + + notice "PR_URL is: ${NEW_PR_URL}" + notice "PR_BRANCH is: ${TEMP_BRANCH}" + notice "PR_DUPLICATES are: ${DUPLICATE_PRS}" + end_span +} + +function main() { + # Sanity check + has_anything_changed + has_required_config + + create_temporary_branch_with_changes "$@" + create_pr + close_duplicate_prs + + report_job_output + report_summary +} + +main "$@" diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/actions/download-artifact/action.yml b/testbed/aws-powertools__powertools-lambda-python/.github/actions/download-artifact/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..1f1347e4220f3b50a97c800fd32d5738bf697edf --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/actions/download-artifact/action.yml @@ -0,0 +1,58 @@ +name: Download artifact +description: Wrapper around GitHub's official action, with additional extraction before download + +# PROCESS +# +# 1. Downloads artifact using actions/download-artifact action +# 2. Extracts and overwrites tarball previously uploaded +# 3. Remove archive after extraction + +# NOTES +# +# Upload-artifact and download-artifact takes ~2m40s to upload 8MB +# so this is custom action cuts down the entire operation to 1s +# by uploading/extracting a tarball while relying on the official upload-artifact/download-artifact actions +# + +# USAGE +# +# NOTE: Meant to be used with ./.github/actions/upload-artifact +# +# - name: Restore sealed source code +# uses: ./.github/actions/download-artifact +# with: +# name: ${{ needs.seal.outputs.INTEGRITY_HASH }} +# path: . + +# https://github.com/actions/download-artifact/blob/main/action.yml +inputs: + name: + description: Artifact name + required: true + path: + description: Destination path. By default, it will download to the current working directory. + required: false + default: . + +runs: + using: composite + steps: + - name: Download artifacts + uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e # v4.1.7 + with: + name: ${{ inputs.name }} + path: ${{ inputs.path }} + + - name: Extract artifacts + run: tar -xvf "${ARCHIVE}" + env: + ARCHIVE: ${{ inputs.name }}.tar + shell: bash + working-directory: ${{ inputs.path }} + + - name: Remove archive + run: rm -f "${ARCHIVE}" + env: + ARCHIVE: ${{ inputs.name }}.tar + shell: bash + working-directory: ${{ inputs.path }} diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/actions/seal-restore/action.yml b/testbed/aws-powertools__powertools-lambda-python/.github/actions/seal-restore/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..1107414b64060d917b95029ae7de97e45bd031e9 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/actions/seal-restore/action.yml @@ -0,0 +1,82 @@ +name: "Restore sealed source code" +description: "Restore sealed source code and confirm integrity hash" + +# PROCESS +# +# 1. Exports artifact name using Prefix + GitHub Run ID (unique for each release trigger) +# 2. Compress entire source code as tarball OR given files +# 3. Create and export integrity hash for tarball +# 4. Upload artifact +# 5. Remove archive + +# USAGE +# +# - name: Seal and upload +# id: seal_source_code +# uses: ./.github/actions/seal +# with: +# artifact_name_prefix: "source" +# +# - name: Restore sealed source code +# uses: ./.github/actions/seal-restore +# with: +# integrity_hash: ${{ needs.seal_source_code.outputs.integrity_hash }} +# artifact_name: ${{ needs.seal_source_code.outputs.artifact_name }} + +# NOTES +# +# To be used together with .github/actions/seal + +inputs: + integrity_hash: + description: "Integrity hash to verify" + required: true + artifact_name: + description: "Sealed artifact name to restore" + required: true + +runs: + using: "composite" + steps: + - id: adjust-path + run: echo "${{ github.action_path }}" >> $GITHUB_PATH + shell: bash + + - name: Download artifacts + uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e # v4.1.7 + with: + name: ${{ inputs.artifact_name }} + path: . + + - id: integrity_hash + name: Create integrity hash for downloaded artifact + run: | + HASH=$(sha256sum "${ARTIFACT_NAME}.tar" | awk '{print $1}') + + echo "current_hash=${HASH}" >> "$GITHUB_OUTPUT" + env: + ARTIFACT_NAME: ${{ inputs.artifact_name }} + shell: bash + + - id: verify_hash + name: Verify sealed artifact integrity hash + run: test "${CURRENT_HASH}" = "${PROVIDED_HASH}" || exit 1 + env: + ARTIFACT_NAME: ${{ inputs.artifact_name }} + PROVIDED_HASH: ${{ inputs.integrity_hash }} + CURRENT_HASH: ${{ steps.integrity_hash.outputs.current_hash }} + shell: bash + + # Restore and overwrite tarball in current directory + - id: overwrite + name: Extract tarball + run: tar -xvf "${ARTIFACT_NAME}".tar + env: + ARTIFACT_NAME: ${{ inputs.artifact_name }} + shell: bash + + - name: Remove archive + run: rm -f "${ARTIFACT_NAME}.tar" + env: + ARTIFACT_NAME: ${{ inputs.artifact_name }} + shell: bash diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/actions/seal/action.yml b/testbed/aws-powertools__powertools-lambda-python/.github/actions/seal/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..c3e75a13e92a37cfd778357877a1efa630225c2b --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/actions/seal/action.yml @@ -0,0 +1,93 @@ +name: "Seal and hash source code" +description: "Seal and export source code as a tarball artifact along with its integrity hash" + +# PROCESS +# +# 1. Exports artifact name using Prefix + GitHub Run ID (unique for each release trigger) +# 2. Compress entire source code as tarball OR given files +# 3. Create and export integrity hash for tarball +# 4. Upload artifact +# 5. Remove archive + +# USAGE +# +# - name: Seal and upload +# id: seal_source_code +# uses: ./.github/actions/seal +# with: +# artifact_name_prefix: "source" + +inputs: + files: + description: "Files to seal separated by space" + required: false + artifact_name_prefix: + description: "Prefix to use when exporting artifact" + required: true + +outputs: + integrity_hash: + description: "Source code integrity hash" + value: ${{ steps.integrity_hash.outputs.integrity_hash }} + artifact_name: + description: "Artifact name containTemporary branch created with staged changed" + value: ${{ steps.export_artifact_name.outputs.artifact_name }} + +runs: + using: "composite" + steps: + - id: adjust-path + run: echo "${{ github.action_path }}" >> $GITHUB_PATH + shell: bash + + - id: export_artifact_name + name: Export final artifact name + run: echo "artifact_name=${ARTIFACT_PREFIX}-${GITHUB_RUN_ID}" >> "$GITHUB_OUTPUT" + env: + GITHUB_RUN_ID: ${{ github.run_id }} + ARTIFACT_PREFIX: ${{ inputs.artifact_name_prefix }} + shell: bash + + # By default, create a tarball of the current directory minus .git + # otherwise it breaks GH Actions when restoring it + - id: compress_all + if: ${{ !inputs.files }} + name: Create tarball for entire source + run: tar --exclude-vcs -cvf "${ARTIFACT_NAME}".tar * + env: + ARTIFACT_NAME: ${{ steps.export_artifact_name.outputs.artifact_name }} + shell: bash + + # If a list of files are given, then create a tarball for those only + - id: compress_selected_files + if: ${{ inputs.files }} + name: Create tarball for selected files + run: tar --exclude-vcs -cvf "${ARTIFACT_NAME}".tar "${FILES}" + env: + FILES: ${{ inputs.files }} + ARTIFACT_NAME: ${{ steps.export_artifact_name.outputs.artifact_name }} + shell: bash + + - id: integrity_hash + name: Create and export integrity hash for tarball + run: | + HASH=$(sha256sum "${ARTIFACT_NAME}.tar" | awk '{print $1}') + + echo "integrity_hash=${HASH}" >> "$GITHUB_OUTPUT" + env: + ARTIFACT_NAME: ${{ steps.export_artifact_name.outputs.artifact_name }} + shell: bash + + - name: Upload artifacts + uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 # v4.3.3 + with: + if-no-files-found: error + name: ${{ steps.export_artifact_name.outputs.artifact_name }} + path: ${{ steps.export_artifact_name.outputs.artifact_name }}.tar + retention-days: 1 + + - name: Remove archive + run: rm -f "${ARTEFACT_NAME}.tar" + env: + ARTIFACT_NAME: ${{ steps.export_artifact_name.outputs.artifact_name }} + shell: bash diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/actions/upload-artifact/action.yml b/testbed/aws-powertools__powertools-lambda-python/.github/actions/upload-artifact/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..f88ea2475b9c5ce380668b399a80cb7bd59a6eb3 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/actions/upload-artifact/action.yml @@ -0,0 +1,82 @@ +name: Upload artifact +description: Wrapper around GitHub's official action, with additional archiving before upload + +# PROCESS +# +# 1. Creates tarball excluding .git files +# 2. Uploads tarball using actions/upload-artifact action, fail CI job if no file is found +# 3. Remove archive after uploading it. + +# NOTES +# +# Upload-artifact and download-artifact takes ~2m40s to upload 8MB +# so this is custom action cuts down the entire operation to 1s +# by uploading/extracting a tarball while relying on the official upload-artifact/download-artifact actions +# + +# USAGE +# +# NOTE: Meant to be used with ./.github/actions/download-artifact +# +# - name: Upload sealed source code +# uses: ./.github/actions/upload-artifact +# with: +# name: ${{ steps.integrity.outputs.INTEGRITY_HASH }} +# path: . + +# https://github.com/actions/upload-artifact/blob/main/action.yml +inputs: + name: + description: Artifact name + required: true + path: + description: > + A file, directory or wildcard pattern that describes what to upload. + + You can pass multiple paths separated by space (e.g., dir1 dir2 file.txt). + + Paths and wildcard patterns must be tar command compatible. + required: true + retention-days: + description: > + Artifact retention in days. By default 1 day, max of 90 days, and 0 honours default repo retention. + + You can change max days in the repository settings. + required: false + default: "1" + if-no-files-found: + description: > + Action to perform if no files are found: warn, error, ignore. By default, it fails fast with 'error'. + + Options: + warn: Output a warning but do not fail the action + error: Fail the action with an error message + ignore: Do not output any warnings or errors, the action does not fail + required: false + default: error + +runs: + using: composite + steps: + - name: Archive artifacts + run: | + tar --exclude-vcs \ + -cvf "${ARCHIVE}" "${PATH_TO_ARCHIVE}" + env: + ARCHIVE: ${{ inputs.name }}.tar + PATH_TO_ARCHIVE: ${{ inputs.path }} + shell: bash + + - name: Upload artifacts + uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 # v4.3.3 + with: + if-no-files-found: ${{ inputs.if-no-files-found }} + name: ${{ inputs.name }} + path: ${{ inputs.name }}.tar + retention-days: ${{ inputs.retention-days }} + + - name: Remove archive + run: rm -f "${ARCHIVE}" + env: + ARCHIVE: ${{ inputs.name }}.tar + shell: bash diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/actions/upload-release-provenance/action.yml b/testbed/aws-powertools__powertools-lambda-python/.github/actions/upload-release-provenance/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..d0829efd4f4ac926c15029c2904c6ae56992027a --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/actions/upload-release-provenance/action.yml @@ -0,0 +1,67 @@ +name: "Upload provenance attestation to release" +description: "Download and upload newly generated provenance attestation to latest release." + +# PROCESS +# +# 1. Downloads provenance attestation artifact generated earlier in the release pipeline +# 2. Updates latest GitHub draft release pointing to newly git release tag +# 3. Uploads provenance attestation file to latest GitHub draft release + +# USAGE +# +# - name: Upload provenance +# id: upload-provenance +# uses: ./.github/actions/upload-release-provenance +# with: +# release_version: ${{ needs.seal.outputs.RELEASE_VERSION }} +# provenance_name: ${{needs.provenance.outputs.provenance-name}} +# github_token: ${{ secrets.GITHUB_TOKEN }} + +# NOTES +# +# There are no outputs. +# + +inputs: + provenance_name: + description: "Provenance artifact name to download" + required: true + release_version: + description: "Release version (e.g., 2.20.0)" + required: true + github_token: + description: "GitHub token for GitHub CLI" + required: true + +runs: + using: "composite" + steps: + - id: adjust-path + run: echo "${{ github.action_path }}" >> $GITHUB_PATH + shell: bash + + - id: download-provenance + name: Download newly generated provenance + uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e # v4.1.7 + with: + name: ${{ inputs.provenance_name }} + + - id: sync-release-tag + name: Update draft release tag to release commit tag + run: | + CURRENT_DRAFT_RELEASE=$(gh release list | awk '{ if ($2 == "Draft") print $1}') + gh release edit "${CURRENT_DRAFT_RELEASE}" --tag v"${RELEASE_VERSION}" + env: + RELEASE_VERSION: ${{ inputs.release_version }} + GH_TOKEN: ${{ inputs.github_token }} + shell: bash + + - id: upload-provenance + name: Upload provenance to release tag + # clobber flag means overwrite release asset if available (eventual consistency, retried failed steps) + run: gh release upload --clobber v"${RELEASE_VERSION}" "${PROVENANCE_FILE}" + env: + RELEASE_VERSION: ${{ inputs.release_version }} + PROVENANCE_FILE: ${{ inputs.provenance_name }} + GH_TOKEN: ${{ inputs.github_token }} + shell: bash diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/actions/verify-provenance/verify_provenance.sh b/testbed/aws-powertools__powertools-lambda-python/.github/actions/verify-provenance/verify_provenance.sh new file mode 100644 index 0000000000000000000000000000000000000000..dbfe280473d0cb83b7b918b9feba9428539d6a16 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/actions/verify-provenance/verify_provenance.sh @@ -0,0 +1,134 @@ +#!/bin/bash +set -uo pipefail # prevent accessing unset env vars, prevent masking pipeline errors to the next command + +#docs +#title :verify_provenance.sh +#description :This script will download and verify a signed Powertools for AWS Lambda (Python) release build with SLSA Verifier +#author :@heitorlessa +#date :July 1st 2023 +#version :0.1 +#usage :bash verify_provenance.sh {release version} +#notes :Meant to use in GitHub Actions or locally (MacOS, Linux, WSL). +#os_version :Ubuntu 22.04.2 LTS +#============================================================================== + +# Check if RELEASE_VERSION is provided as a command line argument +if [[ $# -eq 1 ]]; then + export readonly RELEASE_VERSION="$1" +else + echo "ERROR: Please provider Powertools release version as a command line argument." + echo "Example: bash verify_provenance.sh 2.20.0" + exit 1 +fi + +export readonly ARCHITECTURE=$(uname -m | sed 's/x86_64/amd64/g') # arm64, x86_64 ->amd64 +export readonly OS_NAME=$(uname -s | tr '[:upper:]' '[:lower:]') # darwin, linux +export readonly SLSA_VERIFIER_VERSION="2.3.0" +export readonly SLSA_VERIFIER_CHECKSUM_FILE="SHA256SUM.md" +export readonly SLSA_VERIFIER_BINARY="./slsa-verifier-${OS_NAME}-${ARCHITECTURE}" + +export readonly RELEASE_BINARY="aws_lambda_powertools-${RELEASE_VERSION}-py3-none-any.whl" +export readonly ORG="aws-powertools" +export readonly REPO="powertools-lambda-python" +export readonly PROVENANCE_FILE="multiple.intoto.jsonl" + +export readonly FILES=("${SLSA_VERIFIER_BINARY}" "${SLSA_VERIFIER_CHECKSUM_FILE}" "${PROVENANCE_FILE}" "${RELEASE_BINARY}") + +function debug() { + TIMESTAMP=$(date -u "+%FT%TZ") # 2023-05-10T07:53:59Z + echo ""${TIMESTAMP}" DEBUG - [*] $1" +} + +function error() { + cleanup + TIMESTAMP=$(date -u "+%FT%TZ") # 2023-05-10T07:53:59Z + echo ""${TIMESTAMP}" ERROR - [!] $1" + echo ""${TIMESTAMP}" ERROR - [!] exiting" + exit 1 +} + +function download_slsa_verifier() { + readonly SLSA_URL="https://github.com/slsa-framework/slsa-verifier/releases/download/v${SLSA_VERIFIER_VERSION}/slsa-verifier-${OS_NAME}-${ARCHITECTURE}" + # debug "Downloading SLSA Verifier for - Binary: slsa-verifier-${OS_NAME}-${ARCHITECTURE}" + debug "Downloading SLSA Verifier binary: ${SLSA_URL}" + curl \ + --location \ + --fail \ + --silent \ + -O "${SLSA_URL}" || error "Failed to download SLSA Verifier binary" + + readonly SLSA_CHECKSUM_URL="https://raw.githubusercontent.com/slsa-framework/slsa-verifier/f59b55ef2190581d40fc1a5f3b7a51cab2f4a652/${SLSA_VERIFIER_CHECKSUM_FILE}" + debug "Downloading SLSA Verifier checksums" + curl \ + --location \ + --fail \ + --silent \ + -O "${SLSA_CHECKSUM_URL}" || error "Failed to download SLSA Verifier binary checksum file" + + debug "Verifying SLSA Verifier binary integrity" + CURRENT_HASH=$(sha256sum "${SLSA_VERIFIER_BINARY}" | awk '{print $1}') + if [[ $(grep "${CURRENT_HASH}" "${SLSA_VERIFIER_CHECKSUM_FILE}") ]]; then + debug "SLSA Verifier binary integrity confirmed" + chmod +x "${SLSA_VERIFIER_BINARY}" + else + error "Failed integrity check for SLSA Verifier binary: ${SLSA_VERIFIER_BINARY}" + fi +} + +function download_provenance() { + readonly PROVENANCE_URL="https://github.com/${ORG}/${REPO}/releases/download/v${RELEASE_VERSION}/${PROVENANCE_FILE}" + debug "Downloading attestation: ${PROVENANCE_URL}" + + curl \ + --location \ + --fail \ + --silent \ + -O ${PROVENANCE_URL} || error "Failed to download provenance. Does the release already exist?" +} + +function download_release_artifact() { + debug "Downloading ${RELEASE_VERSION} release from PyPi" + python -m pip download \ + --only-binary=:all: \ + --no-deps \ + --quiet \ + aws-lambda-powertools=="${RELEASE_VERSION}" +} + +function verify_provenance() { + debug "Verifying attestation with slsa-verifier" + "${SLSA_VERIFIER_BINARY}" verify-artifact \ + --provenance-path "${PROVENANCE_FILE}" \ + --source-uri github.com/${ORG}/${REPO} \ + ${RELEASE_BINARY} +} + +function cleanup() { + debug "Cleaning up previously downloaded files" + rm -f "${SLSA_VERIFIER_BINARY}" + rm -f "${SLSA_VERIFIER_CHECKSUM_FILE}" + rm -f "${PROVENANCE_FILE}" + rm -f "${RELEASE_BINARY}" + echo "${FILES[@]}" | xargs -n1 echo "Removed file: " +} + +function main() { + download_slsa_verifier + download_provenance + download_release_artifact + verify_provenance + cleanup +} + +main + +# Lessons learned +# +# 1. If source doesn't match provenance +# +# FAILED: SLSA verification failed: source used to generate the binary does not match provenance: expected source 'awslabs/aws-lambda-powertools-python', got 'heitorlessa/aws-lambda-powertools-test' +# +# 2. Avoid building deps during download in Test registry endpoints +# +# FAILED: Could not find a version that satisfies the requirement poetry-core>=1.3.2 (from versions: 1.2.0) +# diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/boring-cyborg.yml b/testbed/aws-powertools__powertools-lambda-python/.github/boring-cyborg.yml new file mode 100644 index 0000000000000000000000000000000000000000..006db19c5850f5901826c52f0b64f7db7d35ec32 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/boring-cyborg.yml @@ -0,0 +1,165 @@ +##### Labeler ########################################################################################################## +labelPRBasedOnFilePath: + logger: + - aws_lambda_powertools/logging/* + - aws_lambda_powertools/logging/**/* + - aws_lambda_powertools/package_logger.py + tracer: + - aws_lambda_powertools/tracing/* + - aws_lambda_powertools/tracing/**/* + metrics: + - aws_lambda_powertools/metrics/* + - aws_lambda_powertools/metrics/**/* + event_handlers: + - aws_lambda_powertools/event_handler/* + - aws_lambda_powertools/event_handler/**/* + middleware_factory: + - aws_lambda_powertools/middleware_factory/* + - aws_lambda_powertools/middleware_factory/**/* + parameters: + - aws_lambda_powertools/parameters/* + - aws_lambda_powertools/parameters/**/* + batch: + - aws_lambda_powertools/batch/* + - aws_lambda_powertools/batch/**/* + validator: + - aws_lambda_powertools/validation/* + - aws_lambda_powertools/validation/**/* + event_sources: + - aws_lambda_powertools/data_classes/* + - aws_lambda_powertools/data_classes/**/* + parser: + - aws_lambda_powertools/parser/* + - aws_lambda_powertools/parser/**/* + idempotency: + - aws_lambda_powertools/idempotency/* + - aws_lambda_powertools/idempotency/**/* + feature_flags: + - aws_lambda_powertools/feature_flags/* + - aws_lambda_powertools/feature_flags/**/* + jmespath: + - aws_lambda_powertools/utilities/jmespath_utils/* + typing: + - aws_lambda_powertools/utilities/typing/* + - mypy.ini + streaming: + - aws_lambda_powertools/utilities/streaming/* + commons: + - aws_lambda_powertools/shared/* + + documentation: + - docs/* + - docs/**/* + - mkdocs.yml + + github-actions: + - .github/workflows/* + - .github/workflows/**/* + - .github/dependabot.yml + - .github/boring-cyborg.yml + - .github/release-drafter.yml + - .github/semantic.yml + - .github/stale.yml + - .github/mergify.yml + + github-templates: + - .github/ISSUE_TEMPLATE/* + - .github/PULL_REQUEST_TEMPLATE.md + - .github/.chglog/* + - .github/.chglog/**/* + + internal: + - .flake8 + - .bandit.baseline + - .gitignore + - .pre-commit-config.yaml + - MANIFEST.in + - Makefile + - CONTRIBUTING.md + - MAINTAINERS.md + - CODE_OF_CONDUCT.md + - LICENSE + - THIRD-PARTY-LICENSES + - aws_lambda_powertools_python/shared/* + - aws_lambda_powertools_python/shared/** + + dependencies: + - pyproject.toml + - poetry.lock + + tests: + - tests/* + - tests/**/* + - benchmark/* + - benchmark/**/* + +##### Greetings ######################################################################################################## +firstPRWelcomeComment: > + Thanks a lot for your first contribution! Please check out our contributing guidelines and don't hesitate to ask whatever you need. + + In the meantime, check out the #python channel on our Powertools for AWS Lambda Discord: [Invite link](https://discord.gg/B8zZKbbyET) + +# Comment to be posted to congratulate user on their first merged PR +firstPRMergeComment: > + Awesome work, congrats on your first merged pull request and thank you for helping improve everyone's experience! + +# Comment to be posted to on first time issues +firstIssueWelcomeComment: > + Thanks for opening your first issue here! We'll come back to you as soon as we can. + + In the meantime, check out the #python channel on our Powertools for AWS Lambda Discord: [Invite link](https://discord.gg/B8zZKbbyET) + +###### IssueLink Adder ################################################################################################# +# Insert Issue (Jira/Github etc) link in PR description based on the Issue ID in PR title. +#insertIssueLinkInPrDescription: +# # specify the placeholder for the issue link that should be present in the description +# descriptionIssuePlaceholderRegexp: "^Issue link: (.*)$" +# matchers: +# # you can have several matches - for different types of issues +# # only the first matching entry is replaced +# jiraIssueMatch: +# # specify the regexp of issue id that you can find in the title of the PR +# # the match groups can be used to build the issue id (${1}, ${2}, etc.). +# titleIssueIdRegexp: \[(AIRFLOW-[0-9]{4})\] +# # the issue link to be added. ${1}, ${2} ... are replaced with the match groups from the +# # title match (remember to use quotes) +# descriptionIssueLink: "[${1}](https://issues.apache.org/jira/browse/${1}/)" +# docOnlyIssueMatch: +# titleIssueIdRegexp: \[(AIRFLOW-X{4})\] +# descriptionIssueLink: "`Document only change, no JIRA issue`" + +###### Title Validator ################################################################################################# +# Verifies if commit/PR titles match the regexp specified +#verifyTitles: +# # Regular expression that should be matched by titles of commits or PR +# titleRegexp: ^\[AIRFLOW-[0-9]{4}\].*$|^\[AIRFLOW-XXXX\].*$ +# # If set to true, it will always check the PR title (as opposed to the individual commits). +# alwaysUsePrTitle: true +# # If set to true, it will only check the commit in case there is a single commit. +# # In case of multiple commits it will check PR title. +# # This reflects the standard behaviour of Github that for `Squash & Merge` GitHub +# # uses the PR title rather than commit messages for the squashed commit ¯\_(ツ)_/¯ +# # For single-commit PRs it takes the squashed commit message from the commit as expected. +# # +# # If set to false it will check all commit messages. This is useful when you do not squash commits at merge. +# validateEitherPrOrSingleCommitTitle: true +# # The title the GitHub status should appear from. +# statusTitle: "Title Validator" +# # A custom message to be displayed when the title passes validation. +# successMessage: "Validation successful!" +# # A custom message to be displayed when the title fails validation. +# # Allows insertion of ${type} (commit/PR), ${title} (the title validated) and ${regex} (the titleRegexp above). +# failureMessage: "Wrong ${type} title: ${title}" + +###### PR/Branch Up-To-Date Checker #################################################################################### +# Check if the branch is up to date with develop when certain files are modified +#checkUpToDate: +# # The default branch is "develop", change the branch if you want to check against a different target branch +# targetBranch: develop +# files: +# # File paths that you want to check for +# # In this example, it checks if the branch is up to date when alembic migrations are modified in the PR. +# # It helps avoid multiple heads in alembic migrations in a collaborative development project. +# - airflow/migrations/* +# - airflow/migrations/**/* +# - airflow/alembic.ini diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/dependabot.yml b/testbed/aws-powertools__powertools-lambda-python/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..fed13e3e577f3420a5a60e5ba84e0d8cc252c75e --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/dependabot.yml @@ -0,0 +1,89 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" + commit-message: + prefix: chore + include: scope + + - package-ecosystem: "pip" + directory: "/" + schedule: + interval: "daily" + target-branch: "develop" + commit-message: + prefix: chore + include: scope + ignore: + # 2022-04-23: Ignoring boto3 changes until we need to care about them. + - dependency-name: "boto3" + groups: + boto-typing: + patterns: + - "mypy-boto3-*" + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "daily" + target-branch: "develop" + commit-message: + prefix: chore + include: scope + allow: + # Allow updates for AWS CDK + - dependency-name: "aws-cdk" + + - package-ecosystem: pip + directory: /benchmark/src/instrumented + commit-message: + prefix: chore + include: scope + schedule: + interval: daily + + - package-ecosystem: pip + directory: /benchmark/src/reference + commit-message: + prefix: chore + include: scope + schedule: + interval: daily + + - package-ecosystem: docker + directory: /docs + commit-message: + prefix: chore + include: scope + schedule: + interval: daily + + - package-ecosystem: pip + directory: /docs + commit-message: + prefix: chore + include: scope + schedule: + interval: daily + + - package-ecosystem: pip + directory: /examples/event_handler_graphql/src + commit-message: + prefix: chore + include: scope + schedule: + interval: daily + + - package-ecosystem: gomod + directory: /layer/scripts/layer-balancer + commit-message: + prefix: chore + include: scope + schedule: + interval: daily + groups: + layer-balancer: + patterns: + - "*" diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/mergify.yml b/testbed/aws-powertools__powertools-lambda-python/.github/mergify.yml new file mode 100644 index 0000000000000000000000000000000000000000..dc3f195358695c1e8ab1199e7ee6059ac51b1b8e --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/mergify.yml @@ -0,0 +1,30 @@ +## Temporarily disabled after Mergify breaking changes +## might move to custom GitHub Actions altogether +# queue_rules: +# - name: default +# conditions: +# # Conditions to get out of the queue (= merged) +# - check-success=Semantic Pull Request +# - "#approved-reviews-by>=1" +# - -title~=(WIP|wip) +# - -label~="do-not-merge" +# - "#changes-requested-reviews-by=0" + +# pull_request_rules: +# - name: automatic merge for Dependabot pull requests +# conditions: +# - author~=^dependabot(|-preview)\[bot\]$ +# actions: +# queue: +# name: default +# method: squash +# commit_message: title+body + +# - name: Automatic merge ⬇️ on approval ✔ +# conditions: +# - "#approved-reviews-by>=2" +# actions: +# queue: +# name: default +# method: squash +# commit_message: title+body diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/release-drafter.yml b/testbed/aws-powertools__powertools-lambda-python/.github/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..b590898b51714fa110954e61f271f2d519ad915e --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/release-drafter.yml @@ -0,0 +1,37 @@ +change-template: "* $TITLE (#$NUMBER) by @$AUTHOR" +categories: + - title: "⚡ Breaking Changes" + labels: + - "breaking-change" + - title: "🌟New features and non-breaking changes" + labels: + - "feature" + - title: "📜 Documentation updates" + labels: + - "documentation" + - title: "🐛 Bug and hot fixes" + labels: + - "bug" + - "fix" + - title: "🚒 Deprecations" + labels: + - "deprecated" + - title: "🔧 Maintenance" + labels: + - "internal" + - "dependencies" +exclude-labels: + - "skip-changelog" +tag-template: "v$NEXT_PATCH_VERSION" +template: | + ## Summary + + **[Human readable summary of changes]** + + ## Changes + + $CHANGES + + ## This release was made possible by the following contributors: + + $CONTRIBUTORS diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/scripts/comment_on_large_pr.js b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/comment_on_large_pr.js new file mode 100644 index 0000000000000000000000000000000000000000..c17199faf76153c10a8ea4b044b9bfd1fd8a6b58 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/comment_on_large_pr.js @@ -0,0 +1,73 @@ +const { + PR_NUMBER, + PR_ACTION, + PR_AUTHOR, + IGNORE_AUTHORS, +} = require("./constants") + + +/** + * Notify PR author to split XXL PR in smaller chunks + * + * @param {object} core - core functions instance from @actions/core + * @param {object} gh_client - Pre-authenticated REST client (Octokit) + * @param {string} owner - GitHub Organization + * @param {string} repository - GitHub repository + */ +const notifyAuthor = async ({ + core, + gh_client, + owner, + repository, +}) => { + core.info(`Commenting on PR ${PR_NUMBER}`) + + let msg = `### ⚠️Large PR detected⚠️ + +Please consider breaking into smaller PRs to avoid significant review delays. Ignore if this PR has naturally grown to this size after reviews. + `; + + try { + await gh_client.rest.issues.createComment({ + owner: owner, + repo: repository, + body: msg, + issue_number: PR_NUMBER, + }); + } catch (error) { + core.setFailed("Failed to notify PR author to split large PR"); + console.error(err); + } +} + +module.exports = async ({github, context, core}) => { + if (IGNORE_AUTHORS.includes(PR_AUTHOR)) { + return core.notice("Author in IGNORE_AUTHORS list; skipping...") + } + + if (PR_ACTION != "labeled") { + return core.notice("Only run on PRs labeling actions; skipping") + } + + + /** @type {string[]} */ + const { data: labels } = await github.rest.issues.listLabelsOnIssue({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: PR_NUMBER, + }) + + // Schema: https://docs.github.com/en/rest/issues/labels#list-labels-for-an-issue + for (const label of labels) { + core.info(`Label: ${label}`) + if (label.name == "size/XXL") { + await notifyAuthor({ + core: core, + gh_client: github, + owner: context.repo.owner, + repository: context.repo.repo, + }) + break; + } + } +} diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/scripts/constants.js b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..8bfe55719740f97ae64ae1ec5c8dfb0250d402c3 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/constants.js @@ -0,0 +1,42 @@ +module.exports = Object.freeze({ + /** @type {string} */ + // Values: https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request + "PR_ACTION": process.env.PR_ACTION?.replace(/"/g, '') || "", + + /** @type {string} */ + "PR_AUTHOR": process.env.PR_AUTHOR?.replace(/"/g, '') || "", + + /** @type {string} */ + "PR_BODY": process.env.PR_BODY || "", + + /** @type {string} */ + "PR_TITLE": process.env.PR_TITLE || "", + + /** @type {number} */ + "PR_NUMBER": process.env.PR_NUMBER || 0, + + /** @type {string} */ + "PR_IS_MERGED": process.env.PR_IS_MERGED || "false", + + /** @type {string} */ + "PR_LABELS": process.env.PR_LABELS || "", + + /** @type {string} */ + "LABEL_BLOCK": "do-not-merge", + + /** @type {string} */ + "LABEL_BLOCK_REASON": "need-issue", + + /** @type {string} */ + "LABEL_BLOCK_MISSING_LICENSE_AGREEMENT": "need-license-agreement-acknowledge", + + /** @type {string} */ + "LABEL_PENDING_RELEASE": "pending-release", + + /** @type {string} */ + "HANDLE_MAINTAINERS_TEAM": "@aws-powertools/powertools-lambda-python", + + /** @type {string[]} */ + "IGNORE_AUTHORS": ["dependabot[bot]", "markdownify[bot]"], + +}); diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/scripts/download_pr_artifact.js b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/download_pr_artifact.js new file mode 100644 index 0000000000000000000000000000000000000000..274467c1f1c2a14de1920c2b4fc8fbcb1dfbf0c6 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/download_pr_artifact.js @@ -0,0 +1,26 @@ +module.exports = async ({github, context, core}) => { + const fs = require('fs'); + + const workflowRunId = process.env.WORKFLOW_ID; + core.info(`Listing artifacts for workflow run ${workflowRunId}`); + + const artifacts = await github.rest.actions.listWorkflowRunArtifacts({ + owner: context.repo.owner, + repo: context.repo.repo, + run_id: workflowRunId, + }); + + const matchArtifact = artifacts.data.artifacts.filter(artifact => artifact.name == "pr")[0]; + + core.info(`Downloading artifacts for workflow run ${workflowRunId}`); + const artifact = await github.rest.actions.downloadArtifact({ + owner: context.repo.owner, + repo: context.repo.repo, + artifact_id: matchArtifact.id, + archive_format: 'zip', + }); + + core.info("Saving artifact found", artifact); + + fs.writeFileSync('pr.zip', Buffer.from(artifact.data)); +} diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/scripts/enforce_acknowledgment.js b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/enforce_acknowledgment.js new file mode 100644 index 0000000000000000000000000000000000000000..3e3be636edee9d1c5c86a632e8143df46dde5630 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/enforce_acknowledgment.js @@ -0,0 +1,40 @@ +const { +PR_ACTION, +PR_AUTHOR, +PR_BODY, +PR_NUMBER, +IGNORE_AUTHORS, +LABEL_BLOCK, +LABEL_BLOCK_REASON +} = require("./constants") + +module.exports = async ({github, context, core}) => { + if (IGNORE_AUTHORS.includes(PR_AUTHOR)) { + return core.notice("Author in IGNORE_AUTHORS list; skipping...") + } + + if (PR_ACTION != "opened") { + return core.notice("Only newly open PRs are labelled to avoid spam; skipping") + } + + const RELATED_ISSUE_REGEX = /Issue number:[^\d\r\n]+(?<issue>\d+)/; + const isMatch = RELATED_ISSUE_REGEX.exec(PR_BODY); + if (isMatch == null) { + core.info(`No related issue found, maybe the author didn't use the template but there is one.`) + + let msg = "No related issues found. Please ensure there is an open issue related to this change to avoid significant delays or closure."; + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + body: msg, + issue_number: PR_NUMBER, + }); + + return await github.rest.issues.addLabels({ + issue_number: PR_NUMBER, + owner: context.repo.owner, + repo: context.repo.repo, + labels: [LABEL_BLOCK, LABEL_BLOCK_REASON] + }) + } +} diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/scripts/label_missing_acknowledgement_section.js b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/label_missing_acknowledgement_section.js new file mode 100644 index 0000000000000000000000000000000000000000..12b85241d1d6499b883cbbb22a2e95e3c0a643c1 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/label_missing_acknowledgement_section.js @@ -0,0 +1,41 @@ +const { + PR_ACTION, + PR_AUTHOR, + PR_BODY, + PR_NUMBER, + IGNORE_AUTHORS, + LABEL_BLOCK, + LABEL_BLOCK_MISSING_LICENSE_AGREEMENT +} = require("./constants") + +module.exports = async ({github, context, core}) => { + if (IGNORE_AUTHORS.includes(PR_AUTHOR)) { + return core.notice("Author in IGNORE_AUTHORS list; skipping...") + } + + if (PR_ACTION != "opened") { + return core.notice("Only newly open PRs are labelled to avoid spam; skipping") + } + + const RELATED_ACK_SECTION_REGEX = /By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice./; + + const isMatch = RELATED_ACK_SECTION_REGEX.exec(PR_BODY); + if (isMatch == null) { + core.info(`No acknowledgement section found, maybe the author didn't use the template but there is one.`) + + let msg = "No acknowledgement section found. Please make sure you used the template to open a PR and didn't remove the acknowledgment section. Check the template here: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/.github/PULL_REQUEST_TEMPLATE.md#acknowledgment"; + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + body: msg, + issue_number: PR_NUMBER, + }); + + return await github.rest.issues.addLabels({ + issue_number: PR_NUMBER, + owner: context.repo.owner, + repo: context.repo.repo, + labels: [LABEL_BLOCK, LABEL_BLOCK_MISSING_LICENSE_AGREEMENT] + }) + } +} diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/scripts/label_missing_related_issue.js b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/label_missing_related_issue.js new file mode 100644 index 0000000000000000000000000000000000000000..705e414c47f5ed4e14036dc1cf80306f526f2cdd --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/label_missing_related_issue.js @@ -0,0 +1,40 @@ +const { + PR_ACTION, + PR_AUTHOR, + PR_BODY, + PR_NUMBER, + IGNORE_AUTHORS, + LABEL_BLOCK, + LABEL_BLOCK_REASON +} = require("./constants") + +module.exports = async ({github, context, core}) => { + if (IGNORE_AUTHORS.includes(PR_AUTHOR)) { + return core.notice("Author in IGNORE_AUTHORS list; skipping...") + } + + if (PR_ACTION != "opened") { + return core.notice("Only newly open PRs are labelled to avoid spam; skipping") + } + + const RELATED_ISSUE_REGEX = /Issue number:[^\d\r\n]+(?<issue>\d+)/; + const isMatch = RELATED_ISSUE_REGEX.exec(PR_BODY); + if (isMatch == null) { + core.info(`No related issue found, maybe the author didn't use the template but there is one.`) + + let msg = "No related issues found. Please ensure there is an open issue related to this change to avoid significant delays or closure."; + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + body: msg, + issue_number: PR_NUMBER, + }); + + return await github.rest.issues.addLabels({ + issue_number: PR_NUMBER, + owner: context.repo.owner, + repo: context.repo.repo, + labels: [LABEL_BLOCK, LABEL_BLOCK_REASON] + }) + } +} diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/scripts/label_pr_based_on_title.js b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/label_pr_based_on_title.js new file mode 100644 index 0000000000000000000000000000000000000000..02f77f448b83dbeddf75470aba5c0c98f61e9f71 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/label_pr_based_on_title.js @@ -0,0 +1,62 @@ +const { PR_NUMBER, PR_TITLE, PR_LABELS } = require("./constants") + +module.exports = async ({github, context, core}) => { + const FEAT_REGEX = /feat(\((.+)\))?(:.+)/ + const BUG_REGEX = /(fix|bug)(\((.+)\))?(:.+)/ + const DOCS_REGEX = /(docs|doc)(\((.+)\))?(:.+)/ + const CHORE_REGEX = /(chore)(\((.+)\))?(:.+)/ + const DEPRECATED_REGEX = /(deprecated)(\((.+)\))?(:.+)/ + const REFACTOR_REGEX = /(refactor)(\((.+)\))?(:.+)/ + + const labels = { + "feature": FEAT_REGEX, + "bug": BUG_REGEX, + "documentation": DOCS_REGEX, + "internal": CHORE_REGEX, + "enhancement": REFACTOR_REGEX, + "deprecated": DEPRECATED_REGEX, + } + + // get PR labels from env + const prLabels = PR_LABELS.replaceAll("\"", "").split(","); + const labelKeys = Object.keys(labels); + + let miss = 0; + try { + for (const label in labels) { + const matcher = new RegExp(labels[label]) + const matches = matcher.exec(PR_TITLE) + if (matches != null) { + core.info(`Auto-labeling PR ${PR_NUMBER} with ${label}`) + + for (const prLabel of prLabels) { + if (labelKeys.includes(prLabel) && prLabel !== label) { + core.info(`PR previously tagged with: ${prLabel}, removing.`); + await github.rest.issues.removeLabel({ + issue_number: PR_NUMBER, + owner: context.repo.owner, + repo: context.repo.repo, + name: prLabel + }) + } + } + + await github.rest.issues.addLabels({ + issue_number: PR_NUMBER, + owner: context.repo.owner, + repo: context.repo.repo, + labels: [label] + }) + + return; + } else { + core.debug(`'${PR_TITLE}' didn't match '${label}' semantic.`) + miss += 1 + } + } + } finally { + if (miss == Object.keys(labels).length) { + core.notice(`PR ${PR_NUMBER} title '${PR_TITLE}' doesn't follow semantic titles; skipping...`) + } + } +} diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/scripts/label_related_issue.js b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/label_related_issue.js new file mode 100644 index 0000000000000000000000000000000000000000..790aac1ced5d36edb9addbc8c15ed8da83dcb669 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/label_related_issue.js @@ -0,0 +1,53 @@ +const { + PR_AUTHOR, + PR_BODY, + PR_NUMBER, + IGNORE_AUTHORS, + LABEL_PENDING_RELEASE, + HANDLE_MAINTAINERS_TEAM, + PR_IS_MERGED, +} = require("./constants") + +module.exports = async ({github, context, core}) => { + if (IGNORE_AUTHORS.includes(PR_AUTHOR)) { + return core.notice("Author in IGNORE_AUTHORS list; skipping...") + } + + if (PR_IS_MERGED == "false") { + return core.notice("Only merged PRs to avoid spam; skipping") + } + + const RELATED_ISSUE_REGEX = /Issue number:[^\d\r\n]+(?<issue>\d+)/; + + const isMatch = RELATED_ISSUE_REGEX.exec(PR_BODY); + + try { + if (!isMatch) { + core.setFailed(`Unable to find related issue for PR number ${PR_NUMBER}.\n\n Body details: ${PR_BODY}`); + return await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + body: `${HANDLE_MAINTAINERS_TEAM} No related issues found. Please ensure '${LABEL_PENDING_RELEASE}' label is applied before releasing.`, + issue_number: PR_NUMBER, + }); + } + } catch (error) { + core.setFailed(`Unable to create comment on PR number ${PR_NUMBER}.\n\n Error details: ${error}`); + throw new Error(error); + } + + const { groups: {issue} } = isMatch + + try { + core.info(`Auto-labeling related issue ${issue} for release`) + return await github.rest.issues.addLabels({ + issue_number: issue, + owner: context.repo.owner, + repo: context.repo.repo, + labels: [LABEL_PENDING_RELEASE] + }) + } catch (error) { + core.setFailed(`Is this issue number (${issue}) valid? Perhaps a discussion?`); + throw new Error(error); + } +} diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/scripts/post_release.js b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/post_release.js new file mode 100644 index 0000000000000000000000000000000000000000..d6a598f1960853c9344f080b3c1cbd34ad73d503 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/post_release.js @@ -0,0 +1,112 @@ +const STAGED_LABEL = "pending-release"; + +/** + * Fetch issues using GitHub REST API + * + * @param {object} gh_client - Pre-authenticated REST client (Octokit) + * @param {string} org - GitHub Organization + * @param {string} repository - GitHub repository + * @param {string} state - GitHub issue state (open, closed) + * @param {string} label - Comma-separated issue labels to fetch + * @return {Object[]} issues - Array of issues matching params + * @see {@link https://octokit.github.io/rest.js/v18#usage|Octokit client} + */ +const fetchIssues = async ({ + gh_client, + org, + repository, + state = "all", + label = STAGED_LABEL, +}) => { + + try { + const { data: issues } = await gh_client.rest.issues.listForRepo({ + owner: org, + repo: repository, + state: state, + labels: label, + }); + + return issues; + + } catch (error) { + console.error(error); + throw new Error("Failed to fetch issues") + } + +}; + +/** + * Notify new release and close staged GitHub issue + * + * @param {object} gh_client - Pre-authenticated REST client (Octokit) + * @param {string} owner - GitHub Organization + * @param {string} repository - GitHub repository + * @param {string} release_version - GitHub Release version + * @see {@link https://octokit.github.io/rest.js/v18#usage|Octokit client} + */ +const notifyRelease = async ({ + gh_client, + owner, + repository, + release_version, +}) => { + const release_url = `https://github.com/${owner}/${repository}/releases/tag/v${release_version}`; + + const issues = await fetchIssues({ + gh_client: gh_client, + org: owner, + repository: repository, + }); + + issues.forEach(async (issue) => { + console.info(`Updating issue number ${issue.number}`); + + const comment = `This is now released under [${release_version}](${release_url}) version!`; + try { + await gh_client.rest.issues.createComment({ + owner: owner, + repo: repository, + body: comment, + issue_number: issue.number, + }); + } catch (error) { + console.error(error); + throw new Error(`Failed to update issue ${issue.number} about ${release_version} release`) + } + + + // Close issue and remove staged label; keep existing ones + const labels = issue.labels + .filter((label) => label.name != STAGED_LABEL) + .map((label) => label.name); + + try { + await gh_client.rest.issues.update({ + repo: repository, + owner: owner, + issue_number: issue.number, + state: "closed", + labels: labels, + }); + } catch (error) { + console.error(error); + throw new Error("Failed to close issue") + } + + console.info(`Issue number ${issue.number} closed and updated`); + }); +}; + +// context: https://github.com/actions/toolkit/blob/main/packages/github/src/context.ts +module.exports = async ({ github, context }) => { + const { RELEASE_VERSION } = process.env; + console.log(`Running post-release script for ${RELEASE_VERSION} version`); + + await notifyRelease({ + gh_client: github, + owner: context.repo.owner, + repository: context.repo.repo, + release_version: RELEASE_VERSION, + }); +}; diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/scripts/save_pr_details.js b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/save_pr_details.js new file mode 100644 index 0000000000000000000000000000000000000000..ba2de975b3c4a2b17b03a78943c1e7c6c63f8272 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/scripts/save_pr_details.js @@ -0,0 +1,23 @@ +module.exports = async ({github, context, core}) => { + const fs = require('fs'); + const filename = "pr.txt"; + + const labelsData = await github.rest.issues.listLabelsOnIssue({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: (context.payload.issue || context.payload.pull_request || context.payload).number, + }); + + const labels = labelsData.data.map((label) => { + return label['name']; + }); + + try { + fs.writeFileSync(`./${filename}`, JSON.stringify({...context.payload, ...{labels:labels.join(",")}})); + + return `PR successfully saved ${filename}` + } catch (err) { + core.setFailed("Failed to save PR details"); + console.error(err); + } +} diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/semantic.yml b/testbed/aws-powertools__powertools-lambda-python/.github/semantic.yml new file mode 100644 index 0000000000000000000000000000000000000000..39119da8d05d103f0c0aa74513e4b11088c17a5b --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/semantic.yml @@ -0,0 +1,19 @@ +# conventional commit types: https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json +types: + - feat + - fix + - docs + - style + - refactor + - perf + - test + - build + - ci + - chore + - revert + - improv + +# Always validate the PR title +# and ignore the commits to lower the entry bar for contribution +# while titles make up the Release notes to ease maintenance overhead +titleOnly: true diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/stale.yml b/testbed/aws-powertools__powertools-lambda-python/.github/stale.yml new file mode 100644 index 0000000000000000000000000000000000000000..d0b1d54f4a3519290951da440b20f403281b2ac6 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/stale.yml @@ -0,0 +1,14 @@ +only: issues +daysUntilStale: 14 +daysUntilClose: 7 +exemptLabels: + - bug + - feature-request +staleLabel: pending-close-response-required +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. +closeComment: > + This issue has been automatically closed because of inactivity. + Please open a new issue if you are still encountering problems. diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/build_changelog.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/build_changelog.yml new file mode 100644 index 0000000000000000000000000000000000000000..ffa6163ca0399a50e82f724b89e5caba8c44555f --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/build_changelog.yml @@ -0,0 +1,31 @@ +# Standalone workflow to update changelog if necessary +name: Build changelog + +# PROCESS +# +# 1. Fetch latest changes compared to the latest tag +# 2. Rebuild CHANGELOG.md using Keep A Changelog format +# 3. Create a PR with the latest changelog (close and reference any it supersedes) + +# USAGE +# +# Always triggered on PR merge or manually from GitHub UI if we must. + +on: + workflow_dispatch: +# push: +# branches: +# - develop + schedule: + # Note: run daily at 10am UTC time until upstream git-chlog uses stable sorting + - cron: "0 10 * * *" + +permissions: + contents: read + +jobs: + changelog: + permissions: + contents: write # create temporary branch to store changelog changes + pull-requests: write # create PR with changelog changes + uses: ./.github/workflows/reusable_publish_changelog.yml diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/codeql-analysis.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/codeql-analysis.yml new file mode 100644 index 0000000000000000000000000000000000000000..196bc4989764ebc6bdb1bb987ce3953c8c80a32c --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/codeql-analysis.yml @@ -0,0 +1,38 @@ +name: "CodeQL" + +# PROCESS +# +# 1. Static code analysis with CodeQL + +# USAGE +# +# NOTE: This is our slowest workflow hence it only runs on code merged. +# +# Always triggered on PR merge when source code changes. + +on: + push: + branches: [develop] + +permissions: + contents: read + +jobs: + analyze: + name: Analyze + if: github.repository == 'aws-powertools/powertools-lambda-python' + runs-on: ubuntu-latest + permissions: + security-events: write + actions: read + + steps: + - name: Checkout repository + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@f31a31c052207cc13b328d6295c5b728bb49568c # v2.13.1 + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@f31a31c052207cc13b328d6295c5b728bb49568c # v2.13.1 diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/dependency-review.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/dependency-review.yml new file mode 100644 index 0000000000000000000000000000000000000000..74eee94fba47ec003015653b4329c00f17228f18 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/dependency-review.yml @@ -0,0 +1,22 @@ +# Dependency Review Action +# +# This Action will scan dependency manifest files that change as part of a Pull Request, +# surfacing known-vulnerable versions of the packages declared or updated in the PR. +# Once installed, if the workflow run is marked as required, +# PRs introducing known-vulnerable packages will be blocked from merging. +# +# Source repository: https://github.com/actions/dependency-review-action +name: 'Dependency Review' +on: [pull_request] + +permissions: + contents: read + +jobs: + dependency-review: + runs-on: ubuntu-latest + steps: + - name: 'Checkout Repository' + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: 'Dependency Review' + uses: actions/dependency-review-action@4081bf99e2866ebe428fc0477b69eb4fcda7220a # v4.4.0 diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/dispatch_analytics.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/dispatch_analytics.yml new file mode 100644 index 0000000000000000000000000000000000000000..3f4d75a024982721a6780f1983510b5fe64dd677 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/dispatch_analytics.yml @@ -0,0 +1,66 @@ +name: Dispatch analytics + +# PROCESS +# +# 1. Trade GitHub JWT token with AWS credentials for the analytics account +# 2. Invoke a Lambda function dispatcher synchronously with the read-only scoped JWT token +# 3. The dispatcher function will call GitHub APIs to read data from the last hour and aggregate for operational analytics + +# USAGE +# +# NOTE: meant to use as a scheduled task only (or manually for debugging purposes). + +on: + workflow_dispatch: + + schedule: + - cron: "0 * * * *" + +permissions: + contents: read + + +jobs: + dispatch_token: + if: github.repository == 'aws-powertools/powertools-lambda-python' + concurrency: + group: analytics + runs-on: ubuntu-latest + environment: analytics + permissions: + id-token: write + actions: read + checks: read + contents: read # previously we needed `write` to use GH_TOKEN in our dispatcher (Lambda) + deployments: read + issues: read + discussions: read + packages: read + pages: read + pull-requests: read + repository-projects: read + security-events: read + statuses: read + steps: + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@5fd3084fc36e372ff1fff382a39b10d03659f355 # v2.2.0 + with: + aws-region: eu-central-1 + role-to-assume: ${{ secrets.AWS_ANALYTICS_ROLE_ARN }} + + - name: Invoke Lambda function + run: | + payload=$(echo -n '{"githubToken": "${{ secrets.GITHUB_TOKEN }}"}' | base64) + response=$(aws lambda invoke \ + --function-name "${{ secrets.AWS_ANALYTICS_DISPATCHER_ARN }}" \ + --payload "$payload" \ + response.json \ + --query 'FunctionError' \ + --output text) + + cat response.json ; echo # add newline at the end + + if [ "$response" != "None" ]; then + echo "Error invoking lambda function: $response. Aborting." + exit 1 + fi diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/label_pr_on_title.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/label_pr_on_title.yml new file mode 100644 index 0000000000000000000000000000000000000000..65b649b2080c2118cecdb0839b66758b6095037c --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/label_pr_on_title.yml @@ -0,0 +1,67 @@ +name: Label PR based on title + +# PROCESS +# +# 1. Fetch PR details previously saved from untrusted location +# 2. Parse details for safety +# 3. Label PR based on semantic title (e.g., area, change type) + +# USAGE +# +# NOTE: meant to be used with ./.github/workflows/record_pr.yml +# +# Security Note: +# +# This workflow depends on "Record PR" workflow that runs in an untrusted location (forks) instead of `pull_request_target`. +# This enforces zero trust where "Record PR" workflow always runs on fork with zero permissions on GH_TOKEN. +# When "Record PR" completes, this workflow runs in our repository with the appropriate permissions and sanitize inputs. +# +# Coupled with "Approve GitHub Action to run on forks", we have confidence no privilege can be escalated, +# since any malicious change would need to be approved, and upon social engineering, it'll have zero permissions. + + +on: + workflow_run: + workflows: ["Record PR details"] + types: + - completed + +permissions: + contents: read + +jobs: + get_pr_details: + permissions: + actions: read # download PR artifact + contents: read # checkout code + # Guardrails to only ever run if PR recording workflow was indeed + # run in a PR event and ran successfully + if: ${{ github.event.workflow_run.conclusion == 'success' }} + uses: ./.github/workflows/reusable_export_pr_details.yml + with: + record_pr_workflow_id: ${{ github.event.workflow_run.id }} + workflow_origin: ${{ github.event.repository.full_name }} + secrets: + token: ${{ secrets.GITHUB_TOKEN }} + label_pr: + needs: get_pr_details + runs-on: ubuntu-latest + permissions: + pull-requests: write # label respective PR + steps: + - name: Checkout repository + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: "Label PR based on title" + uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1 + env: + PR_NUMBER: ${{ needs.get_pr_details.outputs.prNumber }} + PR_TITLE: ${{ needs.get_pr_details.outputs.prTitle }} + PR_LABELS: ${{ needs.get_pr_details.outputs.prLabels }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + # This safely runs in our base repo, not on fork + # thus allowing us to provide a write access token to label based on PR title + # and label PR based on semantic title accordingly + script: | + const script = require('.github/scripts/label_pr_based_on_title.js') + await script({github, context, core}) diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/layer_govcloud.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/layer_govcloud.yml new file mode 100644 index 0000000000000000000000000000000000000000..9c2d3e809b32129650ddb43ff8573d0993b42e8a --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/layer_govcloud.yml @@ -0,0 +1,220 @@ +# GovCloud Layer Publish +# --- +# This workflow publishes a specific layer version in an AWS account based on the environment input. +# +# Using a matrix, we pull each architecture and python version of the layer and store them as artifacts +# we upload them to each of the GovCloud AWS accounts. +# +# A number of safety checks are performed to ensure safety. + +on: + workflow_dispatch: + inputs: + environment: + description: Deployment environment + type: choice + options: + - Gamma + - Prod + required: true + version: + description: Layer version to duplicate + type: string + required: true + workflow_call: + inputs: + environment: + description: Deployment environment + type: string + required: true + version: + description: Layer version to duplicate + type: string + required: true + +name: Layer Deployment (GovCloud) +run-name: Layer Deployment (GovCloud) - ${{ inputs.environment }} + +jobs: + download: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + strategy: + matrix: + layer: + - AWSLambdaPowertoolsPythonV3-python38 + - AWSLambdaPowertoolsPythonV3-python39 + - AWSLambdaPowertoolsPythonV3-python310 + - AWSLambdaPowertoolsPythonV3-python311 + - AWSLambdaPowertoolsPythonV3-python312 + - AWSLambdaPowertoolsPythonV3-python313 + arch: + - arm64 + - x86_64 + environment: Prod (Readonly) + steps: + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2 + with: + role-to-assume: ${{ secrets.AWS_IAM_ROLE }} + aws-region: us-east-1 + mask-aws-account-id: true + - name: Grab Zip + run: | + aws --region us-east-1 lambda get-layer-version-by-arn --arn arn:aws:lambda:us-east-1:017000801446:layer:${{ matrix.layer }}-${{ matrix.arch }}:${{ inputs.version }} --query 'Content.Location' | xargs curl -L -o ${{ matrix.layer }}_${{ matrix.arch }}.zip + aws --region us-east-1 lambda get-layer-version-by-arn --arn arn:aws:lambda:us-east-1:017000801446:layer:${{ matrix.layer }}-${{ matrix.arch }}:${{ inputs.version }} > ${{ matrix.layer }}_${{ matrix.arch }}.json + - name: Store Zip + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 + with: + name: ${{ matrix.layer }}_${{ matrix.arch }}.zip + path: ${{ matrix.layer }}_${{ matrix.arch }}.zip + retention-days: 1 + if-no-files-found: error + - name: Store Metadata + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 + with: + name: ${{ matrix.layer }}_${{ matrix.arch }}.json + path: ${{ matrix.layer }}_${{ matrix.arch }}.json + retention-days: 1 + if-no-files-found: error + + copy_east: + name: Copy (East) + needs: download + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + strategy: + matrix: + layer: + - AWSLambdaPowertoolsPythonV3-python38 + - AWSLambdaPowertoolsPythonV3-python39 + - AWSLambdaPowertoolsPythonV3-python310 + - AWSLambdaPowertoolsPythonV3-python311 + - AWSLambdaPowertoolsPythonV3-python312 + - AWSLambdaPowertoolsPythonV3-python313 + arch: + - arm64 + - x86_64 + environment: GovCloud ${{ inputs.environment }} (East) + steps: + - name: Download Zip + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: ${{ matrix.layer }}_${{ matrix.arch }}.zip + - name: Download Metadata + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: ${{ matrix.layer }}_${{ matrix.arch }}.json + - name: Verify Layer Signature + run: | + SHA=$(jq -r '.Content.CodeSha256' '${{ matrix.layer }}_${{ matrix.arch }}.json') + test "$(openssl dgst -sha256 -binary ${{ matrix.layer }}_${{ matrix.arch }}.zip | openssl enc -base64)" == "$SHA" && echo "SHA OK: ${SHA}" || exit 1 + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2 + with: + role-to-assume: ${{ secrets.AWS_IAM_ROLE }} + aws-region: us-gov-east-1 + mask-aws-account-id: true + - name: Create Layer + id: create-layer + run: | + LAYER_VERSION=$(aws --region us-gov-east-1 lambda publish-layer-version \ + --layer-name ${{ matrix.layer }}-${{ matrix.arch }} \ + --zip-file fileb://./${{ matrix.layer }}_${{ matrix.arch }}.zip \ + --compatible-runtimes "$(jq -r '.CompatibleRuntimes[0]' '${{ matrix.layer }}_${{ matrix.arch }}.json')" \ + --compatible-architectures "$(jq -r '.CompatibleArchitectures[0]' '${{ matrix.layer }}_${{ matrix.arch }}.json')" \ + --license-info "MIT-0" \ + --description "$(jq -r '.Description' '${{ matrix.layer }}_${{ matrix.arch }}.json')" \ + --query 'Version' \ + --output text) + + echo "LAYER_VERSION=$LAYER_VERSION" >> "$GITHUB_OUTPUT" + + aws --region us-gov-east-1 lambda add-layer-version-permission \ + --layer-name '${{ matrix.layer }}-${{ matrix.arch }}' \ + --statement-id 'PublicLayer' \ + --action lambda:GetLayerVersion \ + --principal '*' \ + --version-number "$LAYER_VERSION" + - name: Verify Layer + env: + LAYER_VERSION: ${{ steps.create-layer.outputs.LAYER_VERSION }} + run: | + REMOTE_SHA=$(aws --region us-gov-east-1 lambda get-layer-version-by-arn --arn 'arn:aws-us-gov:lambda:us-gov-east-1:${{ secrets.AWS_ACCOUNT_ID }}:layer:${{ matrix.layer }}-${{ matrix.arch }}:${{ env.LAYER_VERSION }}' --query 'Content.CodeSha256' --output text) + SHA=$(jq -r '.Content.CodeSha256' '${{ matrix.layer }}_${{ matrix.arch }}.json') + test "$REMOTE_SHA" == "$SHA" && echo "SHA OK: ${SHA}" || exit 1 + aws --region us-gov-east-1 lambda get-layer-version-by-arn --arn 'arn:aws-us-gov:lambda:us-gov-east-1:${{ secrets.AWS_ACCOUNT_ID }}:layer:${{ matrix.layer }}-${{ matrix.arch }}:${{ env.LAYER_VERSION }}' --output table + + copy_west: + name: Copy (West) + needs: download + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + strategy: + matrix: + layer: + - AWSLambdaPowertoolsPythonV3-python38 + - AWSLambdaPowertoolsPythonV3-python39 + - AWSLambdaPowertoolsPythonV3-python310 + - AWSLambdaPowertoolsPythonV3-python311 + - AWSLambdaPowertoolsPythonV3-python312 + - AWSLambdaPowertoolsPythonV3-python313 + arch: + - arm64 + - x86_64 + environment: + name: GovCloud ${{ inputs.environment }} (West) + steps: + - name: Download Zip + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: ${{ matrix.layer }}_${{ matrix.arch }}.zip + - name: Download Metadata + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: ${{ matrix.layer }}_${{ matrix.arch }}.json + - name: Verify Layer Signature + run: | + SHA=$(jq -r '.Content.CodeSha256' '${{ matrix.layer }}_${{ matrix.arch }}.json') + test "$(openssl dgst -sha256 -binary ${{ matrix.layer }}_${{ matrix.arch }}.zip | openssl enc -base64)" == "$SHA" && echo "SHA OK: ${SHA}" || exit 1 + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2 + with: + role-to-assume: ${{ secrets.AWS_IAM_ROLE }} + aws-region: us-gov-west-1 + mask-aws-account-id: true + - name: Create Layer + id: create-layer + run: | + LAYER_VERSION=$(aws --region us-gov-west-1 lambda publish-layer-version \ + --layer-name ${{ matrix.layer }}-${{ matrix.arch }} \ + --zip-file fileb://./${{ matrix.layer }}_${{ matrix.arch }}.zip \ + --compatible-runtimes "$(jq -r '.CompatibleRuntimes[0]' '${{ matrix.layer }}_${{ matrix.arch }}.json')" \ + --compatible-architectures "$(jq -r '.CompatibleArchitectures[0]' '${{ matrix.layer }}_${{ matrix.arch }}.json')" \ + --license-info "MIT-0" \ + --description "$(jq -r '.Description' '${{ matrix.layer }}_${{ matrix.arch }}.json')" \ + --query 'Version' \ + --output text) + + echo "LAYER_VERSION=$LAYER_VERSION" >> "$GITHUB_OUTPUT" + + aws --region us-gov-west-1 lambda add-layer-version-permission \ + --layer-name '${{ matrix.layer }}-${{ matrix.arch }}' \ + --statement-id 'PublicLayer' \ + --action lambda:GetLayerVersion \ + --principal '*' \ + --version-number "$LAYER_VERSION" + - name: Verify Layer + env: + LAYER_VERSION: ${{ steps.create-layer.outputs.LAYER_VERSION }} + run: | + REMOTE_SHA=$(aws --region us-gov-west-1 lambda get-layer-version-by-arn --arn 'arn:aws-us-gov:lambda:us-gov-west-1:${{ secrets.AWS_ACCOUNT_ID }}:layer:${{ matrix.layer }}-${{ matrix.arch }}:${{ env.LAYER_VERSION }}' --query 'Content.CodeSha256' --output text) + SHA=$(jq -r '.Content.CodeSha256' '${{ matrix.layer }}_${{ matrix.arch }}.json') + test "$REMOTE_SHA" == "$SHA" && echo "SHA OK: ${SHA}" || exit 1 + aws --region us-gov-west-1 lambda get-layer-version-by-arn --arn 'arn:aws-us-gov:lambda:us-gov-west-1:${{ secrets.AWS_ACCOUNT_ID }}:layer:${{ matrix.layer }}-${{ matrix.arch }}:${{ env.LAYER_VERSION }}' --output table diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/layer_govcloud_python313.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/layer_govcloud_python313.yml new file mode 100644 index 0000000000000000000000000000000000000000..512b44c1ba77b023d79538ce3cb9564de071313d --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/layer_govcloud_python313.yml @@ -0,0 +1,205 @@ +# GovCloud Layer Publish +# --- +# This workflow publishes a specific layer version in an AWS account based on the environment input. +# +# Using a matrix, we pull each architecture and python version of the layer and store them as artifacts +# we upload them to each of the GovCloud AWS accounts. +# +# A number of safety checks are performed to ensure safety. + +on: + workflow_dispatch: + inputs: + environment: + description: Deployment environment + type: choice + options: + - Gamma + - Prod + required: true + version: + description: Layer version to duplicate + type: string + required: true + workflow_call: + inputs: + environment: + description: Deployment environment + type: string + required: true + version: + description: Layer version to duplicate + type: string + required: true + +name: Layer Deployment (GovCloud) - Temporary for Python 3.13 +run-name: Layer Deployment (GovCloud) - ${{ inputs.environment }} + +jobs: + download: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + strategy: + matrix: + layer: + - AWSLambdaPowertoolsPythonV3-python313 + arch: + - arm64 + - x86_64 + environment: Prod (Readonly) + steps: + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2 + with: + role-to-assume: ${{ secrets.AWS_IAM_ROLE }} + aws-region: us-east-1 + mask-aws-account-id: true + - name: Grab Zip + run: | + aws --region us-east-1 lambda get-layer-version-by-arn --arn arn:aws:lambda:us-east-1:017000801446:layer:${{ matrix.layer }}-${{ matrix.arch }}:${{ inputs.version }} --query 'Content.Location' | xargs curl -L -o ${{ matrix.layer }}_${{ matrix.arch }}.zip + aws --region us-east-1 lambda get-layer-version-by-arn --arn arn:aws:lambda:us-east-1:017000801446:layer:${{ matrix.layer }}-${{ matrix.arch }}:${{ inputs.version }} > ${{ matrix.layer }}_${{ matrix.arch }}.json + - name: Store Zip + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 + with: + name: ${{ matrix.layer }}_${{ matrix.arch }}.zip + path: ${{ matrix.layer }}_${{ matrix.arch }}.zip + retention-days: 1 + if-no-files-found: error + - name: Store Metadata + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 + with: + name: ${{ matrix.layer }}_${{ matrix.arch }}.json + path: ${{ matrix.layer }}_${{ matrix.arch }}.json + retention-days: 1 + if-no-files-found: error + + copy_east: + name: Copy (East) + needs: download + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + strategy: + matrix: + layer: + - AWSLambdaPowertoolsPythonV3-python313 + arch: + - arm64 + - x86_64 + environment: GovCloud ${{ inputs.environment }} (East) + steps: + - name: Download Zip + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: ${{ matrix.layer }}_${{ matrix.arch }}.zip + - name: Download Metadata + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: ${{ matrix.layer }}_${{ matrix.arch }}.json + - name: Verify Layer Signature + run: | + SHA=$(jq -r '.Content.CodeSha256' '${{ matrix.layer }}_${{ matrix.arch }}.json') + test "$(openssl dgst -sha256 -binary ${{ matrix.layer }}_${{ matrix.arch }}.zip | openssl enc -base64)" == "$SHA" && echo "SHA OK: ${SHA}" || exit 1 + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2 + with: + role-to-assume: ${{ secrets.AWS_IAM_ROLE }} + aws-region: us-gov-east-1 + mask-aws-account-id: true + - name: Create Layer + id: create-layer + run: | + LAYER_VERSION=$(aws --region us-gov-east-1 lambda publish-layer-version \ + --layer-name ${{ matrix.layer }}-${{ matrix.arch }} \ + --zip-file fileb://./${{ matrix.layer }}_${{ matrix.arch }}.zip \ + --compatible-runtimes "$(jq -r '.CompatibleRuntimes[0]' '${{ matrix.layer }}_${{ matrix.arch }}.json')" \ + --compatible-architectures "$(jq -r '.CompatibleArchitectures[0]' '${{ matrix.layer }}_${{ matrix.arch }}.json')" \ + --license-info "MIT-0" \ + --description "$(jq -r '.Description' '${{ matrix.layer }}_${{ matrix.arch }}.json')" \ + --query 'Version' \ + --output text) + + echo "LAYER_VERSION=$LAYER_VERSION" >> "$GITHUB_OUTPUT" + + aws --region us-gov-east-1 lambda add-layer-version-permission \ + --layer-name '${{ matrix.layer }}-${{ matrix.arch }}' \ + --statement-id 'PublicLayer' \ + --action lambda:GetLayerVersion \ + --principal '*' \ + --version-number "$LAYER_VERSION" + - name: Verify Layer + env: + LAYER_VERSION: ${{ steps.create-layer.outputs.LAYER_VERSION }} + run: | + REMOTE_SHA=$(aws --region us-gov-east-1 lambda get-layer-version-by-arn --arn 'arn:aws-us-gov:lambda:us-gov-east-1:${{ secrets.AWS_ACCOUNT_ID }}:layer:${{ matrix.layer }}-${{ matrix.arch }}:${{ env.LAYER_VERSION }}' --query 'Content.CodeSha256' --output text) + SHA=$(jq -r '.Content.CodeSha256' '${{ matrix.layer }}_${{ matrix.arch }}.json') + test "$REMOTE_SHA" == "$SHA" && echo "SHA OK: ${SHA}" || exit 1 + aws --region us-gov-east-1 lambda get-layer-version-by-arn --arn 'arn:aws-us-gov:lambda:us-gov-east-1:${{ secrets.AWS_ACCOUNT_ID }}:layer:${{ matrix.layer }}-${{ matrix.arch }}:${{ env.LAYER_VERSION }}' --output table + + copy_west: + name: Copy (West) + needs: download + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + strategy: + matrix: + layer: + - AWSLambdaPowertoolsPythonV3-python313 + arch: + - arm64 + - x86_64 + environment: + name: GovCloud ${{ inputs.environment }} (West) + steps: + - name: Download Zip + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: ${{ matrix.layer }}_${{ matrix.arch }}.zip + - name: Download Metadata + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: ${{ matrix.layer }}_${{ matrix.arch }}.json + - name: Verify Layer Signature + run: | + SHA=$(jq -r '.Content.CodeSha256' '${{ matrix.layer }}_${{ matrix.arch }}.json') + test "$(openssl dgst -sha256 -binary ${{ matrix.layer }}_${{ matrix.arch }}.zip | openssl enc -base64)" == "$SHA" && echo "SHA OK: ${SHA}" || exit 1 + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2 + with: + role-to-assume: ${{ secrets.AWS_IAM_ROLE }} + aws-region: us-gov-west-1 + mask-aws-account-id: true + - name: Create Layer + id: create-layer + run: | + LAYER_VERSION=$(aws --region us-gov-west-1 lambda publish-layer-version \ + --layer-name ${{ matrix.layer }}-${{ matrix.arch }} \ + --zip-file fileb://./${{ matrix.layer }}_${{ matrix.arch }}.zip \ + --compatible-runtimes "$(jq -r '.CompatibleRuntimes[0]' '${{ matrix.layer }}_${{ matrix.arch }}.json')" \ + --compatible-architectures "$(jq -r '.CompatibleArchitectures[0]' '${{ matrix.layer }}_${{ matrix.arch }}.json')" \ + --license-info "MIT-0" \ + --description "$(jq -r '.Description' '${{ matrix.layer }}_${{ matrix.arch }}.json')" \ + --query 'Version' \ + --output text) + + echo "LAYER_VERSION=$LAYER_VERSION" >> "$GITHUB_OUTPUT" + + aws --region us-gov-west-1 lambda add-layer-version-permission \ + --layer-name '${{ matrix.layer }}-${{ matrix.arch }}' \ + --statement-id 'PublicLayer' \ + --action lambda:GetLayerVersion \ + --principal '*' \ + --version-number "$LAYER_VERSION" + - name: Verify Layer + env: + LAYER_VERSION: ${{ steps.create-layer.outputs.LAYER_VERSION }} + run: | + REMOTE_SHA=$(aws --region us-gov-west-1 lambda get-layer-version-by-arn --arn 'arn:aws-us-gov:lambda:us-gov-west-1:${{ secrets.AWS_ACCOUNT_ID }}:layer:${{ matrix.layer }}-${{ matrix.arch }}:${{ env.LAYER_VERSION }}' --query 'Content.CodeSha256' --output text) + SHA=$(jq -r '.Content.CodeSha256' '${{ matrix.layer }}_${{ matrix.arch }}.json') + test "$REMOTE_SHA" == "$SHA" && echo "SHA OK: ${SHA}" || exit 1 + aws --region us-gov-west-1 lambda get-layer-version-by-arn --arn 'arn:aws-us-gov:lambda:us-gov-west-1:${{ secrets.AWS_ACCOUNT_ID }}:layer:${{ matrix.layer }}-${{ matrix.arch }}:${{ env.LAYER_VERSION }}' --output table diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/layer_govcloud_verify.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/layer_govcloud_verify.yml new file mode 100644 index 0000000000000000000000000000000000000000..736077698a513f6b2931ffd28ba4432b4f0224c8 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/layer_govcloud_verify.yml @@ -0,0 +1,114 @@ +# GovCloud Layer Verification +# --- +# This workflow queries the GovCloud layer info in production only + +on: + workflow_dispatch: + inputs: + version: + description: Layer version to verify information + type: string + required: true + workflow_call: + inputs: + version: + description: Layer version to verify information + type: string + required: true + +name: Layer Verification (GovCloud) +run-name: Layer Verification (GovCloud) + +jobs: + commercial: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + strategy: + matrix: + layer: + - AWSLambdaPowertoolsPythonV3-python38 + - AWSLambdaPowertoolsPythonV3-python39 + - AWSLambdaPowertoolsPythonV3-python310 + - AWSLambdaPowertoolsPythonV3-python311 + - AWSLambdaPowertoolsPythonV3-python312 + - AWSLambdaPowertoolsPythonV3-python313 + arch: + - arm64 + - x86_64 + environment: Prod (Readonly) + steps: + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2 + with: + role-to-assume: ${{ secrets.AWS_IAM_ROLE }} + aws-region: us-east-1 + mask-aws-account-id: true + - name: Output ${{ matrix.layer }}-${{ matrix.arch }} + run: | + aws --region us-east-1 lambda get-layer-version-by-arn --arn 'arn:aws:lambda:us-east-1:017000801446:layer:${{ matrix.layer }}-${{ matrix.arch }}:${{ inputs.version }}' | jq -r '{"Layer Version Arn": .LayerVersionArn, "Version": .Version, "Description": .Description, "Compatible Runtimes": .CompatibleRuntimes[0], "Compatible Architectures": .CompatibleArchitectures[0], "SHA": .Content.CodeSha256} | keys[] as $k | [$k, .[$k]] | @tsv' | column -t -s $'\t' + + gov_east: + name: Verify (East) + needs: commercial + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + strategy: + matrix: + layer: + - AWSLambdaPowertoolsPythonV3-python38 + - AWSLambdaPowertoolsPythonV3-python39 + - AWSLambdaPowertoolsPythonV3-python310 + - AWSLambdaPowertoolsPythonV3-python311 + - AWSLambdaPowertoolsPythonV3-python312 + - AWSLambdaPowertoolsPythonV3-python313 + arch: + - arm64 + - x86_64 + environment: GovCloud Prod (East) + steps: + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2 + with: + role-to-assume: ${{ secrets.AWS_IAM_ROLE }} + aws-region: us-gov-east-1 + mask-aws-account-id: true + - name: Verify Layer ${{ matrix.layer }}-${{ matrix.arch }} + id: verify-layer + run: | + aws --region us-gov-east-1 lambda get-layer-version-by-arn --arn 'arn:aws-us-gov:lambda:us-gov-east-1:${{ secrets.AWS_ACCOUNT_ID }}:layer:${{ matrix.layer }}-${{ matrix.arch }}:${{ inputs.version }}' | jq -r '{"Layer Version Arn": .LayerVersionArn, "Version": .Version, "Description": .Description, "Compatible Runtimes": .CompatibleRuntimes[0], "Compatible Architectures": .CompatibleArchitectures[0], "SHA": .Content.CodeSha256} | keys[] as $k | [$k, .[$k]] | @tsv' | column -t -s $'\t' + + gov_west: + name: Verify (West) + needs: commercial + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + strategy: + matrix: + layer: + - AWSLambdaPowertoolsPythonV3-python38 + - AWSLambdaPowertoolsPythonV3-python39 + - AWSLambdaPowertoolsPythonV3-python310 + - AWSLambdaPowertoolsPythonV3-python311 + - AWSLambdaPowertoolsPythonV3-python312 + - AWSLambdaPowertoolsPythonV3-python313 + arch: + - arm64 + - x86_64 + environment: GovCloud Prod (West) + steps: + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2 + with: + role-to-assume: ${{ secrets.AWS_IAM_ROLE }} + aws-region: us-gov-east-1 + mask-aws-account-id: true + - name: Verify Layer ${{ matrix.layer }}-${{ matrix.arch }} + id: verify-layer + run: | + aws --region us-gov-west-1 lambda get-layer-version-by-arn --arn 'arn:aws-us-gov:lambda:us-gov-west-1:${{ secrets.AWS_ACCOUNT_ID }}:layer:${{ matrix.layer }}-${{ matrix.arch }}:${{ inputs.version }}' | jq -r '{"Layer Version Arn": .LayerVersionArn, "Version": .Version, "Description": .Description, "Compatible Runtimes": .CompatibleRuntimes[0], "Compatible Architectures": .CompatibleArchitectures[0], "SHA": .Content.CodeSha256} | keys[] as $k | [$k, .[$k]] | @tsv' | column -t -s $'\t' diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/layer_rename.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/layer_rename.yml new file mode 100644 index 0000000000000000000000000000000000000000..cd965fe00e20f3a24589b9eac0d608a734e08903 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/layer_rename.yml @@ -0,0 +1,163 @@ +# Rename Layer +# --- +# This workflow copies a specific layer version in an AWS account, renaming it in the process +# +# Using a matrix, we pull each architecture and python version of the layer and store them as artifacts +# we upload them to each of the AWS accounts. +# +# A number of safety checks are performed to ensure safety. + +on: + workflow_dispatch: + inputs: + environment: + description: Deployment environment + type: choice + options: + - beta + - prod + default: beta + required: true + version: + description: Layer version to duplicate + type: string + required: true + workflow_call: + inputs: + environment: + description: Deployment environment + type: string + required: true + version: + description: Layer version to duplicate + type: string + required: true + +name: Layer Rename +run-name: Layer Rename - ${{ inputs.environment }} + +permissions: + contents: read + +jobs: + download: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + strategy: + matrix: + layer: + - AWSLambdaPowertoolsPythonV3-python38 + - AWSLambdaPowertoolsPythonV3-python39 + - AWSLambdaPowertoolsPythonV3-python310 + - AWSLambdaPowertoolsPythonV3-python311 + - AWSLambdaPowertoolsPythonV3-python312 + environment: layer-prod + steps: + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2 + with: + role-to-assume: ${{ secrets.AWS_LAYERS_ROLE_ARN }} + aws-region: us-east-1 + mask-aws-account-id: true + - name: Grab Zip + run: | + aws --region us-east-1 lambda get-layer-version-by-arn --arn arn:aws:lambda:us-east-1:017000801446:layer:${{ matrix.layer }}-x86:${{ inputs.version }} --query 'Content.Location' | xargs curl -L -o ${{ matrix.layer }}_x86_64.zip + aws --region us-east-1 lambda get-layer-version-by-arn --arn arn:aws:lambda:us-east-1:017000801446:layer:${{ matrix.layer }}-x86:${{ inputs.version }} > ${{ matrix.layer }}_x86_64.json + - name: Store Zip + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 + with: + name: ${{ matrix.layer }}_x86_64.zip + path: ${{ matrix.layer }}_x86_64.zip + retention-days: 1 + if-no-files-found: error + - name: Store Metadata + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 + with: + name: ${{ matrix.layer }}_x86_64.json + path: ${{ matrix.layer }}_x86_64.json + retention-days: 1 + if-no-files-found: error + + copy: + name: Copy + needs: download + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + strategy: + matrix: + layer: + - AWSLambdaPowertoolsPythonV3-python38 + - AWSLambdaPowertoolsPythonV3-python39 + - AWSLambdaPowertoolsPythonV3-python310 + - AWSLambdaPowertoolsPythonV3-python311 + - AWSLambdaPowertoolsPythonV3-python312 + region: + - "af-south-1" + - "ap-east-1" + - "ap-northeast-1" + - "ap-northeast-2" + - "ap-northeast-3" + - "ap-south-1" + - "ap-south-2" + - "ap-southeast-1" + - "ap-southeast-2" + - "ap-southeast-3" + - "ap-southeast-4" + - "ca-central-1" + - "ca-west-1" + - "eu-central-1" + - "eu-central-2" + - "eu-north-1" + - "eu-south-1" + - "eu-south-2" + - "eu-west-1" + - "eu-west-2" + - "eu-west-3" + - "il-central-1" + - "me-central-1" + - "me-south-1" + - "sa-east-1" + - "us-east-1" + - "us-east-2" + - "us-west-1" + - "us-west-2" + environment: layer-${{ inputs.environment }} + steps: + - name: Download Zip + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: ${{ matrix.layer }}_x86_64.zip + - name: Download Metadata + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: ${{ matrix.layer }}_x86_64.json + - name: Verify Layer Signature + run: | + SHA=$(jq -r '.Content.CodeSha256' ${{ matrix.layer }}_x86_64.json) + test $(openssl dgst -sha256 -binary ${{ matrix.layer }}_x86_64.zip | openssl enc -base64) == $SHA && echo "SHA OK: ${SHA}" || exit 1 + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2 + with: + role-to-assume: ${{ secrets.AWS_LAYERS_ROLE_ARN }} + aws-region: ${{ matrix.region }} + mask-aws-account-id: true + - name: Create Layer + run: | + aws --region ${{ matrix.region }} lambda publish-layer-version \ + --layer-name ${{ matrix.layer }}-x86_64 \ + --zip-file fileb://./${{ matrix.layer }}_x86_64.zip \ + --compatible-runtimes $(jq -r ".CompatibleRuntimes[0]" ${{ matrix.layer }}_x86_64.json) \ + --compatible-architectures $(jq -r ".CompatibleArchitectures[0]" ${{ matrix.layer }}_x86_64.json) \ + --license-info "MIT-0" \ + --description "$(jq -r '.Description' ${{ matrix.layer }}_x86_64.json)" \ + --query 'Version' | \ + xargs aws --region ${{ matrix.region }} lambda add-layer-version-permission \ + --layer-name ${{ matrix.layer }}-x86_64 \ + --statement-id 'PublicLayer' \ + --action lambda:GetLayerVersion \ + --principal '*' \ + --version-number diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_closed_issues.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_closed_issues.yml new file mode 100644 index 0000000000000000000000000000000000000000..61f4d20460d090a274698f78bf1a49c34a2f8134 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_closed_issues.yml @@ -0,0 +1,33 @@ +name: Closed Issue Message + +# PROCESS +# +# 1. Comment on recently closed issues to warn future responses may not be looked after + +# USAGE +# +# Always triggered upon issue closure +# + +on: + issues: + types: [closed] +permissions: + contents: read + +jobs: + auto_comment: + runs-on: ubuntu-latest + permissions: + issues: write # comment on issues + steps: + - uses: aws-actions/closed-issue-message@80edfc24bdf1283400eb04d20a8a605ae8bf7d48 + with: + repo-token: "${{ secrets.GITHUB_TOKEN }}" + message: | + ### ⚠️COMMENT VISIBILITY WARNING⚠️ + This issue is now closed. Please be mindful that future comments are hard for our team to see. + + If you need more assistance, please either tag a [team member](https://github.com/aws-powertools/powertools-lambda-python/blob/develop/MAINTAINERS.md#current-maintainers) or open a new issue that references this one. + + If you wish to keep having a conversation with other community members under this issue feel free to do so. diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_label_added.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_label_added.yml new file mode 100644 index 0000000000000000000000000000000000000000..50ba09921889f9615c2aa5d9eba7a71025acd657 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_label_added.yml @@ -0,0 +1,62 @@ +name: On Label added + +# PROCESS +# +# 1. Fetch PR details previously saved from untrusted location +# 2. Parse details for safety +# 3. Comment on PR labels `size/XXL` and suggest splitting into smaller PRs if possible + +# USAGE +# +# NOTE: meant to be used with ./.github/workflows/record_pr.yml +# +# Security Note: +# +# This workflow depends on "Record PR" workflow that runs in an untrusted location (forks) instead of `pull_request_target`. +# This enforces zero trust where "Record PR" workflow always runs on fork with zero permissions on GH_TOKEN. +# When "Record PR" completes, this workflow runs in our repository with the appropriate permissions and sanitize inputs. +# +# Coupled with "Approve GitHub Action to run on forks", we have confidence no privilege can be escalated, +# since any malicious change would need to be approved, and upon social engineering, it'll have zero permissions. + +on: + workflow_run: + workflows: ["Record PR details"] + types: + - completed + +permissions: + contents: read + +jobs: + get_pr_details: + permissions: + actions: read # download PR artifact + contents: read # checkout code + if: ${{ github.event.workflow_run.conclusion == 'success' }} + uses: ./.github/workflows/reusable_export_pr_details.yml + with: + record_pr_workflow_id: ${{ github.event.workflow_run.id }} + workflow_origin: ${{ github.event.repository.full_name }} + secrets: + token: ${{ secrets.GITHUB_TOKEN }} + + split_large_pr: + needs: get_pr_details + runs-on: ubuntu-latest + permissions: + pull-requests: write # comment on PR + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + # Maintenance: Persist state per PR as an artifact to avoid spam on label add + - name: "Suggest split large Pull Request" + uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1 + env: + PR_NUMBER: ${{ needs.get_pr_details.outputs.prNumber }} + PR_ACTION: ${{ needs.get_pr_details.outputs.prAction }} + PR_AUTHOR: ${{ needs.get_pr_details.outputs.prAuthor }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const script = require('.github/scripts/comment_on_large_pr.js'); + await script({github, context, core}); diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_merged_pr.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_merged_pr.yml new file mode 100644 index 0000000000000000000000000000000000000000..68eaf552e1614b65da0eabe710c19cc77724112e --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_merged_pr.yml @@ -0,0 +1,64 @@ +name: On PR merge + +# PROCESS +# +# 1. Fetch PR details previously saved from untrusted location +# 2. Parse details for safety +# 3. Add `pending-release` label for related issue +# 4. Make a comment in PR if related issue is invalid or can't be labeled + +# USAGE +# +# NOTE: meant to be used with ./.github/workflows/record_pr.yml +# +# Security Note: +# +# This workflow depends on "Record PR" workflow that runs in an untrusted location (forks) instead of `pull_request_target`. +# This enforces zero trust where "Record PR" workflow always runs on fork with zero permissions on GH_TOKEN. +# When "Record PR" completes, this workflow runs in our repository with the appropriate permissions and sanitize inputs. +# +# Coupled with "Approve GitHub Action to run on forks", we have confidence no privilege can be escalated, +# since any malicious change would need to be approved, and upon social engineering, it'll have zero permissions. + +on: + workflow_run: + workflows: ["Record PR details"] + types: + - completed + +permissions: + contents: read + +jobs: + get_pr_details: + permissions: + actions: read # download PR artifact + contents: read # checkout code + if: github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success' + uses: ./.github/workflows/reusable_export_pr_details.yml + with: + record_pr_workflow_id: ${{ github.event.workflow_run.id }} + workflow_origin: ${{ github.event.repository.full_name }} + secrets: + token: ${{ secrets.GITHUB_TOKEN }} + release_label_on_merge: + needs: get_pr_details + runs-on: ubuntu-latest + permissions: + pull-requests: write # make a comment in PR if unable to find related issue + issues: write # label issue with pending-release + if: needs.get_pr_details.outputs.prIsMerged == 'true' + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: "Label PR related issue for release" + uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1 + env: + PR_NUMBER: ${{ needs.get_pr_details.outputs.prNumber }} + PR_BODY: ${{ needs.get_pr_details.outputs.prBody }} + PR_IS_MERGED: ${{ needs.get_pr_details.outputs.prIsMerged }} + PR_AUTHOR: ${{ needs.get_pr_details.outputs.prAuthor }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const script = require('.github/scripts/label_related_issue.js') + await script({github, context, core}) diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_opened_pr.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_opened_pr.yml new file mode 100644 index 0000000000000000000000000000000000000000..0db1bcaa02694a3cd392c1736caadb8a561e371d --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_opened_pr.yml @@ -0,0 +1,81 @@ +name: On new PR + +# PROCESS +# +# 1. Fetch PR details previously saved from untrusted location +# 2. Parse details for safety +# 3. Confirm there is a related issue for newly opened PR +# 4. Verify if PR template is used and legal acknowledgement hasn't been removed + +# USAGE +# +# NOTE: meant to be used with ./.github/workflows/record_pr.yml +# +# Security Note: +# +# This workflow depends on "Record PR" workflow that runs in an untrusted location (forks) instead of `pull_request_target`. +# This enforces zero trust where "Record PR" workflow always runs on fork with zero permissions on GH_TOKEN. +# When "Record PR" completes, this workflow runs in our repository with the appropriate permissions and sanitize inputs. +# +# Coupled with "Approve GitHub Action to run on forks", we have confidence no privilege can be escalated, +# since any malicious change would need to be approved, and upon social engineering, it'll have zero permissions. + +on: + workflow_run: + workflows: ["Record PR details"] + types: + - completed + +permissions: + contents: read + +jobs: + get_pr_details: + permissions: + actions: read # download PR artifact + contents: read # checkout code + if: ${{ github.event.workflow_run.conclusion == 'success' }} + uses: ./.github/workflows/reusable_export_pr_details.yml + with: + record_pr_workflow_id: ${{ github.event.workflow_run.id }} + workflow_origin: ${{ github.event.repository.full_name }} + secrets: + token: ${{ secrets.GITHUB_TOKEN }} + check_related_issue: + permissions: + pull-requests: write # label and comment on PR if missing related issue (requirement) + needs: get_pr_details + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: "Ensure related issue is present" + uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1 + env: + PR_BODY: ${{ needs.get_pr_details.outputs.prBody }} + PR_NUMBER: ${{ needs.get_pr_details.outputs.prNumber }} + PR_ACTION: ${{ needs.get_pr_details.outputs.prAction }} + PR_AUTHOR: ${{ needs.get_pr_details.outputs.prAuthor }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const script = require('.github/scripts/label_missing_related_issue.js') + await script({github, context, core}) + check_acknowledge_section: + needs: get_pr_details + runs-on: ubuntu-latest + permissions: + pull-requests: write # label and comment on PR if missing acknowledge section (requirement) + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: "Ensure acknowledgement section is present" + uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1 + env: + PR_BODY: ${{ needs.get_pr_details.outputs.prBody }} + PR_NUMBER: ${{ needs.get_pr_details.outputs.prNumber }} + PR_ACTION: ${{ needs.get_pr_details.outputs.prAction }} + PR_AUTHOR: ${{ needs.get_pr_details.outputs.prAuthor }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const script = require('.github/scripts/label_missing_acknowledgement_section.js') + await script({github, context, core}) diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_pr_updates.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_pr_updates.yml new file mode 100644 index 0000000000000000000000000000000000000000..2663d7073992a0369aa6ee3bf919b377cbe2a738 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_pr_updates.yml @@ -0,0 +1,36 @@ +# Fail PR check if do-not-merge label is present +name: PR requirements + +# PROCESS +# +# 1. Verify whether 'do-not-merge' label is present +# 2. Fail PR to prevent merging until resolved +# 3. Pass PR if do-not-merge label is removed by a maintainer + +# USAGE +# +# Always triggered on PR labeling changes. + +# NOTES +# +# PR requirements are checked async in on_opened_pr.yml and enforced here synchronously +# due to limitations in GH API. + +on: + pull_request: + types: + - opened + - labeled + - unlabeled + +permissions: {} # no permission required + +jobs: + check-requirements: + runs-on: ubuntu-latest + steps: + - name: Block if it doesn't minimum requirements + if: contains(github.event.pull_request.labels.*.name, 'do-not-merge') + run: | + echo "This PR does not meet minimum requirements (check PR comments)." + exit 1 diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_push_docs.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_push_docs.yml new file mode 100644 index 0000000000000000000000000000000000000000..fc1aa3786e66816f8d34c5e346c2dbe13c9f344f --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_push_docs.yml @@ -0,0 +1,36 @@ +name: Docs + +# PROCESS +# +# 1. Build User Guide and API docs +# 2. Publish to GitHub Pages +# 3. Publish to S3 (new home) + +# USAGE +# +# Always triggered on PR merge when changes in documentation changes occur. + +on: + push: + branches: + - develop + paths: + - "docs/**" + - "mkdocs.yml" + - "examples/**" + - "CHANGELOG.md" + +permissions: + contents: read + +jobs: + release-docs: + permissions: + contents: write # push to gh-pages + pages: write # deploy gh-pages website + id-token: write # trade JWT token for AWS credentials in AWS Docs account + secrets: inherit + uses: ./.github/workflows/reusable_publish_docs.yml + with: + version: develop + alias: stage \ No newline at end of file diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_schedule_monthly_roadmap_reminder.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_schedule_monthly_roadmap_reminder.yml new file mode 100644 index 0000000000000000000000000000000000000000..a274e2dea08ff381b0dbbcda6227ceb8425a20d4 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/on_schedule_monthly_roadmap_reminder.yml @@ -0,0 +1,22 @@ +name: Monthly roadmap reminder + +on: + workflow_dispatch: {} + schedule: + - cron: '0 0 1 * *' # runs first day of the month + +permissions: + contents: read + + +jobs: + call-workflow-passing-data: + permissions: + contents: read + pull-requests: read + issues: write # create monthly roadmap report + + # setting to `@main` until we have releases and governance installed + uses: aws-powertools/actions/.github/workflows/monthly_roadmap_reminder.yml@main + secrets: + token: ${{ secrets.GITHUB_TOKEN }} diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/ossf_scorecard.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/ossf_scorecard.yml new file mode 100644 index 0000000000000000000000000000000000000000..6339569edef4575e92deec7cfdf8d62dd239a6f4 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/ossf_scorecard.yml @@ -0,0 +1,48 @@ +name: Scorecard supply-chain security +on: + # For Branch-Protection check. Only the default branch is supported. See + # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection + branch_protection_rule: + schedule: + - cron: "0 9 * * *" + push: + branches: [develop] + workflow_dispatch: + +permissions: read-all + +jobs: + analysis: + name: Scorecard analysis + runs-on: ubuntu-latest + environment: scorecard + permissions: + security-events: write # update code-scanning dashboard + id-token: write # confirm org+repo identity before publish results + + steps: + - name: "Checkout code" + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + persist-credentials: false + + - name: "Run analysis" + uses: ossf/scorecard-action@62b2cac7ed8198b15735ed49ab1e5cf35480ba46 # v2.4.0 + with: + results_file: results.sarif + results_format: sarif + publish_results: true # publish to OSSF Scorecard REST API + repo_token: ${{ secrets.SCORECARD_TOKEN }} # read-only fine-grained token to read branch protection settings + + - name: "Upload results" + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 + with: + name: SARIF file + path: results.sarif + retention-days: 5 + + # Upload the results to GitHub's code scanning dashboard. + - name: "Upload to code-scanning" + uses: github/codeql-action/upload-sarif@17573ee1cc1b9d061760f3a006fc4aac4f944fd5 # v2.2.4 + with: + sarif_file: results.sarif diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/pre-release.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/pre-release.yml new file mode 100644 index 0000000000000000000000000000000000000000..f678c966fc47c78240342840f0b48b65850460cf --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/pre-release.yml @@ -0,0 +1,275 @@ +name: Pre-Release + +# PRE-RELEASE PROCESS +# +# === Automated activities === +# +# 1. [Seal] Bump to release version and export source code with integrity hash +# 2. [Quality check] Restore sealed source code, run tests, linting, security and complexity base line +# 3. [Build] Restore sealed source code, create and export hashed build artifact for PyPi release (wheel, tarball) +# 4. [Provenance] Generates provenance for build, signs attestation with GitHub OIDC claims to confirm it came from this release pipeline, commit, org, repo, branch, hash, etc. +# 5. [Release] Restore built artifact, and publish package to PyPi prod repository +# 6. [PR to bump version] Restore sealed source code, and create a PR to update trunk with latest released project metadata + +# NOTE +# +# See MAINTAINERS.md "Releasing a new version" for release mechanisms +# +# Every job is isolated and starts a new fresh container. + +env: + RELEASE_COMMIT: ${{ github.sha }} + +on: + workflow_dispatch: + inputs: + skip_code_quality: + description: "Skip tests, linting, and baseline. Only use if release fail for reasons beyond our control and you need a quick release." + default: false + type: boolean + required: false + skip_pypi: + description: "Skip publishing to PyPi. Used for testing release steps." + default: false + type: boolean + required: false + schedule: + # Note: run daily on weekdays at 8am UTC time + - cron: "0 8 * * 1-5" + +permissions: + contents: read + +jobs: + + # This job bumps the package version to the pre-release version + # creates an integrity hash from the source code + # uploads the artifact with the integrity hash as the key name + # so subsequent jobs can restore from a trusted point in time to prevent tampering + seal: + # ignore forks + if: github.repository == 'aws-powertools/powertools-lambda-python' + + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + integrity_hash: ${{ steps.seal_source_code.outputs.integrity_hash }} + artifact_name: ${{ steps.seal_source_code.outputs.artifact_name }} + RELEASE_VERSION: ${{ steps.release_version.outputs.RELEASE_VERSION }} + steps: + # NOTE: Different from prod release, we need both poetry and source code available in earlier steps to bump and verify. + + # We use a pinned version of Poetry to be certain it won't modify source code before we create a hash + - name: Install poetry + run: | + pipx install git+https://github.com/python-poetry/poetry@68b88e5390720a3dd84f02940ec5200bfce39ac6 # v1.5.0 + pipx inject poetry git+https://github.com/monim67/poetry-bumpversion@315fe3324a699fa12ec20e202eb7375d4327d1c4 # v0.3.1 + + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Bump and export release version + id: release_version + run: | + RELEASE_VERSION="$(poetry version prerelease --short | head -n1 | tr -d '\n')" + + echo "RELEASE_VERSION=${RELEASE_VERSION}" >> "$GITHUB_OUTPUT" + + - name: Verifies pre-release version semantics + # verify pre-release semantics before proceeding to avoid versioning pollution + # e.g., 2.40.0a1 and 2.40.0b2 are valid while 2.40.0 is not + # NOTE. we do it in a separate step to handle edge cases like + # `poetry` CLI uses immutable install, versioning behaviour could change even in a minor version (we had breaking changes before) + # a separate step allows us to pinpoint what happened (before/after) + run: | + if [[ ! "$RELEASE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+[a-b].*$ ]]; then + echo "Version $VERSION doesn't look like a pre-release version; aborting" + exit 1 + fi + env: + RELEASE_VERSION: ${{ steps.release_version.outputs.RELEASE_VERSION}} + + - name: Seal and upload + id: seal_source_code + uses: ./.github/actions/seal + with: + artifact_name_prefix: "source" + + # This job runs our automated test suite, complexity and security baselines + # it ensures previously merged have been tested as part of the pull request process + # + # NOTE + # + # we don't upload the artifact after testing to prevent any tampering of our source code dependencies + quality_check: + needs: seal + runs-on: ubuntu-latest + permissions: + contents: read + steps: + # NOTE: we need actions/checkout to configure git first (pre-commit hooks in make dev) + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ needs.seal.outputs.integrity_hash }} + artifact_name: ${{ needs.seal.outputs.artifact_name }} + + - name: Debug cache restore + run: cat pyproject.toml + + - name: Install poetry + run: pipx install git+https://github.com/python-poetry/poetry@68b88e5390720a3dd84f02940ec5200bfce39ac6 # v1.5.0 + - name: Set up Python + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: "3.12" + cache: "poetry" + - name: Install dependencies + run: make dev + - name: Run all tests, linting and baselines + run: make pr + + # This job creates a release artifact (tar.gz, wheel) + # it checks out code from release commit for custom actions to work + # then restores the sealed source code (overwrites any potential tampering) + # it's done separately from release job to enforce least privilege. + # We export just the final build artifact for release + build: + runs-on: ubuntu-latest + needs: [quality_check, seal] + permissions: + contents: read + outputs: + integrity_hash: ${{ steps.seal_build.outputs.integrity_hash }} + artifact_name: ${{ steps.seal_build.outputs.artifact_name }} + attestation_hashes: ${{ steps.encoded_hash.outputs.attestation_hashes }} + steps: + # NOTE: we need actions/checkout to configure git first (pre-commit hooks in make dev) + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ needs.seal.outputs.integrity_hash }} + artifact_name: ${{ needs.seal.outputs.artifact_name }} + + - name: Install poetry + run: pipx install git+https://github.com/python-poetry/poetry@68b88e5390720a3dd84f02940ec5200bfce39ac6 # v1.5.0 + - name: Set up Python + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: "3.12" + cache: "poetry" + + - name: Build python package and wheel + run: poetry build + + - name: Seal and upload + id: seal_build + uses: ./.github/actions/seal + with: + artifact_name_prefix: "build" + files: "dist/" + + # NOTE: SLSA retraces our build to its artifact to ensure it wasn't tampered + # coupled with GitHub OIDC, SLSA can then confidently sign it came from this release pipeline+commit+branch+org+repo+actor+integrity hash + - name: Create attestation encoded hash for provenance + id: encoded_hash + working-directory: dist + run: echo "attestation_hashes=$(sha256sum ./* | base64 -w0)" >> "$GITHUB_OUTPUT" + + # This job creates a provenance file that describes how our release was built (all steps) + # after it verifies our build is reproducible within the same pipeline + # it confirms that its own software and the CI build haven't been tampered with (Trust but verify) + # lastly, it creates and sign an attestation (multiple.intoto.jsonl) that confirms + # this build artifact came from this GitHub org, branch, actor, commit ID, inputs that triggered this pipeline, and matches its integrity hash + # NOTE: supply chain threats review (we protect against all of them now): https://slsa.dev/spec/v1.0/threats-overview + provenance: + needs: [seal, build] + permissions: + contents: write # nested job explicitly require despite upload assets being set to false + actions: read # To read the workflow path. + id-token: write # To sign the provenance. + # NOTE: provenance fails if we use action pinning... it's a Github limitation + # because SLSA needs to trace & attest it came from a given branch; pinning doesn't expose that information + # https://github.com/slsa-framework/slsa-github-generator/blob/main/internal/builders/generic/README.md#referencing-the-slsa-generator + uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v2.0.0 + with: + base64-subjects: ${{ needs.build.outputs.attestation_hashes }} + upload-assets: false # we upload its attestation in create_tag job, otherwise it creates a new release + + # This job uses release artifact to publish to PyPi + # it exchanges JWT tokens with GitHub to obtain PyPi credentials + # since it's already registered as a Trusted Publisher. + # It uses the sealed build artifact (.whl, .tar.gz) to release it + release: + needs: [build, seal, provenance] + environment: pre-release + runs-on: ubuntu-latest + permissions: + id-token: write # OIDC for PyPi Trusted Publisher feature + env: + RELEASE_VERSION: ${{ needs.seal.outputs.RELEASE_VERSION }} + steps: + # NOTE: we need actions/checkout in order to use our local actions (e.g., ./.github/actions) + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ needs.build.outputs.integrity_hash }} + artifact_name: ${{ needs.build.outputs.artifact_name }} + + - name: Upload to PyPi prod + if: ${{ !inputs.skip_pypi }} + uses: pypa/gh-action-pypi-publish@15c56dba361d8335944d31a2ecd17d700fc7bcbc # v1.12.2 + + # Creates a PR with the latest version we've just released + # since our trunk is protected against any direct pushes from automation + bump_version: + needs: [release, seal, provenance] + permissions: + contents: write # create-pr action creates a temporary branch + pull-requests: write # create-pr action creates a PR using the temporary branch + runs-on: ubuntu-latest + steps: + # NOTE: we need actions/checkout to authenticate and configure git first + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ needs.seal.outputs.integrity_hash }} + artifact_name: ${{ needs.seal.outputs.artifact_name }} + + - name: Download provenance + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: ${{needs.provenance.outputs.provenance-name}} + + - name: Update provenance + run: mkdir -p "${PROVENANCE_DIR}" && mv "${PROVENANCE_FILE}" "${PROVENANCE_DIR}/" + env: + PROVENANCE_FILE: ${{ needs.provenance.outputs.provenance-name }} + PROVENANCE_DIR: provenance/${{ needs.seal.outputs.RELEASE_VERSION}} + + - name: Create PR + id: create-pr + uses: ./.github/actions/create-pr + with: + files: "pyproject.toml aws_lambda_powertools/shared/version.py provenance/" + temp_branch_prefix: "ci-bump" + pull_request_title: "chore(ci): new pre-release ${{ needs.seal.outputs.RELEASE_VERSION }}" + github_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/publish_v2_layer.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/publish_v2_layer.yml new file mode 100644 index 0000000000000000000000000000000000000000..50d0d9250467c8a61c6a34ef8fdc86c78ed4258a --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/publish_v2_layer.yml @@ -0,0 +1,317 @@ +name: Deploy v2 layer to all regions + +# PROCESS +# +# 1. Compile Layer using cdk-aws-lambda-powertools-layer CDK construct for x86_64 and ARM (uses custom runner as it's CPU heavy) +# 2. Kick off pipeline for beta, prod, and canary releases +# 3. Create PR to update trunk so staged docs also point to the latest Layer ARN, when merged +# 4. Builds and publishes docs with latest Layer ARN using given version (generally coming from release) + + +# USAGE +# +# NOTE: meant to be used with ./.github/workflows/release.yml +# +# publish_layer: +# needs: [seal, release, create_tag] +# secrets: inherit +# permissions: +# id-token: write +# contents: write +# pages: write +# pull-requests: write +# uses: ./.github/workflows/publish_v2_layer.yml +# with: +# latest_published_version: ${{ needs.seal.outputs.RELEASE_VERSION }} +# pre_release: ${{ inputs.pre_release }} +# source_code_artifact_name: ${{ needs.seal.outputs.artifact_name }} +# source_code_integrity_hash: ${{ needs.seal.outputs.integrity_hash }} + + +on: + workflow_dispatch: + inputs: + latest_published_version: + description: "Latest PyPi published version to rebuild latest docs for, e.g. 2.0.0, 2.0.0a1 (pre-release)" + required: true + source_code_artifact_name: + description: "Artifact name to restore sealed source code" + type: string + required: true + source_code_integrity_hash: + description: "Sealed source code integrity hash" + type: string + required: true + pre_release: + description: "Publishes documentation using a pre-release tag (2.0.0a1)." + default: false + type: boolean + required: false + workflow_call: + inputs: + latest_published_version: + type: string + description: "Latest PyPi published version to rebuild latest docs for, e.g. 2.0.0, 2.0.0a1 (pre-release)" + required: true + pre_release: + description: "Publishes documentation using a pre-release tag (2.0.0a1)." + default: false + type: boolean + required: false + source_code_artifact_name: + description: "Artifact name to restore sealed source code" + type: string + required: true + source_code_integrity_hash: + description: "Sealed source code integrity hash" + type: string + required: true + +permissions: + contents: read + + +env: + RELEASE_COMMIT: ${{ github.sha }} + +jobs: + build-layer: + permissions: + # lower privilege propagated from parent workflow (release.yml) + contents: read + id-token: write + pages: none + pull-requests: none + runs-on: aws-powertools_ubuntu-latest_8-core + defaults: + run: + working-directory: ./layer + steps: + - name: checkout + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ inputs.source_code_integrity_hash }} + artifact_name: ${{ inputs.source_code_artifact_name }} + + - name: Install poetry + run: pipx install git+https://github.com/python-poetry/poetry@68b88e5390720a3dd84f02940ec5200bfce39ac6 # v1.5.0 + - name: Setup Node.js + uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + with: + node-version: "16.12" + - name: Setup python + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: "3.12" + cache: "pip" + - name: Resolve and install project dependencies + # CDK spawns system python when compiling stack + # therefore it ignores both activated virtual env and cached interpreter by GH + run: | + poetry export --format requirements.txt --output requirements.txt + pip install --require-hashes -r requirements.txt + + - name: Set up QEMU + uses: docker/setup-qemu-action@49b3bc8e6bdd4a60e6116a5414239cba5943d3cf # v2.0.0 + with: + platforms: arm64 + # NOTE: we need QEMU to build Layer against a different architecture (e.g., ARM) + + - name: Set up Docker Buildx + id: builder + uses: docker/setup-buildx-action@c47758b77c9736f4b2ef4073d4d51994fabfe349 # v3.7.1 + with: + install: true + driver: docker + platforms: linux/amd64,linux/arm64 + + - name: Install CDK + working-directory: ./ + run: | + npm ci + npx cdk --version + + # Baking time for PyPi eventual consistency; 60s seemed more than enough + # https://github.com/aws-powertools/powertools-lambda-python/issues/2491 + - name: Baking time (PyPi) + run: sleep 60 + + - name: CDK build + run: npx cdk synth --verbose --context version="${{ inputs.latest_published_version }}" -o cdk.out + - name: zip output + run: zip -r cdk.out.zip cdk.out + - name: Archive CDK artifacts + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 + with: + name: cdk-layer-artefact + path: layer/cdk.out.zip + + beta: + needs: build-layer + # lower privilege propagated from parent workflow (release.yml) + permissions: + id-token: write + contents: read + pages: write # docs will be updated with latest Layer ARNs + pull-requests: write # creation-action will create a PR with Layer ARN updates + uses: ./.github/workflows/reusable_deploy_v2_layer_stack.yml + secrets: inherit + with: + stage: "BETA" + artefact-name: "cdk-layer-artefact" + environment: "layer-beta" + latest_published_version: ${{ inputs.latest_published_version }} + source_code_artifact_name: ${{ inputs.source_code_artifact_name }} + source_code_integrity_hash: ${{ inputs.source_code_integrity_hash }} + + prod: + needs: beta + # lower privilege propagated from parent workflow (release.yml) + permissions: + id-token: write + contents: read + pages: write # docs will be updated with latest Layer ARNs + pull-requests: write # creation-action will create a PR with Layer ARN updates + uses: ./.github/workflows/reusable_deploy_v2_layer_stack.yml + secrets: inherit + with: + stage: "PROD" + artefact-name: "cdk-layer-artefact" + environment: "layer-prod" + latest_published_version: ${{ inputs.latest_published_version }} + source_code_artifact_name: ${{ inputs.source_code_artifact_name }} + source_code_integrity_hash: ${{ inputs.source_code_integrity_hash }} + + sar-beta: + needs: beta # canaries run on Layer Beta env + permissions: + # lower privilege propagated from parent workflow (release.yml) + id-token: write + contents: read + pull-requests: none + pages: none + uses: ./.github/workflows/reusable_deploy_v2_sar.yml + secrets: inherit + with: + stage: "BETA" + artefact-name: "cdk-layer-artefact" + environment: "layer-beta" + package-version: ${{ inputs.latest_published_version }} + source_code_artifact_name: ${{ inputs.source_code_artifact_name }} + source_code_integrity_hash: ${{ inputs.source_code_integrity_hash }} + + + sar-prod: + needs: sar-beta + permissions: + # lower privilege propagated from parent workflow (release.yml) + id-token: write + contents: read + pull-requests: none + pages: none + uses: ./.github/workflows/reusable_deploy_v2_sar.yml + secrets: inherit + with: + stage: "PROD" + artefact-name: "cdk-layer-artefact" + environment: "layer-prod" + package-version: ${{ inputs.latest_published_version }} + source_code_artifact_name: ${{ inputs.source_code_artifact_name }} + source_code_integrity_hash: ${{ inputs.source_code_integrity_hash }} + + + # Updating the documentation with the latest Layer ARNs is a two-phase process + # + # 1. Update layer ARNs with latest deployed locally and create a PR with these changes + # 2. Pull from temporary branch with these changes and update the docs we're releasing + # + # This keeps our permissions tight and we don't run into a conflict, + # where a new release creates a new doc (2.16.0) while layers are still pointing to 2.15 + # because the PR has to be merged while release process is running + + update_v2_layer_arn_docs: + needs: prod + outputs: + temp_branch: ${{ steps.create-pr.outputs.temp_branch }} + runs-on: ubuntu-latest + permissions: + # lower privilege propagated from parent workflow (release.yml) + contents: write + pull-requests: write + id-token: none + pages: none + steps: + - name: Checkout repository # reusable workflows start clean, so we need to checkout again + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ inputs.source_code_integrity_hash }} + artifact_name: ${{ inputs.source_code_artifact_name }} + + - name: Download CDK layer artifacts + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + path: cdk-layer-stack + pattern: cdk-layer-stack-* # merge all Layer artifacts created per region earlier (reusable_deploy_v2_layer_stack.yml; step "Save Layer ARN artifact") + merge-multiple: true + - name: Replace layer versions in documentation + run: | + ls -la cdk-layer-stack/ + ./layer/scripts/update_layer_arn.sh cdk-layer-stack + # NOTE: It felt unnecessary creating yet another PR to update changelog w/ latest tag + # since this is the only step in the release where we update docs from a temp branch + - name: Update changelog with latest tag + run: make changelog + - name: Create PR + id: create-pr + uses: ./.github/actions/create-pr + with: + files: "docs/index.md examples CHANGELOG.md" + temp_branch_prefix: "ci-layer-docs" + pull_request_title: "chore(ci): layer docs update" + github_token: ${{ secrets.GITHUB_TOKEN }} + + + prepare_docs_alias: + runs-on: ubuntu-latest + permissions: + # lower privilege propagated from parent workflow (release.yml) + contents: read + pages: none + id-token: none + pull-requests: none + outputs: + DOCS_ALIAS: ${{ steps.set-alias.outputs.DOCS_ALIAS }} + steps: + - name: Set docs alias + id: set-alias + run: | + DOCS_ALIAS=latest + if [[ "${{ inputs.pre_release }}" == true ]] ; then + DOCS_ALIAS=alpha + fi + echo DOCS_ALIAS="$DOCS_ALIAS" >> "$GITHUB_OUTPUT" + + release_docs: + needs: [update_v2_layer_arn_docs, prepare_docs_alias] + permissions: + # lower privilege propagated from parent workflow (release.yml) + contents: write + pages: write + pull-requests: none + id-token: write + secrets: inherit + uses: ./.github/workflows/reusable_publish_docs.yml + with: + version: ${{ inputs.latest_published_version }} + alias: ${{ needs.prepare_docs_alias.outputs.DOCS_ALIAS }} + git_ref: ${{ needs.update_v2_layer_arn_docs.outputs.temp_branch }} diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/publish_v3_layer.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/publish_v3_layer.yml new file mode 100644 index 0000000000000000000000000000000000000000..d1635e029289c755d9f6152960f9c8d3976aea4f --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/publish_v3_layer.yml @@ -0,0 +1,315 @@ +name: Deploy v3 layer to all regions + +# PROCESS +# +# 1. Compile Layer using cdk-aws-lambda-powertools-layer CDK construct for Python3.8-3.12 and x86_64/ARM architectures (uses custom runner as it's CPU heavy) +# 2. Kick off pipeline for beta, prod, and canary releases +# 3. Create PR to update trunk so staged docs also point to the latest Layer ARN, when merged +# 4. Builds and publishes docs with latest Layer ARN using given version (generally coming from release) + +# USAGE +# +# NOTE: meant to be used with ./.github/workflows/release-v3.yml +# +# publish_layer: +# needs: [seal, release, create_tag] +# secrets: inherit +# permissions: +# id-token: write +# contents: write +# pages: write +# pull-requests: write +# uses: ./.github/workflows/publish_v2_layer.yml +# with: +# latest_published_version: ${{ needs.seal.outputs.RELEASE_VERSION }} +# pre_release: ${{ inputs.pre_release }} +# source_code_artifact_name: ${{ needs.seal.outputs.artifact_name }} +# source_code_integrity_hash: ${{ needs.seal.outputs.integrity_hash }} + + +on: + workflow_dispatch: + inputs: + latest_published_version: + description: "Latest PyPi published version to rebuild latest docs for, e.g. 3.0.0, 3.0.0a1 (pre-release)" + required: true + source_code_artifact_name: + description: "Artifact name to restore sealed source code" + type: string + required: true + source_code_integrity_hash: + description: "Sealed source code integrity hash" + type: string + required: true + pre_release: + description: "Publishes documentation using a pre-release tag (3.0.0a1)." + default: false + type: boolean + required: false + workflow_call: + inputs: + latest_published_version: + type: string + description: "Latest PyPi published version to rebuild latest docs for, e.g. 3.0.0, 3.0.0a1 (pre-release)" + required: true + pre_release: + description: "Publishes documentation using a pre-release tag (3.0.0a1)." + default: false + type: boolean + required: false + source_code_artifact_name: + description: "Artifact name to restore sealed source code" + type: string + required: true + source_code_integrity_hash: + description: "Sealed source code integrity hash" + type: string + required: true + +permissions: + contents: read + + +env: + RELEASE_COMMIT: ${{ github.sha }} + +jobs: + build-layer: + permissions: + # lower privilege propagated from parent workflow (release-v3.yml) + contents: read + id-token: write + pages: none + pull-requests: none + runs-on: aws-powertools_ubuntu-latest_8-core + strategy: + max-parallel: 5 + matrix: + python-version: ["3.8","3.9","3.10","3.11","3.12","3.13"] + defaults: + run: + working-directory: ./layer_v3 + steps: + - name: checkout + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ inputs.source_code_integrity_hash }} + artifact_name: ${{ inputs.source_code_artifact_name }} + + - name: Install poetry + run: pipx install git+https://github.com/python-poetry/poetry@68b88e5390720a3dd84f02940ec5200bfce39ac6 # v1.5.0 + - name: Setup Node.js + uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + with: + node-version: "18.20.4" + - name: Setup python + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: ${{ matrix.python-version }} + cache: "pip" + - name: Resolve and install project dependencies + # CDK spawns system python when compiling stack + # therefore it ignores both activated virtual env and cached interpreter by GH + run: | + poetry export --format requirements.txt --output requirements.txt + pip install --require-hashes -r requirements.txt + + - name: Set up QEMU + uses: docker/setup-qemu-action@49b3bc8e6bdd4a60e6116a5414239cba5943d3cf # v2.0.0 + with: + platforms: arm64 + # NOTE: we need QEMU to build Layer against a different architecture (e.g., ARM) + + - name: Set up Docker Buildx + id: builder + uses: docker/setup-buildx-action@c47758b77c9736f4b2ef4073d4d51994fabfe349 # v3.7.1 + with: + install: true + driver: docker + platforms: linux/amd64,linux/arm64 + + - name: Install CDK + working-directory: ./ + run: | + npm ci + npx cdk --version + + # Baking time for PyPi eventual consistency; 60s seemed more than enough + # https://github.com/aws-powertools/powertools-lambda-python/issues/2491 + - name: Baking time (PyPi) + run: sleep 60 + + - name: CDK build + run: npx cdk synth --verbose --context version="${{ inputs.latest_published_version }}" --context pythonVersion="python${{ matrix.python-version }}" -o cdk.out + - name: zip output + run: zip -r cdk.py${{ matrix.python-version }}.out.zip cdk.out + - name: Archive CDK artifacts + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 + with: + name: cdk-layer-artifact-py${{ matrix.python-version }} + path: layer_v3/cdk.py${{ matrix.python-version }}.out.zip + + beta: + needs: build-layer + # lower privilege propagated from parent workflow (release-v3.yml) + permissions: + id-token: write + contents: read + pages: write # docs will be updated with latest Layer ARNs + pull-requests: write # creation-action will create a PR with Layer ARN updates + uses: ./.github/workflows/reusable_deploy_v3_layer_stack.yml + secrets: inherit + with: + stage: "BETA" + environment: "layer-beta" + source_code_artifact_name: ${{ inputs.source_code_artifact_name }} + source_code_integrity_hash: ${{ inputs.source_code_integrity_hash }} + + prod: + needs: beta + # lower privilege propagated from parent workflow (release-v3.yml) + permissions: + id-token: write + contents: read + pages: write # docs will be updated with latest Layer ARNs + pull-requests: write # creation-action will create a PR with Layer ARN updates + uses: ./.github/workflows/reusable_deploy_v3_layer_stack.yml + secrets: inherit + with: + stage: "PROD" + environment: "layer-prod" + source_code_artifact_name: ${{ inputs.source_code_artifact_name }} + source_code_integrity_hash: ${{ inputs.source_code_integrity_hash }} + + # UNCOMMENT sar-beta JOB + #sar-beta: + # needs: beta # canaries run on Layer Beta env + # permissions: + # lower privilege propagated from parent workflow (release.yml) + # id-token: write + # contents: read + # pull-requests: none + # pages: none + # uses: ./.github/workflows/reusable_deploy_v3_sar.yml + # secrets: inherit + # with: + # stage: "BETA" + # environment: "layer-beta" + # package-version: ${{ inputs.latest_published_version }} + # source_code_artifact_name: ${{ inputs.source_code_artifact_name }} + # source_code_integrity_hash: ${{ inputs.source_code_integrity_hash }} + + # UNCOMMENT sar-prod JOB + #sar-prod: + # needs: sar-beta + # permissions: + # lower privilege propagated from parent workflow (release.yml) + # id-token: write + # contents: read + # pull-requests: none + # pages: none + # uses: ./.github/workflows/reusable_deploy_v3_sar.yml + # secrets: inherit + # with: + # stage: "PROD" + # environment: "layer-prod" + # package-version: ${{ inputs.latest_published_version }} + # source_code_artifact_name: ${{ inputs.source_code_artifact_name }} + # source_code_integrity_hash: ${{ inputs.source_code_integrity_hash }} + + + # Updating the documentation with the latest Layer ARNs is a two-phase process + # + # 1. Update layer ARNs with latest deployed locally and create a PR with these changes + # 2. Pull from temporary branch with these changes and update the docs we're releasing + # + # This keeps our permissions tight and we don't run into a conflict, + # where a new release creates a new doc (2.16.0) while layers are still pointing to 2.15 + # because the PR has to be merged while release process is running + + update_v3_layer_arn_docs: + needs: prod + outputs: + temp_branch: ${{ steps.create-pr.outputs.temp_branch }} + runs-on: ubuntu-latest + permissions: + # lower privilege propagated from parent workflow (release.yml) + contents: write + pull-requests: write + id-token: none + pages: none + steps: + - name: Checkout repository # reusable workflows start clean, so we need to checkout again + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ inputs.source_code_integrity_hash }} + artifact_name: ${{ inputs.source_code_artifact_name }} + + # UNCOMMENT THIS + # - name: Download CDK layer artifacts + # uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e # v4.1.7 + # with: + # path: cdk-layer-stack + # pattern: cdk-layer-stack-* # merge all Layer artifacts created per region earlier (reusable_deploy_v2_layer_stack.yml; step "Save Layer ARN artifact") + # merge-multiple: true + # - name: Replace layer versions in documentation + # run: | + # ls -la cdk-layer-stack/ + # ./layer_v3/scripts/update_layer_arn.sh cdk-layer-stack + # NOTE: It felt unnecessary creating yet another PR to update changelog w/ latest tag + # since this is the only step in the release where we update docs from a temp branch + # - name: Update changelog with latest tag + # run: make changelog + # - name: Create PR + # id: create-pr + # uses: ./.github/actions/create-pr + # with: + # files: "docs/index.md examples CHANGELOG.md" + # temp_branch_prefix: "ci-layer-docs" + # pull_request_title: "chore(ci): layer docs update" + # github_token: ${{ secrets.GITHUB_TOKEN }} + + prepare_docs_alias: + runs-on: ubuntu-latest + permissions: + # lower privilege propagated from parent workflow (release.yml) + contents: read + pages: none + id-token: none + pull-requests: none + outputs: + DOCS_ALIAS: ${{ steps.set-alias.outputs.DOCS_ALIAS }} + steps: + - name: Set docs alias + id: set-alias + run: | + DOCS_ALIAS=latest + if [[ "${{ inputs.pre_release }}" == true ]] ; then + DOCS_ALIAS=alpha + fi + echo DOCS_ALIAS="$DOCS_ALIAS" >> "$GITHUB_OUTPUT" + + release_docs: + needs: [update_v3_layer_arn_docs, prepare_docs_alias] + permissions: + # lower privilege propagated from parent workflow (release.yml) + contents: write + pages: write + pull-requests: none + id-token: write + secrets: inherit + uses: ./.github/workflows/reusable_publish_docs.yml + with: + version: ${{ inputs.latest_published_version }} + alias: ${{ needs.prepare_docs_alias.outputs.DOCS_ALIAS }} + git_ref: ${{ needs.update_v3_layer_arn_docs.outputs.temp_branch }} diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/quality_check.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/quality_check.yml new file mode 100644 index 0000000000000000000000000000000000000000..fb51b9ce26b972c8457f412530242dbe3e1945c8 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/quality_check.yml @@ -0,0 +1,83 @@ +name: Code quality + +# PROCESS +# +# 1. Install all dependencies and spin off containers for all supported Python versions +# 2. Run code formatters and linters (various checks) for code standard +# 3. Run static typing checker for potential bugs +# 4. Run entire test suite for regressions except end-to-end (unit, functional, performance) +# 5. Run static analysis (in addition to CodeQL) for common insecure code practices +# 6. Run complexity baseline to avoid error-prone bugs and keep maintenance lower +# 7. Collect and report on test coverage + +# USAGE +# +# Always triggered on new PRs, PR changes and PR merge. + + +on: + pull_request: + paths: + - "aws_lambda_powertools/**" + - "tests/**" + - "examples/**" + - "pyproject.toml" + - "poetry.lock" + - "mypy.ini" + branches: + - develop + push: + paths: + - "aws_lambda_powertools/**" + - "tests/**" + - "examples/**" + - "pyproject.toml" + - "poetry.lock" + - "mypy.ini" + branches: + - develop + +permissions: + contents: read + +jobs: + quality_check: + runs-on: ubuntu-latest + strategy: + max-parallel: 4 + matrix: + python-version: ["3.8","3.9","3.10","3.11","3.12","3.13"] + env: + PYTHON: "${{ matrix.python-version }}" + permissions: + contents: read # checkout code only + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Install poetry + run: pipx install poetry + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: ${{ matrix.python-version }} + cache: "poetry" + - name: Install dependencies + run: make dev + - name: Formatting and Linting + run: make lint + - name: Static type checking + run: make mypy + - name: Test with pytest + run: make test + - name: Test dependencies with Nox + run: make test-dependencies + - name: Security baseline + run: make security-baseline + - name: Complexity baseline + run: make complexity-baseline + - name: Upload coverage to Codecov + uses: codecov/codecov-action@5c47607acb93fed5485fdbf7232e8a31425f672a # 5.0.2 + with: + token: ${{ secrets.CODECOV_TOKEN }} + file: ./coverage.xml + env_vars: PYTHON + name: aws-lambda-powertools-python-codecov diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/quality_code_cdk_constructor.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/quality_code_cdk_constructor.yml new file mode 100644 index 0000000000000000000000000000000000000000..c3fdf614e01e7cc6fd81bd23941805c9647f8bc5 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/quality_code_cdk_constructor.yml @@ -0,0 +1,70 @@ +name: Code quality - CDK constructor + +# PROCESS +# +# 1. Install all dependencies and spin off containers for all supported Python versions +# 2. Run code formatters and linters (various checks) for code standard +# 3. Run static typing checker for potential bugs +# 4. Run tests + +# USAGE +# +# Always triggered on new PRs, PR changes and PR merge. + + +on: + pull_request: + paths: + - "layer_v3/layer_constructors/**" + branches: + - develop + push: + paths: + - "layer_v3/layer_constructors/**" + branches: + - develop + +permissions: + contents: read + +jobs: + quality_check_cdk: + runs-on: ubuntu-latest + strategy: + max-parallel: 4 + matrix: + python-version: ["3.12"] + env: + PYTHON: "${{ matrix.python-version }}" + permissions: + contents: read # checkout code only + defaults: + run: + working-directory: ./layer_v3/layer_constructors + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Install poetry + run: pipx install poetry + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: ${{ matrix.python-version }} + cache: "poetry" + - name: Set up QEMU + uses: docker/setup-qemu-action@49b3bc8e6bdd4a60e6116a5414239cba5943d3cf # v2.0.0 + with: + platforms: arm64 + # NOTE: we need QEMU to build Layer against a different architecture (e.g., ARM) + - name: Set up Docker Buildx + id: builder + uses: docker/setup-buildx-action@c47758b77c9736f4b2ef4073d4d51994fabfe349 # v3.7.1 + with: + install: true + driver: docker + platforms: linux/amd64,linux/arm64 + - name: Install dependencies + run: | + pip install --upgrade pip pre-commit poetry + poetry install + - name: Test with pytest + run: poetry run pytest tests diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/rebuild_latest_docs.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/rebuild_latest_docs.yml new file mode 100644 index 0000000000000000000000000000000000000000..665cad81dd18ca8febb5b3e22ead00d26a9bb0f5 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/rebuild_latest_docs.yml @@ -0,0 +1,39 @@ +name: Rebuild latest docs + +# PROCESS +# +# 1. Build User Guide and API docs +# 2. Publish to GitHub Pages +# 3. Publish to S3 (new home) + +# USAGE +# +# Only used for deploying a documentation hotfix to /latest and its associated version w/o a full release. +# +# Steps: +# +# 1. Trigger "Rebuild latest docs" workflow manually: https://docs.github.com/en/actions/managing-workflow-runs/manually-running-a-workflow +# 2. Use the latest version released under Releases e.g. 2.0.0 + +on: + workflow_dispatch: + inputs: + latest_published_version: + description: "Latest PyPi published version to rebuild latest docs for, e.g. 2.16.3" + default: "2.16.3" + required: true + +permissions: + contents: read + +jobs: + release-docs: + permissions: + contents: write # push to gh-pages + pages: write # deploy gh-pages website + id-token: write # trade JWT token for AWS credentials in AWS Docs account + secrets: inherit + uses: ./.github/workflows/reusable_publish_docs.yml + with: + version: ${{ inputs.latest_published_version }} + alias: latest diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/record_pr.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/record_pr.yml new file mode 100644 index 0000000000000000000000000000000000000000..51b501fe74d1396d71c59f87d4da2c140761488f --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/record_pr.yml @@ -0,0 +1,60 @@ +name: Record PR details + +# PROCESS +# +# 1. Runs in fork location upon PR creation or changes +# 2. Saves GitHub Pull Request Webhook payload +# 3. Uploads as a temporary GitHub Action Artifact with shortest retention + +# USAGE +# +# see .github/workflows/on_merged_pr.yml and related for full example. +# +# on: +# workflow_run: +# workflows: ["Record PR details"] +# types: +# - completed +# +# Security Note: +# +# For security, this is intended to be a 2-step process: (1) collect PR, (2) act on PR. +# Do not ever use `pull_request_target` to "simplify", as it sends a write-token to the fork. Our linter should catch it. +# +# The first step runs in untrusted location (fork), therefore we limit permissions to only check out code. +# +# The second step will be workflows that want to act on a given PR, this time with intended permissions, and +# it runs on its base location (this repo!). +# +# This enforces zero trust where this workflow always runs on fork with zero permissions on GH_TOKEN. +# When this workflow completes, X workflows run in our repository with the appropriate permissions and sanitize inputs. +# +# Coupled with "Approve GitHub Action to run on forks", we have confidence no privilege can be escalated, +# since any malicious change would need to be approved, and upon social engineering, it'll have zero permissions. + + +on: + pull_request: + types: [opened, edited, closed, labeled] + +permissions: + contents: read + +jobs: + record_pr: + runs-on: ubuntu-latest + permissions: + contents: read # NOTE: treat as untrusted location + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: "Extract PR details" + uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1 + with: + script: | + const script = require('.github/scripts/save_pr_details.js') + await script({github, context, core}) + - uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 + with: + name: pr + path: pr.txt + retention-days: 1 diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/release-drafter.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..473968803b0e994fceba557b6b27acb64d952089 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/release-drafter.yml @@ -0,0 +1,32 @@ +name: Release Drafter + +# PROCESS +# +# 1. Enumerate all PRs in merged state +# 2. Filter out any PR labeled `skip-changelog` +# 3. Updates or creates a new release in Draft mode + +# USAGE +# +# Always run on merged PRs or manually via GitHub UI for debugging purposes. +# +# see .github/release-drafter.yml for configuration + +on: + push: + branches: + - develop + workflow_dispatch: + +permissions: + contents: read + +jobs: + update_release_draft: + runs-on: ubuntu-latest + permissions: + contents: write # create release in draft mode + steps: + - uses: release-drafter/release-drafter@3f0f87098bd6b5c5b9a36d49c41d998ea58f9348 # v5.20.1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/release-v3.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/release-v3.yml new file mode 100644 index 0000000000000000000000000000000000000000..0008a9b55b914728f7879727f8e12846b110f136 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/release-v3.yml @@ -0,0 +1,374 @@ +name: Release V3 + +# RELEASE PROCESS +# +# === Automated activities === +# +# 1. [Seal] Bump to release version and export source code with integrity hash +# 2. [Quality check] Restore sealed source code, run tests, linting, security and complexity base line +# 3. [Build] Restore sealed source code, create and export hashed build artifact for PyPi release (wheel, tarball) +# 4. [Provenance] Generates provenance for build, signs attestation with GitHub OIDC claims to confirm it came from this release pipeline, commit, org, repo, branch, hash, etc. +# 5. [Release] Restore built artifact, and publish package to PyPi prod repository +# 6. [Create Tag] Restore sealed source code, create a new git tag using released version, uploads provenance to latest draft release +# 7. [PR to bump version] Restore sealed source code, and create a PR to update trunk with latest released project metadata +# 8. [Publish Layer v3] Compile Layer in multiple Python versions and kick off pipeline for beta, prod, and canary releases +# 9. [Publish Layer v3] Update docs with latest Layer ARNs and Changelog +# 10. [Publish Layer v3] Create PR to update trunk so staged docs also point to the latest Layer ARN, when merged +# 12. [Post release] Close all issues labeled "pending-release" and notify customers about the release +# +# === Manual activities === +# +# 1. Kick off this workflow with the intended version +# 2. Update draft release notes after this workflow completes +# 3. If not already set, use `v<new version>` as a tag, e.g., v3.0.0, and select develop as target branch + +# NOTE +# +# See MAINTAINERS.md "Releasing a new version" for release mechanisms +# +# Every job is isolated and starts a new fresh container. + +env: + RELEASE_COMMIT: ${{ github.sha }} + RELEASE_TAG_VERSION: ${{ inputs.version_to_publish }} + +on: + workflow_dispatch: + inputs: + version_to_publish: + description: "Version to be released in PyPi, Docs, and Lambda Layer, e.g. v3.0.0, v3.0.0a0 (pre-release)" + default: v3.0.0 + required: true + skip_pypi: + description: "Skip publishing to PyPi as it can't publish more than once. Useful for semi-failed releases" + default: false + type: boolean + required: false + skip_code_quality: + description: "Skip tests, linting, and baseline. Only use if release fail for reasons beyond our control and you need a quick release." + default: false + type: boolean + required: false + pre_release: + description: "Publishes documentation using a pre-release tag (v3.0.0a0). You are still responsible for passing a pre-release version tag to the workflow." + default: false + type: boolean + required: false + +permissions: + contents: read + +jobs: + + # This job bumps the package version to the release version + # creates an integrity hash from the source code + # uploads the artifact with the integrity hash as the key name + # so subsequent jobs can restore from a trusted point in time to prevent tampering + seal: + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + integrity_hash: ${{ steps.seal_source_code.outputs.integrity_hash }} + artifact_name: ${{ steps.seal_source_code.outputs.artifact_name }} + RELEASE_VERSION: ${{ steps.release_version.outputs.RELEASE_VERSION }} + steps: + - name: Export release version + id: release_version + # transform tag format `v<version` to `<version>` + run: | + RELEASE_VERSION="${RELEASE_TAG_VERSION:1}" + echo "RELEASE_VERSION=${RELEASE_VERSION}" >> "$GITHUB_OUTPUT" + + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + # We use a pinned version of Poetry to be certain it won't modify source code before we create a hash + - name: Install poetry + run: | + pipx install git+https://github.com/python-poetry/poetry@68b88e5390720a3dd84f02940ec5200bfce39ac6 # v1.5.0 + pipx inject poetry git+https://github.com/monim67/poetry-bumpversion@315fe3324a699fa12ec20e202eb7375d4327d1c4 # v0.3.1 + + - name: Bump package version + id: versioning + run: poetry version "${RELEASE_VERSION}" + env: + RELEASE_VERSION: ${{ steps.release_version.outputs.RELEASE_VERSION}} + + - name: Seal and upload + id: seal_source_code + uses: ./.github/actions/seal + with: + artifact_name_prefix: "source" + + # This job runs our automated test suite, complexity and security baselines + # it ensures previously merged have been tested as part of the pull request process + # + # NOTE + # + # we don't upload the artifact after testing to prevent any tampering of our source code dependencies + quality_check: + needs: seal + runs-on: ubuntu-latest + permissions: + contents: read + steps: + # NOTE: we need actions/checkout to configure git first (pre-commit hooks in make dev) + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ needs.seal.outputs.integrity_hash }} + artifact_name: ${{ needs.seal.outputs.artifact_name }} + + - name: Debug cache restore + run: cat pyproject.toml + + - name: Install poetry + run: pipx install git+https://github.com/python-poetry/poetry@68b88e5390720a3dd84f02940ec5200bfce39ac6 # v1.5.0 + - name: Set up Python + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: "3.12" + cache: "poetry" + - name: Install dependencies + run: make dev + - name: Run all tests, linting and baselines + run: make pr + + # This job creates a release artifact (tar.gz, wheel) + # it checks out code from release commit for custom actions to work + # then restores the sealed source code (overwrites any potential tampering) + # it's done separately from release job to enforce least privilege. + # We export just the final build artifact for release + build: + runs-on: ubuntu-latest + needs: [quality_check, seal] + permissions: + contents: read + outputs: + integrity_hash: ${{ steps.seal_build.outputs.integrity_hash }} + artifact_name: ${{ steps.seal_build.outputs.artifact_name }} + attestation_hashes: ${{ steps.encoded_hash.outputs.attestation_hashes }} + steps: + # NOTE: we need actions/checkout to configure git first (pre-commit hooks in make dev) + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ needs.seal.outputs.integrity_hash }} + artifact_name: ${{ needs.seal.outputs.artifact_name }} + + - name: Install poetry + run: pipx install git+https://github.com/python-poetry/poetry@68b88e5390720a3dd84f02940ec5200bfce39ac6 # v1.5.0 + - name: Set up Python + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: "3.12" + cache: "poetry" + + - name: Build python package and wheel + run: poetry build + + - name: Seal and upload + id: seal_build + uses: ./.github/actions/seal + with: + artifact_name_prefix: "build" + files: "dist/" + + # NOTE: SLSA retraces our build to its artifact to ensure it wasn't tampered + # coupled with GitHub OIDC, SLSA can then confidently sign it came from this release pipeline+commit+branch+org+repo+actor+integrity hash + - name: Create attestation encoded hash for provenance + id: encoded_hash + working-directory: dist + run: echo "attestation_hashes=$(sha256sum ./* | base64 -w0)" >> "$GITHUB_OUTPUT" + + # This job creates a provenance file that describes how our release was built (all steps) + # after it verifies our build is reproducible within the same pipeline + # it confirms that its own software and the CI build haven't been tampered with (Trust but verify) + # lastly, it creates and sign an attestation (multiple.intoto.jsonl) that confirms + # this build artifact came from this GitHub org, branch, actor, commit ID, inputs that triggered this pipeline, and matches its integrity hash + # NOTE: supply chain threats review (we protect against all of them now): https://slsa.dev/spec/v1.0/threats-overview + provenance: + needs: [seal, build] + permissions: + contents: write # nested job explicitly require despite upload assets being set to false + actions: read # To read the workflow path. + id-token: write # To sign the provenance. + # NOTE: provenance fails if we use action pinning... it's a Github limitation + # because SLSA needs to trace & attest it came from a given branch; pinning doesn't expose that information + # https://github.com/slsa-framework/slsa-github-generator/blob/main/internal/builders/generic/README.md#referencing-the-slsa-generator + uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v2.0.0 + with: + base64-subjects: ${{ needs.build.outputs.attestation_hashes }} + upload-assets: false # we upload its attestation in create_tag job, otherwise it creates a new release + + # This job uses release artifact to publish to PyPi + # it exchanges JWT tokens with GitHub to obtain PyPi credentials + # since it's already registered as a Trusted Publisher. + # It uses the sealed build artifact (.whl, .tar.gz) to release it + release: + needs: [build, seal, provenance] + environment: release + runs-on: ubuntu-latest + permissions: + id-token: write # OIDC for PyPi Trusted Publisher feature + env: + RELEASE_VERSION: ${{ needs.seal.outputs.RELEASE_VERSION }} + steps: + # NOTE: we need actions/checkout in order to use our local actions (e.g., ./.github/actions) + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ needs.build.outputs.integrity_hash }} + artifact_name: ${{ needs.build.outputs.artifact_name }} + + - name: Upload to PyPi prod + if: ${{ !inputs.skip_pypi }} + uses: pypa/gh-action-pypi-publish@15c56dba361d8335944d31a2ecd17d700fc7bcbc # v1.12.2 + + # PyPi test maintenance affected us numerous times, leaving for history purposes + # - name: Upload to PyPi test + # if: ${{ !inputs.skip_pypi }} + # uses: pypa/gh-action-pypi-publish@15c56dba361d8335944d31a2ecd17d700fc7bcbc # v1.12.2 + # with: + # repository-url: https://test.pypi.org/legacy/ + + # We create a Git Tag using our release version (e.g., v3.16.0) + # using our sealed source code we created earlier. + # Because we bumped version of our project as part of CI + # we need to add this into git before pushing the tag + # otherwise the release commit will be used as the basis for the tag. + # Later, we create a PR to update trunk with our newest release version (e.g., bump_version job) + create_tag: + needs: [release, seal, provenance] + runs-on: ubuntu-latest + permissions: + contents: write + steps: + # NOTE: we need actions/checkout to authenticate and configure git first + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ needs.seal.outputs.integrity_hash }} + artifact_name: ${{ needs.seal.outputs.artifact_name }} + + - id: setup-git + name: Git client setup and refresh tip + run: | + git config user.name "Powertools for AWS Lambda (Python) bot" + git config user.email "151832416+aws-powertools-bot@users.noreply.github.com" + git config remote.origin.url >&- + + - name: Create Git Tag + run: | + git add pyproject.toml aws_lambda_powertools/shared/version.py + git commit -m "chore: version bump" + git tag -a v"${RELEASE_VERSION}" -m "release_version: v${RELEASE_VERSION}" + git push origin v"${RELEASE_VERSION}" + env: + RELEASE_VERSION: ${{ needs.seal.outputs.RELEASE_VERSION }} + + - name: Upload provenance + id: upload-provenance + uses: ./.github/actions/upload-release-provenance + with: + release_version: ${{ needs.seal.outputs.RELEASE_VERSION }} + provenance_name: ${{needs.provenance.outputs.provenance-name}} + github_token: ${{ secrets.GITHUB_TOKEN }} + + # Creates a PR with the latest version we've just released + # since our trunk is protected against any direct pushes from automation + bump_version: + needs: [release, seal] + permissions: + contents: write # create-pr action creates a temporary branch + pull-requests: write # create-pr action creates a PR using the temporary branch + runs-on: ubuntu-latest + steps: + # NOTE: we need actions/checkout to authenticate and configure git first + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ needs.seal.outputs.integrity_hash }} + artifact_name: ${{ needs.seal.outputs.artifact_name }} + + - name: Create PR + id: create-pr + uses: ./.github/actions/create-pr + with: + files: "pyproject.toml aws_lambda_powertools/shared/version.py" + temp_branch_prefix: "ci-bump" + pull_request_title: "chore(ci): bump version to ${{ needs.seal.outputs.RELEASE_VERSION }}" + github_token: ${{ secrets.GITHUB_TOKEN }} + + # This job compiles a Lambda Layer optimized for space and speed (e.g., Cython) + # It then deploys to Layer's Beta and Prod account, including SAR Beta and Prod account. + # It uses canaries to attest Layers can be used and imported between stages. + # Lastly, it updates our documentation with the latest Layer ARN for all regions + # + # NOTE + # + # Watch out for the depth limit of 4 nested workflow_calls. + # publish_layer -> publish_3_layer -> reusable_deploy_v3_layer_stack + publish_layer: + needs: [seal, release, create_tag] + secrets: inherit + permissions: + id-token: write + contents: write + pages: write + pull-requests: write + uses: ./.github/workflows/publish_v3_layer.yml + with: + latest_published_version: ${{ needs.seal.outputs.RELEASE_VERSION }} + pre_release: ${{ inputs.pre_release }} + source_code_artifact_name: ${{ needs.seal.outputs.artifact_name }} + source_code_integrity_hash: ${{ needs.seal.outputs.integrity_hash }} + + post_release: + needs: [seal, release, publish_layer] + permissions: + contents: read + issues: write + discussions: write + pull-requests: write + runs-on: ubuntu-latest + env: + RELEASE_VERSION: ${{ needs.seal.outputs.RELEASE_VERSION }} + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ needs.seal.outputs.integrity_hash }} + artifact_name: ${{ needs.seal.outputs.artifact_name }} + - name: Close issues related to this release + uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const post_release = require('.github/scripts/post_release.js') + await post_release({github, context, core}) diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/release.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/release.yml new file mode 100644 index 0000000000000000000000000000000000000000..6bb3943e83395e1196377d8c1a48fbba85dffff7 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/release.yml @@ -0,0 +1,376 @@ +name: Release + +# RELEASE PROCESS +# +# === Automated activities === +# +# 1. [Seal] Bump to release version and export source code with integrity hash +# 2. [Quality check] Restore sealed source code, run tests, linting, security and complexity base line +# 3. [Build] Restore sealed source code, create and export hashed build artifact for PyPi release (wheel, tarball) +# 4. [Provenance] Generates provenance for build, signs attestation with GitHub OIDC claims to confirm it came from this release pipeline, commit, org, repo, branch, hash, etc. +# 5. [Release] Restore built artifact, and publish package to PyPi prod repository +# 6. [Create Tag] Restore sealed source code, create a new git tag using released version, uploads provenance to latest draft release +# 7. [PR to bump version] Restore sealed source code, and create a PR to update trunk with latest released project metadata +# 8. [Publish Layer] Compile Layer and kick off pipeline for beta, prod, and canary releases +# 9. [Publish Layer] Update docs with latest Layer ARNs and Changelog +# 10. [Publish Layer] Create PR to update trunk so staged docs also point to the latest Layer ARN, when merged +# 12. [Post release] Close all issues labeled "pending-release" and notify customers about the release +# +# === Manual activities === +# +# 1. Kick off this workflow with the intended version +# 2. Update draft release notes after this workflow completes +# 3. If not already set, use `v<new version>` as a tag, e.g., v1.26.4, and select develop as target branch + +# NOTE +# +# See MAINTAINERS.md "Releasing a new version" for release mechanisms +# +# Every job is isolated and starts a new fresh container. + +env: + RELEASE_COMMIT: ${{ github.sha }} + RELEASE_TAG_VERSION: ${{ inputs.version_to_publish }} + +on: + workflow_dispatch: + inputs: + version_to_publish: + description: "Version to be released in PyPi, Docs, and Lambda Layer, e.g. v2.0.0, v2.0.0a0 (pre-release)" + default: v2.0.0 + required: true + skip_pypi: + description: "Skip publishing to PyPi as it can't publish more than once. Useful for semi-failed releases" + default: false + type: boolean + required: false + skip_code_quality: + description: "Skip tests, linting, and baseline. Only use if release fail for reasons beyond our control and you need a quick release." + default: false + type: boolean + required: false + pre_release: + description: "Publishes documentation using a pre-release tag (v2.0.0a0). You are still responsible for passing a pre-release version tag to the workflow." + default: false + type: boolean + required: false + +permissions: + contents: read + +jobs: + + # This job bumps the package version to the release version + # creates an integrity hash from the source code + # uploads the artifact with the integrity hash as the key name + # so subsequent jobs can restore from a trusted point in time to prevent tampering + seal: + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + integrity_hash: ${{ steps.seal_source_code.outputs.integrity_hash }} + artifact_name: ${{ steps.seal_source_code.outputs.artifact_name }} + RELEASE_VERSION: ${{ steps.release_version.outputs.RELEASE_VERSION }} + steps: + - name: Export release version + id: release_version + # transform tag format `v<version` to `<version>` + run: | + RELEASE_VERSION="${RELEASE_TAG_VERSION:1}" + echo "RELEASE_VERSION=${RELEASE_VERSION}" >> "$GITHUB_OUTPUT" + + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + # We use a pinned version of Poetry to be certain it won't modify source code before we create a hash + - name: Install poetry + run: | + pipx install git+https://github.com/python-poetry/poetry@68b88e5390720a3dd84f02940ec5200bfce39ac6 # v1.5.0 + pipx inject poetry git+https://github.com/monim67/poetry-bumpversion@315fe3324a699fa12ec20e202eb7375d4327d1c4 # v0.3.1 + + - name: Bump package version + id: versioning + run: poetry version "${RELEASE_VERSION}" + env: + RELEASE_VERSION: ${{ steps.release_version.outputs.RELEASE_VERSION}} + + - name: Seal and upload + id: seal_source_code + uses: ./.github/actions/seal + with: + artifact_name_prefix: "source" + + # This job runs our automated test suite, complexity and security baselines + # it ensures previously merged have been tested as part of the pull request process + # + # NOTE + # + # we don't upload the artifact after testing to prevent any tampering of our source code dependencies + quality_check: + needs: seal + runs-on: ubuntu-latest + permissions: + contents: read + steps: + # NOTE: we need actions/checkout to configure git first (pre-commit hooks in make dev) + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ needs.seal.outputs.integrity_hash }} + artifact_name: ${{ needs.seal.outputs.artifact_name }} + + - name: Debug cache restore + run: cat pyproject.toml + + - name: Install poetry + run: pipx install git+https://github.com/python-poetry/poetry@68b88e5390720a3dd84f02940ec5200bfce39ac6 # v1.5.0 + - name: Set up Python + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: "3.12" + cache: "poetry" + - name: Install dependencies + run: make dev + - name: Run all tests, linting and baselines + run: make pr + + # This job creates a release artifact (tar.gz, wheel) + # it checks out code from release commit for custom actions to work + # then restores the sealed source code (overwrites any potential tampering) + # it's done separately from release job to enforce least privilege. + # We export just the final build artifact for release + build: + runs-on: ubuntu-latest + needs: [quality_check, seal] + permissions: + contents: read + outputs: + integrity_hash: ${{ steps.seal_build.outputs.integrity_hash }} + artifact_name: ${{ steps.seal_build.outputs.artifact_name }} + attestation_hashes: ${{ steps.encoded_hash.outputs.attestation_hashes }} + steps: + # NOTE: we need actions/checkout to configure git first (pre-commit hooks in make dev) + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ needs.seal.outputs.integrity_hash }} + artifact_name: ${{ needs.seal.outputs.artifact_name }} + + - name: Install poetry + run: pipx install git+https://github.com/python-poetry/poetry@68b88e5390720a3dd84f02940ec5200bfce39ac6 # v1.5.0 + - name: Set up Python + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: "3.12" + cache: "poetry" + + - name: Build python package and wheel + run: poetry build + + - name: Seal and upload + id: seal_build + uses: ./.github/actions/seal + with: + artifact_name_prefix: "build" + files: "dist/" + + # NOTE: SLSA retraces our build to its artifact to ensure it wasn't tampered + # coupled with GitHub OIDC, SLSA can then confidently sign it came from this release pipeline+commit+branch+org+repo+actor+integrity hash + - name: Create attestation encoded hash for provenance + id: encoded_hash + working-directory: dist + run: echo "attestation_hashes=$(sha256sum ./* | base64 -w0)" >> "$GITHUB_OUTPUT" + + # This job creates a provenance file that describes how our release was built (all steps) + # after it verifies our build is reproducible within the same pipeline + # it confirms that its own software and the CI build haven't been tampered with (Trust but verify) + # lastly, it creates and sign an attestation (multiple.intoto.jsonl) that confirms + # this build artifact came from this GitHub org, branch, actor, commit ID, inputs that triggered this pipeline, and matches its integrity hash + # NOTE: supply chain threats review (we protect against all of them now): https://slsa.dev/spec/v1.0/threats-overview + provenance: + needs: [seal, build] + permissions: + contents: write # nested job explicitly require despite upload assets being set to false + actions: read # To read the workflow path. + id-token: write # To sign the provenance. + # NOTE: provenance fails if we use action pinning... it's a Github limitation + # because SLSA needs to trace & attest it came from a given branch; pinning doesn't expose that information + # https://github.com/slsa-framework/slsa-github-generator/blob/main/internal/builders/generic/README.md#referencing-the-slsa-generator + uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v2.0.0 + with: + base64-subjects: ${{ needs.build.outputs.attestation_hashes }} + upload-assets: false # we upload its attestation in create_tag job, otherwise it creates a new release + + # This job uses release artifact to publish to PyPi + # it exchanges JWT tokens with GitHub to obtain PyPi credentials + # since it's already registered as a Trusted Publisher. + # It uses the sealed build artifact (.whl, .tar.gz) to release it + release: + needs: [build, seal, provenance] + environment: release + runs-on: ubuntu-latest + permissions: + id-token: write # OIDC for PyPi Trusted Publisher feature + env: + RELEASE_VERSION: ${{ needs.seal.outputs.RELEASE_VERSION }} + steps: + # NOTE: we need actions/checkout in order to use our local actions (e.g., ./.github/actions) + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ needs.build.outputs.integrity_hash }} + artifact_name: ${{ needs.build.outputs.artifact_name }} + + - name: Upload to PyPi prod + if: ${{ !inputs.skip_pypi }} + uses: pypa/gh-action-pypi-publish@15c56dba361d8335944d31a2ecd17d700fc7bcbc # v1.12.2 + + # PyPi test maintenance affected us numerous times, leaving for history purposes + # - name: Upload to PyPi test + # if: ${{ !inputs.skip_pypi }} + # uses: pypa/gh-action-pypi-publish@15c56dba361d8335944d31a2ecd17d700fc7bcbc # v1.12.2 + # with: + # repository-url: https://test.pypi.org/legacy/ + + # We create a Git Tag using our release version (e.g., v2.16.0) + # using our sealed source code we created earlier. + # Because we bumped version of our project as part of CI + # we need to add this into git before pushing the tag + # otherwise the release commit will be used as the basis for the tag. + # Later, we create a PR to update trunk with our newest release version (e.g., bump_version job) + create_tag: + needs: [release, seal, provenance] + runs-on: ubuntu-latest + permissions: + contents: write + steps: + # NOTE: we need actions/checkout to authenticate and configure git first + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ needs.seal.outputs.integrity_hash }} + artifact_name: ${{ needs.seal.outputs.artifact_name }} + + - id: setup-git + name: Git client setup and refresh tip + run: | + git config user.name "Powertools for AWS Lambda (Python) bot" + git config user.email "151832416+aws-powertools-bot@users.noreply.github.com" + git config remote.origin.url >&- + + - name: Create Git Tag + run: | + git add pyproject.toml aws_lambda_powertools/shared/version.py + git commit -m "chore: version bump" + git tag -a v"${RELEASE_VERSION}" -m "release_version: v${RELEASE_VERSION}" + git push origin v"${RELEASE_VERSION}" + env: + RELEASE_VERSION: ${{ needs.seal.outputs.RELEASE_VERSION }} + + - name: Upload provenance + id: upload-provenance + uses: ./.github/actions/upload-release-provenance + with: + release_version: ${{ needs.seal.outputs.RELEASE_VERSION }} + provenance_name: ${{needs.provenance.outputs.provenance-name}} + github_token: ${{ secrets.GITHUB_TOKEN }} + + # Creates a PR with the latest version we've just released + # since our trunk is protected against any direct pushes from automation + bump_version: + needs: [release, seal] + permissions: + contents: write # create-pr action creates a temporary branch + pull-requests: write # create-pr action creates a PR using the temporary branch + runs-on: ubuntu-latest + steps: + # NOTE: we need actions/checkout to authenticate and configure git first + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ needs.seal.outputs.integrity_hash }} + artifact_name: ${{ needs.seal.outputs.artifact_name }} + + - name: Create PR + id: create-pr + uses: ./.github/actions/create-pr + with: + files: "pyproject.toml aws_lambda_powertools/shared/version.py" + temp_branch_prefix: "ci-bump" + pull_request_title: "chore(ci): bump version to ${{ needs.seal.outputs.RELEASE_VERSION }}" + github_token: ${{ secrets.GITHUB_TOKEN }} + + # This job compiles a Lambda Layer optimized for space and speed (e.g., Cython) + # It then deploys to Layer's Beta and Prod account, including SAR Beta and Prod account. + # It uses canaries to attest Layers can be used and imported between stages. + # Lastly, it updates our documentation with the latest Layer ARN for all regions + # + # NOTE + # + # Watch out for the depth limit of 4 nested workflow_calls. + # publish_layer -> publish_v2_layer -> reusable_deploy_v2_layer_stack + publish_layer: + needs: [seal, release, create_tag] + secrets: inherit + permissions: + id-token: write + contents: write + pages: write + pull-requests: write + uses: ./.github/workflows/publish_v2_layer.yml + with: + latest_published_version: ${{ needs.seal.outputs.RELEASE_VERSION }} + pre_release: ${{ inputs.pre_release }} + source_code_artifact_name: ${{ needs.seal.outputs.artifact_name }} + source_code_integrity_hash: ${{ needs.seal.outputs.integrity_hash }} + + post_release: + needs: [seal, release, publish_layer] + permissions: + contents: read + issues: write + discussions: write + pull-requests: write + runs-on: ubuntu-latest + env: + RELEASE_VERSION: ${{ needs.seal.outputs.RELEASE_VERSION }} + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ needs.seal.outputs.integrity_hash }} + artifact_name: ${{ needs.seal.outputs.artifact_name }} + + - name: Close issues related to this release + uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const post_release = require('.github/scripts/post_release.js') + await post_release({github, context, core}) diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_deploy_v2_layer_stack.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_deploy_v2_layer_stack.yml new file mode 100644 index 0000000000000000000000000000000000000000..eb4a9a58ee834c3367d76dee6de89f183a66750b --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_deploy_v2_layer_stack.yml @@ -0,0 +1,207 @@ +name: Deploy CDK Layer v2 stack + +# PROCESS +# +# 1. Split what AWS regions support ARM vs regions that Lambda support ARM +# 2. Deploy previously built layer for each AWS commercial region +# 3. Export all published Layers as JSON +# 4. Deploy Canaries to every deployed region to test whether Powertools can be imported etc. + +# USAGE +# +# NOTE: meant to be used with ./.github/workflows/publish_v2_layer.yml +# +# beta: +# needs: build-layer +# # lower privilege propagated from parent workflow (release.yml) +# permissions: +# id-token: write +# contents: read +# pages: write # docs will be updated with latest Layer ARNs +# pull-requests: write # creation-action will create a PR with Layer ARN updates +# uses: ./.github/workflows/reusable_deploy_v2_layer_stack.yml +# secrets: inherit +# with: +# stage: "BETA" +# artefact-name: "cdk-layer-artefact" +# environment: "layer-beta" +# latest_published_version: ${{ inputs.latest_published_version }} + +on: + workflow_call: + inputs: + stage: + description: "Deployment stage (BETA, PROD)" + required: true + type: string + artefact-name: + description: "CDK Layer Artefact name to download" + required: true + type: string + environment: + description: "GitHub Environment to use for encrypted secrets" + required: true + type: string + latest_published_version: + description: "Latest version that is published" + required: true + type: string + source_code_artifact_name: + description: "Artifact name to restore sealed source code" + type: string + required: true + source_code_integrity_hash: + description: "Sealed source code integrity hash" + type: string + required: true + +permissions: + contents: read + +env: + RELEASE_COMMIT: ${{ github.sha }} # it gets propagated from the caller for security reasons + +jobs: + deploy-cdk-stack: + runs-on: ubuntu-latest + environment: ${{ inputs.environment }} + # lower privilege propagated from parent workflow (publish_v2_layer.yml) + permissions: + id-token: write + pull-requests: none + contents: read + pages: none + defaults: + run: + working-directory: ./layer + strategy: + fail-fast: false + matrix: + # To get a list of current regions, use: + # aws ec2 describe-regions --all-regions --query "Regions[].RegionName" --output text | tr "\t" "\n" | sort + include: + - region: "af-south-1" + has_arm64_support: "true" + - region: "ap-east-1" + has_arm64_support: "true" + - region: "ap-northeast-1" + has_arm64_support: "true" + - region: "ap-northeast-2" + has_arm64_support: "true" + - region: "ap-northeast-3" + has_arm64_support: "true" + - region: "ap-south-1" + has_arm64_support: "true" + - region: "ap-south-2" + has_arm64_support: "true" + - region: "ap-southeast-1" + has_arm64_support: "true" + - region: "ap-southeast-2" + has_arm64_support: "true" + - region: "ap-southeast-3" + has_arm64_support: "true" + - region: "ap-southeast-4" + has_arm64_support: "true" + - region: "ca-central-1" + has_arm64_support: "true" + - region: "ca-west-1" + has_arm64_support: "true" + - region: "eu-central-1" + has_arm64_support: "true" + - region: "eu-central-2" + has_arm64_support: "true" + - region: "eu-north-1" + has_arm64_support: "true" + - region: "eu-south-1" + has_arm64_support: "true" + - region: "eu-south-2" + has_arm64_support: "true" + - region: "eu-west-1" + has_arm64_support: "true" + - region: "eu-west-2" + has_arm64_support: "true" + - region: "eu-west-3" + has_arm64_support: "true" + - region: "il-central-1" + has_arm64_support: "true" + - region: "me-central-1" + has_arm64_support: "true" + - region: "me-south-1" + has_arm64_support: "true" + - region: "sa-east-1" + has_arm64_support: "true" + - region: "us-east-1" + has_arm64_support: "true" + - region: "us-east-2" + has_arm64_support: "true" + - region: "us-west-1" + has_arm64_support: "true" + - region: "us-west-2" + has_arm64_support: "true" + steps: + - name: checkout + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ inputs.source_code_integrity_hash }} + artifact_name: ${{ inputs.source_code_artifact_name }} + + - name: Install poetry + run: pipx install git+https://github.com/python-poetry/poetry@68b88e5390720a3dd84f02940ec5200bfce39ac6 # v1.5.0 + - name: aws credentials + uses: aws-actions/configure-aws-credentials@5fd3084fc36e372ff1fff382a39b10d03659f355 # v2.2.0 + with: + aws-region: ${{ matrix.region }} + role-to-assume: ${{ secrets.AWS_LAYERS_ROLE_ARN }} + - name: Setup Node.js + uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + with: + node-version: "16.12" + - name: Setup python + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: "3.12" + cache: "pip" + - name: Resolve and install project dependencies + # CDK spawns system python when compiling stack + # therefore it ignores both activated virtual env and cached interpreter by GH + run: | + poetry export --format requirements.txt --output requirements.txt + pip install --require-hashes -r requirements.txt + - name: install cdk and deps + working-directory: ./ + run: | + npm ci + npx cdk --version + - name: install deps + run: poetry install + - name: Download artifact + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: ${{ inputs.artefact-name }} + path: layer + - name: unzip artefact + run: unzip cdk.out.zip + - name: CDK Deploy Layer + run: npx cdk deploy --app cdk.out --context region=${{ matrix.region }} --parameters HasARM64Support=${{ matrix.has_arm64_support }} 'LayerV2Stack' --require-approval never --verbose --outputs-file cdk-outputs.json + - name: Store latest Layer ARN + if: ${{ inputs.stage == 'PROD' }} + run: | + mkdir cdk-layer-stack + jq -r -c '.LayerV2Stack.LatestLayerArn' cdk-outputs.json > cdk-layer-stack/${{ matrix.region }}-layer-version.txt + jq -r -c '.LayerV2Stack.LatestLayerArm64Arn' cdk-outputs.json >> cdk-layer-stack/${{ matrix.region }}-layer-version.txt + cat cdk-layer-stack/${{ matrix.region }}-layer-version.txt + - name: Save Layer ARN artifact + if: ${{ inputs.stage == 'PROD' }} + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 + with: + name: cdk-layer-stack-${{ matrix.region }} + path: ./layer/cdk-layer-stack/* # NOTE: upload-artifact does not inherit working-directory setting. + if-no-files-found: error + retention-days: 1 + - name: CDK Deploy Canary + run: npx cdk deploy --app cdk.out --context region=${{ matrix.region }} --parameters DeployStage="${{ inputs.stage }}" --parameters HasARM64Support=${{ matrix.has_arm64_support }} 'CanaryV2Stack' --require-approval never --verbose diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_deploy_v2_sar.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_deploy_v2_sar.yml new file mode 100644 index 0000000000000000000000000000000000000000..f40d87434a91bd54b4f926cbc7c4aa26b3dfed80 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_deploy_v2_sar.yml @@ -0,0 +1,209 @@ +name: Deploy V2 SAR + +# PROCESS +# +# 1. This workflow starts after the layer artifact is produced on `publish_v2_layer` +# 2. We use the same layer artifact to ensure the SAR app is consistent with the published Lambda Layer +# 3. We publish the SAR for both x86_64 and arm64 (see `matrix` section) +# 4. We use `sam package` and `sam publish` to publish the SAR app +# 5. We remove the previous Canary stack (if present) and deploy a new one to test the SAR App. We retain the Canary in the account for debugging purposes +# 6. Finally the published SAR app is made public on the PROD environment + +# USAGE +# +# NOTE: meant to be used with ./.github/workflows/publish_v2_layer.yml +# +# sar-beta: +# needs: build-layer +# permissions: +# # lower privilege propagated from parent workflow (release.yml) +# id-token: write +# contents: read +# pull-requests: none +# pages: none +# uses: ./.github/workflows/reusable_deploy_v2_sar.yml +# secrets: inherit +# with: +# stage: "BETA" +# artefact-name: "cdk-layer-artefact" +# environment: "layer-beta" +# package-version: ${{ inputs.latest_published_version }} +# source_code_artifact_name: ${{ inputs.source_code_artifact_name }} +# source_code_integrity_hash: ${{ inputs.source_code_integrity_hash }} + +permissions: + id-token: write + contents: read + +env: + NODE_VERSION: 16.12 + AWS_REGION: eu-west-1 + SAR_NAME: aws-lambda-powertools-python-layer + TEST_STACK_NAME: serverlessrepo-v2-powertools-layer-test-stack + RELEASE_COMMIT: ${{ github.sha }} # it gets propagated from the caller for security reasons + +on: + workflow_call: + inputs: + stage: + description: "Deployment stage (BETA, PROD)" + required: true + type: string + artefact-name: + description: "CDK Layer Artefact name to download" + required: true + type: string + package-version: + description: "The version of the package to deploy" + required: true + type: string + environment: + description: "GitHub Environment to use for encrypted secrets" + required: true + type: string + source_code_artifact_name: + description: "Artifact name to restore sealed source code" + type: string + required: true + source_code_integrity_hash: + description: "Sealed source code integrity hash" + type: string + required: true + +jobs: + deploy-sar-app: + runs-on: ubuntu-latest + environment: ${{ inputs.environment }} + strategy: + matrix: + architecture: ["x86_64", "arm64"] + steps: + - name: checkout + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ inputs.source_code_integrity_hash }} + artifact_name: ${{ inputs.source_code_artifact_name }} + + + - name: AWS credentials + uses: aws-actions/configure-aws-credentials@5fd3084fc36e372ff1fff382a39b10d03659f355 # v2.2.0 + with: + aws-region: ${{ env.AWS_REGION }} + role-to-assume: ${{ secrets.AWS_LAYERS_ROLE_ARN }} + + # NOTE + # We connect to Layers account to log our intent to publish a SAR Layer + # we then jump to our specific SAR Account with the correctly scoped IAM Role + # this allows us to have a single trail when a release occurs for a given layer (beta+prod+SAR beta+SAR prod) + - name: AWS credentials SAR role + uses: aws-actions/configure-aws-credentials@5fd3084fc36e372ff1fff382a39b10d03659f355 # v2.2.0 + id: aws-credentials-sar-role + with: + aws-access-key-id: ${{ env.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ env.AWS_SECRET_ACCESS_KEY }} + aws-session-token: ${{ env.AWS_SESSION_TOKEN }} + role-duration-seconds: 1200 + aws-region: ${{ env.AWS_REGION }} + role-to-assume: ${{ secrets.AWS_SAR_V2_ROLE_ARN }} + - name: Setup Node.js + uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + with: + node-version: ${{ env.NODE_VERSION }} + - name: Download artifact + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: ${{ inputs.artefact-name }} + - name: Unzip artefact + run: unzip cdk.out.zip + - name: Configure SAR name + run: | + if [[ "${{ inputs.stage }}" == "BETA" ]]; then + SAR_NAME="test-${SAR_NAME}" + fi + echo SAR_NAME="${SAR_NAME}" >> "$GITHUB_ENV" + - name: Adds arm64 suffix to SAR name + if: ${{ matrix.architecture == 'arm64' }} + run: echo SAR_NAME="${SAR_NAME}-arm64" >> "$GITHUB_ENV" + - name: Normalize semantic version + id: semantic-version # v2.0.0a0 -> v2.0.0-a0 + env: + VERSION: ${{ inputs.package-version }} + run: | + VERSION="${VERSION/a/-a}" + echo "VERSION=${VERSION}" >> "$GITHUB_OUTPUT" + - name: Prepare SAR App + env: + VERSION: ${{ steps.semantic-version.outputs.VERSION }} + run: | + # From the generated LayerStack cdk.out artifact, find the layer asset path for the correct architecture. + # We'll use this as the source directory of our SAR. This way we are re-using the same layer asset for our SAR. + asset=$(jq -jc '.Resources[] | select(.Properties.CompatibleArchitectures == ["${{ matrix.architecture }}"]) | .Metadata."aws:asset:path"' cdk.out/LayerV2Stack.template.json) + + # fill in the SAR SAM template + sed \ + -e "s|<VERSION>|${VERSION}|g" \ + -e "s/<SAR_APP_NAME>/${{ env.SAR_NAME }}/g" \ + -e "s|<LAYER_CONTENT_PATH>|./cdk.out/$asset|g" \ + layer/sar/template.txt > template.yml + + # SAR needs a README and a LICENSE, so just copy the ones from the repo + cp README.md LICENSE "./cdk.out/$asset/" + + # Debug purposes + cat template.yml + - name: Deploy SAR + run: | + # Package the SAR to our SAR S3 bucket, and publish it + sam package --template-file template.yml --output-template-file packaged.yml --s3-bucket ${{ secrets.AWS_SAR_S3_BUCKET }} + sam publish --template packaged.yml --region "$AWS_REGION" + - name: Deploy BETA canary + if: ${{ inputs.stage == 'BETA' }} + run: | + if [[ "${{ matrix.architecture }}" == "arm64" ]]; then + TEST_STACK_NAME="${TEST_STACK_NAME}-arm64" + fi + + echo "Check if stack does not exist" + stack_exists=$(aws cloudformation list-stacks --query "StackSummaries[?(StackName == '$TEST_STACK_NAME' && StackStatus == 'CREATE_COMPLETE')].{StackId:StackId, StackName:StackName, CreationTime:CreationTime, StackStatus:StackStatus}" --output text) + + if [[ -n "$stack_exists" ]] ; then + echo "Found test deployment stack, removing..." + aws cloudformation delete-stack --stack-name "$TEST_STACK_NAME" + aws cloudformation wait stack-delete-complete --stack-name "$TEST_STACK_NAME" + fi + + echo "Creating canary stack" + echo "Stack name: $TEST_STACK_NAME" + aws serverlessrepo create-cloud-formation-change-set \ + --application-id arn:aws:serverlessrepo:${{ env.AWS_REGION }}:${{ steps.aws-credentials-sar-role.outputs.aws-account-id }}:applications/${{ env.SAR_NAME }} \ + --stack-name "${TEST_STACK_NAME/serverlessrepo-/}" \ + --capabilities CAPABILITY_NAMED_IAM + + CHANGE_SET_ID=$(aws cloudformation list-change-sets --stack-name "$TEST_STACK_NAME" --query 'Summaries[*].ChangeSetId' --output text) + aws cloudformation wait change-set-create-complete --change-set-name "$CHANGE_SET_ID" + aws cloudformation execute-change-set --change-set-name "$CHANGE_SET_ID" + aws cloudformation wait stack-create-complete --stack-name "$TEST_STACK_NAME" + + echo "Waiting until stack deployment completes..." + + echo "Exit with error if stack is not in CREATE_COMPLETE" + stack_exists=$(aws cloudformation list-stacks --query "StackSummaries[?(StackName == '$TEST_STACK_NAME' && StackStatus == 'CREATE_COMPLETE')].{StackId:StackId, StackName:StackName, CreationTime:CreationTime, StackStatus:StackStatus}") + if [[ -z "$stack_exists" ]] ; then + echo "Could find successful deployment, exit error..." + exit 1 + fi + echo "Deployment successful" + - name: Publish SAR + if: ${{ inputs.stage == 'PROD' }} + run: | + # wait until SAR registers the app, otherwise it fails to make it public + sleep 15 + echo "Make SAR app public" + aws serverlessrepo put-application-policy \ + --application-id arn:aws:serverlessrepo:${{ env.AWS_REGION }}:${{ steps.aws-credentials-sar-role.outputs.aws-account-id }}:applications/${{ env.SAR_NAME }} \ + --statements Principals='*',Actions=Deploy diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_deploy_v3_layer_stack.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_deploy_v3_layer_stack.yml new file mode 100644 index 0000000000000000000000000000000000000000..7d9c6e252667ac03448a1fee63dd5b2ddaf5e7e1 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_deploy_v3_layer_stack.yml @@ -0,0 +1,214 @@ +name: Deploy CDK Layer v3 stack + +# PROCESS +# +# 1. Split what AWS regions support ARM vs regions that Lambda support ARM +# 2. We build the Lambda layer for 3.8 to 3.12 Python runtime and both x86_64 and arm64 (see `matrix` section) +# 3. Deploy previously built layer for each AWS commercial region +# 4. Export all published Layers as JSON +# 5. Deploy Canaries to every deployed region to test whether Powertools can be imported etc. + +# USAGE +# +# NOTE: meant to be used with ./.github/workflows/publish_v3_layer.yml +# +# beta: +# needs: build-layer +# # lower privilege propagated from parent workflow (release.yml) +# permissions: +# id-token: write +# contents: read +# pages: write # docs will be updated with latest Layer ARNs +# pull-requests: write # creation-action will create a PR with Layer ARN updates +# uses: ./.github/workflows/reusable_deploy_v3_layer_stack.yml +# secrets: inherit +# with: +# stage: "BETA" +# environment: "layer-beta" +# source_code_artifact_name: code.zip +# source_code_integrity_hash: sha256string + +on: + workflow_call: + inputs: + stage: + description: "Deployment stage (BETA, PROD)" + required: true + type: string + environment: + description: "GitHub Environment to use for encrypted secrets" + required: true + type: string + source_code_artifact_name: + description: "Artifact name to restore sealed source code" + type: string + required: true + source_code_integrity_hash: + description: "Sealed source code integrity hash" + type: string + required: true + +permissions: + contents: read + +env: + RELEASE_COMMIT: ${{ github.sha }} # it gets propagated from the caller for security reasons + +jobs: + deploy-cdk-stack: + runs-on: ubuntu-latest + environment: ${{ inputs.environment }} + # lower privilege propagated from parent workflow (publish_v3_layer.yml) + permissions: + id-token: write + pull-requests: none + contents: read + pages: none + defaults: + run: + working-directory: ./layer_v3 + strategy: + fail-fast: false + matrix: + # To get a list of current regions, use: + # aws ec2 describe-regions --all-regions --query "Regions[].RegionName" --output text | tr "\t" "\n" | sort + region: ["af-south-1", "ap-east-1", "ap-northeast-1", "ap-northeast-2", "ap-northeast-3", + "ap-south-1", "ap-south-2", "ap-southeast-1", "ap-southeast-2", "ap-southeast-3", + "ap-southeast-4", "ca-central-1", "ca-west-1", "eu-central-1", "eu-central-2", + "eu-north-1", "eu-south-1", "eu-south-2", "eu-west-1", "eu-west-2", "eu-west-3", + "il-central-1", "me-central-1", "me-south-1", "sa-east-1", "us-east-1", + "us-east-2", "us-west-1", "us-west-2"] + python-version: ["3.8","3.9","3.10","3.11","3.12","3.13"] + include: + - region: "af-south-1" + has_arm64_support: "true" + - region: "ap-east-1" + has_arm64_support: "true" + - region: "ap-northeast-1" + has_arm64_support: "true" + - region: "ap-northeast-2" + has_arm64_support: "true" + - region: "ap-northeast-3" + has_arm64_support: "true" + - region: "ap-south-1" + has_arm64_support: "true" + - region: "ap-south-2" + has_arm64_support: "true" + - region: "ap-southeast-1" + has_arm64_support: "true" + - region: "ap-southeast-2" + has_arm64_support: "true" + - region: "ap-southeast-3" + has_arm64_support: "true" + - region: "ap-southeast-4" + has_arm64_support: "true" + - region: "ca-central-1" + has_arm64_support: "true" + - region: "ca-west-1" + has_arm64_support: "true" + - region: "eu-central-1" + has_arm64_support: "true" + - region: "eu-central-2" + has_arm64_support: "true" + - region: "eu-north-1" + has_arm64_support: "true" + - region: "eu-south-1" + has_arm64_support: "true" + - region: "eu-south-2" + has_arm64_support: "true" + - region: "eu-west-1" + has_arm64_support: "true" + - region: "eu-west-2" + has_arm64_support: "true" + - region: "eu-west-3" + has_arm64_support: "true" + - region: "il-central-1" + has_arm64_support: "true" + - region: "me-central-1" + has_arm64_support: "true" + - region: "me-south-1" + has_arm64_support: "true" + - region: "sa-east-1" + has_arm64_support: "true" + - region: "us-east-1" + has_arm64_support: "true" + - region: "us-east-2" + has_arm64_support: "true" + - region: "us-west-1" + has_arm64_support: "true" + - region: "us-west-2" + has_arm64_support: "true" + steps: + - name: checkout + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ inputs.source_code_integrity_hash }} + artifact_name: ${{ inputs.source_code_artifact_name }} + + - name: Install poetry + run: pipx install git+https://github.com/python-poetry/poetry@68b88e5390720a3dd84f02940ec5200bfce39ac6 # v1.5.0 + - name: aws credentials + uses: aws-actions/configure-aws-credentials@5fd3084fc36e372ff1fff382a39b10d03659f355 # v2.2.0 + with: + aws-region: ${{ matrix.region }} + role-to-assume: ${{ secrets.AWS_LAYERS_ROLE_ARN }} + - name: Setup Node.js + uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + with: + node-version: "18.20.4" + - name: Setup python + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: ${{ matrix.python-version }} + cache: "pip" + - name: Resolve and install project dependencies + # CDK spawns system python when compiling stack + # therefore it ignores both activated virtual env and cached interpreter by GH + run: | + poetry export --format requirements.txt --output requirements.txt + pip install --require-hashes -r requirements.txt + - name: install cdk and deps + working-directory: ./ + run: | + npm ci + npx cdk --version + - name: install deps + run: poetry install + - name: Download artifact + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: cdk-layer-artifact-py${{ matrix.python-version }} + path: layer_v3 + - name: unzip artefact + run: unzip cdk.py${{ matrix.python-version }}.out.zip + - name: Define constants + id: constants + run: | + PYTHON_VERSION=$(echo ${{ matrix.python-version }} | tr -d '.') + echo "PYTHON_VERSION=${PYTHON_VERSION}" >> "$GITHUB_OUTPUT" + LAYER_VERSION=${{ matrix.region }}-$PYTHON_VERSION-layer-version.txt + echo "LAYER_VERSION=${LAYER_VERSION}" >> "$GITHUB_OUTPUT" + - name: CDK Deploy Layer + run: npx cdk deploy --app cdk.out --context region=${{ matrix.region }} --parameters HasARM64Support=${{ matrix.has_arm64_support }} "LayerV3Stack-python${{steps.constants.outputs.PYTHON_VERSION}}" --require-approval never --verbose --outputs-file cdk-outputs.json + - name: Store latest Layer ARN + if: ${{ inputs.stage == 'PROD' }} + run: | + mkdir cdk-layer-stack + jq -r -c ".[\"LayerV3Stack-python${{steps.constants.outputs.PYTHON_VERSION}}\"].LatestLayerArn" cdk-outputs.json > cdk-layer-stack/${{steps.constants.outputs.LAYER_VERSION}} + jq -r -c ".[\"LayerV3Stack-python${{steps.constants.outputs.PYTHON_VERSION}}\"].LatestLayerArm64Arn" cdk-outputs.json >> cdk-layer-stack/${{steps.constants.outputs.LAYER_VERSION}} + cat cdk-layer-stack/${{steps.constants.outputs.LAYER_VERSION}} + - name: Save Layer ARN artifact + if: ${{ inputs.stage == 'PROD' }} + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 + with: + name: cdk-layer-stack-${{ matrix.region }}-${{ matrix.python-version }} + path: ./layer_v3/cdk-layer-stack/* # NOTE: upload-artifact does not inherit working-directory setting. + if-no-files-found: error + retention-days: 1 + - name: CDK Deploy Canary + run: npx cdk deploy --app cdk.out --context region=${{ matrix.region }} --parameters DeployStage="${{ inputs.stage }}" --parameters HasARM64Support=${{ matrix.has_arm64_support }} "CanaryV3Stack-python${{steps.constants.outputs.PYTHON_VERSION}}" --require-approval never --verbose diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_deploy_v3_sar.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_deploy_v3_sar.yml new file mode 100644 index 0000000000000000000000000000000000000000..2f4c14e54869c5a6eae4232cc1fa2bb1188ab38c --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_deploy_v3_sar.yml @@ -0,0 +1,211 @@ +name: Deploy V3 SAR + +# PROCESS +# +# 1. This workflow starts after the layer artifact is produced on `publish_v3_layer` +# 2. We use the same layer artifact to ensure the SAR app is consistent with the published Lambda Layer +# 3. We publish the SAR for 3.8 to 3.13 Python runtime and both x86_64 and arm64 (see `matrix` section) +# 4. We use `sam package` and `sam publish` to publish the SAR app +# 5. We remove the previous Canary stack (if present) and deploy a new one to test the SAR App. We retain the Canary in the account for debugging purposes +# 6. Finally the published SAR app is made public on the PROD environment + +# USAGE +# +# NOTE: meant to be used with ./.github/workflows/publish_v3_layer.yml +# +# sar-beta: +# needs: build-layer +# permissions: +# # lower privilege propagated from parent workflow (release.yml) +# id-token: write +# contents: read +# pull-requests: none +# pages: none +# uses: ./.github/workflows/reusable_deploy_v3_sar.yml +# secrets: inherit +# with: +# stage: "BETA" +# environment: "layer-beta" +# package-version: ${{ inputs.latest_published_version }} +# source_code_artifact_name: ${{ inputs.source_code_artifact_name }} +# source_code_integrity_hash: ${{ inputs.source_code_integrity_hash }} + +permissions: + id-token: write + contents: read + +env: + NODE_VERSION: 18.20.4 + AWS_REGION: eu-west-1 + SAR_NAME: aws-lambda-powertools-python-layer-v3 + TEST_STACK_NAME: serverlessrepo-v3-powertools-layer-test-stack + RELEASE_COMMIT: ${{ github.sha }} # it gets propagated from the caller for security reasons + +on: + workflow_call: + inputs: + stage: + description: "Deployment stage (BETA, PROD)" + required: true + type: string + package-version: + description: "The version of the package to deploy" + required: true + type: string + environment: + description: "GitHub Environment to use for encrypted secrets" + required: true + type: string + source_code_artifact_name: + description: "Artifact name to restore sealed source code" + type: string + required: true + source_code_integrity_hash: + description: "Sealed source code integrity hash" + type: string + required: true + +jobs: + deploy-sar-app: + runs-on: ubuntu-latest + environment: ${{ inputs.environment }} + strategy: + matrix: + architecture: ["x86_64", "arm64"] + python-version: ["3.8","3.9","3.10","3.11","3.12","3.13"] + steps: + - name: checkout + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ env.RELEASE_COMMIT }} + + - name: Restore sealed source code + uses: ./.github/actions/seal-restore + with: + integrity_hash: ${{ inputs.source_code_integrity_hash }} + artifact_name: ${{ inputs.source_code_artifact_name }} + + + - name: AWS credentials + uses: aws-actions/configure-aws-credentials@5fd3084fc36e372ff1fff382a39b10d03659f355 # v2.2.0 + with: + aws-region: ${{ env.AWS_REGION }} + role-to-assume: ${{ secrets.AWS_LAYERS_ROLE_ARN }} + + # NOTE + # We connect to Layers account to log our intent to publish a SAR Layer + # we then jump to our specific SAR Account with the correctly scoped IAM Role + # this allows us to have a single trail when a release occurs for a given layer (beta+prod+SAR beta+SAR prod) + - name: AWS credentials SAR role + uses: aws-actions/configure-aws-credentials@5fd3084fc36e372ff1fff382a39b10d03659f355 # v2.2.0 + id: aws-credentials-sar-role + with: + aws-access-key-id: ${{ env.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ env.AWS_SECRET_ACCESS_KEY }} + aws-session-token: ${{ env.AWS_SESSION_TOKEN }} + role-duration-seconds: 1200 + aws-region: ${{ env.AWS_REGION }} + role-to-assume: ${{ secrets.AWS_SAR_V2_ROLE_ARN }} + - name: Setup Node.js + uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + with: + node-version: ${{ env.NODE_VERSION }} + - name: Download artifact + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: cdk-layer-artifact-py${{ matrix.python-version }} + - name: Unzip artefact + run: unzip cdk.py${{ matrix.python-version }}.out.zip + - name: normalize Python Version + run: | + PYTHON_VERSION=$(echo ${{ matrix.python-version }} | tr -d '.') + echo "PYTHON_VERSION=${PYTHON_VERSION}" >> "$GITHUB_ENV" + - name: Configure SAR name + run: | + if [[ "${{ inputs.stage }}" == "BETA" ]]; then + SAR_NAME="test-${SAR_NAME}" + fi + ARCH_NAME=$(echo ${{ matrix.architecture }} | tr -d '_') + SAR_NAME="${SAR_NAME}-python${{env.PYTHON_VERSION}}-${ARCH_NAME}" + echo SAR_NAME="${SAR_NAME}" >> "$GITHUB_ENV" + - name: Normalize semantic version + id: semantic-version # v2.0.0a0 -> v2.0.0-a0 + env: + VERSION: ${{ inputs.package-version }} + run: | + # VERSION="${VERSION/a/-a}" + VERSION="3.0.0" + echo "VERSION=${VERSION}" >> "$GITHUB_OUTPUT" + - name: Prepare SAR App + env: + VERSION: ${{ steps.semantic-version.outputs.VERSION }} + run: | + # From the generated LayerStack cdk.out artifact, find the layer asset path for the correct architecture. + # We'll use this as the source directory of our SAR. This way we are re-using the same layer asset for our SAR. + PYTHON_VERSION=$(echo ${{ matrix.python-version }} | tr -d '.') + asset=$(jq -jc '.Resources[] | select(.Properties.CompatibleArchitectures == ["${{ matrix.architecture }}"]) | .Metadata."aws:asset:path"' "cdk.out/LayerV3Stack-python${PYTHON_VERSION}.template.json") + + # fill in the SAR SAM template + sed \ + -e "s|<VERSION>|${VERSION}|g" \ + -e "s/<SAR_APP_NAME>/${{ env.SAR_NAME }}/g" \ + -e "s|<LAYER_CONTENT_PATH>|./cdk.out/$asset|g" \ + -e "s|<PYTHON_RUNTIME>|${{ matrix.python-version }}|g" \ + -e "s|<ARCHITECTURE>|${{ matrix.architecture }}|g" \ + layer/sar/template.txt > template.yml + + # SAR needs a README and a LICENSE, so just copy the ones from the repo + cp README.md LICENSE "./cdk.out/$asset/" + - name: Deploy SAR + run: | + # Debug purposes + cat template.yml + + # Package the SAR to our SAR S3 bucket, and publish it + sam package --template-file template.yml --output-template-file packaged.yml --s3-bucket ${{ secrets.AWS_SAR_S3_BUCKET_V3 }} + sam publish --template packaged.yml --region "$AWS_REGION" + - name: Deploy BETA canary + if: ${{ inputs.stage == 'BETA' }} + run: | + ARCH_NAME=$(echo ${{ matrix.architecture }} | tr -d '_') + TEST_STACK_NAME="${TEST_STACK_NAME}-python${{env.PYTHON_VERSION}}-${ARCH_NAME}" + + echo "Check if stack does not exist" + stack_exists=$(aws cloudformation list-stacks --query "StackSummaries[?(StackName == '$TEST_STACK_NAME' && StackStatus == 'CREATE_COMPLETE')].{StackId:StackId, StackName:StackName, CreationTime:CreationTime, StackStatus:StackStatus}" --output text) + + if [[ -n "$stack_exists" ]] ; then + echo "Found test deployment stack, removing..." + aws cloudformation delete-stack --stack-name "$TEST_STACK_NAME" + aws cloudformation wait stack-delete-complete --stack-name "$TEST_STACK_NAME" + fi + + echo "Creating canary stack" + echo "Stack name: $TEST_STACK_NAME" + aws serverlessrepo create-cloud-formation-change-set \ + --application-id arn:aws:serverlessrepo:${{ env.AWS_REGION }}:${{ steps.aws-credentials-sar-role.outputs.aws-account-id }}:applications/${{ env.SAR_NAME }} \ + --stack-name "${TEST_STACK_NAME/serverlessrepo-/}" \ + --capabilities CAPABILITY_NAMED_IAM + + CHANGE_SET_ID=$(aws cloudformation list-change-sets --stack-name "$TEST_STACK_NAME" --query 'Summaries[*].ChangeSetId' --output text) + aws cloudformation wait change-set-create-complete --change-set-name "$CHANGE_SET_ID" + aws cloudformation execute-change-set --change-set-name "$CHANGE_SET_ID" + aws cloudformation wait stack-create-complete --stack-name "$TEST_STACK_NAME" + + echo "Waiting until stack deployment completes..." + + echo "Exit with error if stack is not in CREATE_COMPLETE" + stack_exists=$(aws cloudformation list-stacks --query "StackSummaries[?(StackName == '$TEST_STACK_NAME' && StackStatus == 'CREATE_COMPLETE')].{StackId:StackId, StackName:StackName, CreationTime:CreationTime, StackStatus:StackStatus}") + if [[ -z "$stack_exists" ]] ; then + echo "Could find successful deployment, exit error..." + exit 1 + fi + echo "Deployment successful" + - name: Publish SAR + if: ${{ inputs.stage == 'PROD' }} + run: | + # wait until SAR registers the app, otherwise it fails to make it public + sleep 15 + echo "Make SAR app public" + aws serverlessrepo put-application-policy \ + --application-id arn:aws:serverlessrepo:${{ env.AWS_REGION }}:${{ steps.aws-credentials-sar-role.outputs.aws-account-id }}:applications/${{ env.SAR_NAME }} \ + --statements Principals='*',Actions=Deploy diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_export_pr_details.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_export_pr_details.yml new file mode 100644 index 0000000000000000000000000000000000000000..f4f1bab630e57911ab8e53f1e4e67a6a4dc2147f --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_export_pr_details.yml @@ -0,0 +1,115 @@ +name: Export previously recorded PR + +# PROCESS +# +# 1. Fetch PR details previously saved from untrusted location +# 2. Parse details for safety +# 3. Export only what's needed for automation, e.g., PR number, title, body, author, action, whether is merged + +# USAGE +# +# see .github/workflows/on_merged_pr.yml and related for full example. +# +# NOTE: meant to be used with workflows that react to a given PR state (labeling, new, merged, etc.) +# done separately to isolate security practices and make it reusable. + + +on: + workflow_call: + inputs: + record_pr_workflow_id: + description: "Record PR workflow execution ID to download PR details" + required: true + type: number + workflow_origin: # see https://github.com/aws-powertools/powertools-lambda-python/issues/1349 + description: "Repository full name for runner integrity" + required: true + type: string + secrets: + token: + description: "GitHub Actions temporary and scoped token" + required: true + # Map the workflow outputs to job outputs + outputs: + prNumber: + description: "PR Number" + value: ${{ jobs.export_pr_details.outputs.prNumber }} + prTitle: + description: "PR Title" + value: ${{ jobs.export_pr_details.outputs.prTitle }} + prBody: + description: "PR Body as string" + value: ${{ jobs.export_pr_details.outputs.prBody }} + prAuthor: + description: "PR author username" + value: ${{ jobs.export_pr_details.outputs.prAuthor }} + prAction: + description: "PR event action" + value: ${{ jobs.export_pr_details.outputs.prAction }} + prIsMerged: + description: "Whether PR is merged" + value: ${{ jobs.export_pr_details.outputs.prIsMerged }} + prLabels: + description: "PR Labels" + value: ${{ jobs.export_pr_details.outputs.prLabels }} + +permissions: + contents: read + +jobs: + export_pr_details: + permissions: + actions: read # download PR artifact + # see https://github.com/aws-powertools/powertools-lambda-python/issues/1349 + if: inputs.workflow_origin == 'aws-powertools/powertools-lambda-python' + runs-on: ubuntu-latest + env: + FILENAME: pr.txt + # Map the job outputs to step outputs + outputs: + prNumber: ${{ steps.prNumber.outputs.prNumber }} + prTitle: ${{ steps.prTitle.outputs.prTitle }} + prBody: ${{ steps.prBody.outputs.prBody }} + prAuthor: ${{ steps.prAuthor.outputs.prAuthor }} + prAction: ${{ steps.prAction.outputs.prAction }} + prIsMerged: ${{ steps.prIsMerged.outputs.prIsMerged }} + prLabels: ${{ steps.prLabels.outputs.prLabels }} + steps: + - name: Checkout repository # in case caller workflow doesn't checkout thus failing with file not found + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: "Download previously saved PR" + uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1 + env: + WORKFLOW_ID: ${{ inputs.record_pr_workflow_id }} + # For security, we only download artifacts tied to the successful PR recording workflow + with: + github-token: ${{ secrets.token }} + script: | + const script = require('.github/scripts/download_pr_artifact.js') + await script({github, context, core}) + # NodeJS standard library doesn't provide ZIP capabilities; use system `unzip` command instead + - name: "Unzip PR artifact" + run: unzip pr.zip + # NOTE: We need separate steps for each mapped output and respective IDs + # otherwise the parent caller won't see them regardless on how outputs are set. + - name: "Export Pull Request Number" + id: prNumber + run: echo prNumber="$(jq -c '.number' "${FILENAME}")" >> "$GITHUB_OUTPUT" + - name: "Export Pull Request Title" + id: prTitle + run: echo prTitle="$(jq -c '.pull_request.title' "${FILENAME}")" >> "$GITHUB_OUTPUT" + - name: "Export Pull Request Body" + id: prBody + run: echo prBody="$(jq -c '.pull_request.body' "${FILENAME}")" >> "$GITHUB_OUTPUT" + - name: "Export Pull Request Author" + id: prAuthor + run: echo prAuthor="$(jq -c '.pull_request.user.login' "${FILENAME}")" >> "$GITHUB_OUTPUT" + - name: "Export Pull Request Action" + id: prAction + run: echo prAction="$(jq -c '.action' "${FILENAME}")" >> "$GITHUB_OUTPUT" + - name: "Export Pull Request Merged status" + id: prIsMerged + run: echo prIsMerged="$(jq -c '.pull_request.merged' "${FILENAME}")" >> "$GITHUB_OUTPUT" + - name: "Export Pull Request labels" + id: prLabels + run: echo prLabels="$(jq -c '.labels' "${FILENAME}")" >> "$GITHUB_OUTPUT" diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_publish_changelog.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_publish_changelog.yml new file mode 100644 index 0000000000000000000000000000000000000000..a0bc289e669f78f4bc65762d7ab9c67298409712 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_publish_changelog.yml @@ -0,0 +1,41 @@ +name: Build and publish latest changelog + +# see ./.github/workflows/build_changelog.yml for docs + +on: + workflow_call: + +env: + TEMP_BRANCH_PREFIX: "ci-changelog" + PULL_REQUEST_TITLE: "chore(ci): changelog rebuild" + FILES_TO_COMMIT: "CHANGELOG.md" + +permissions: + contents: read + +jobs: + publish_changelog: + if: github.repository == 'aws-powertools/powertools-lambda-python' + # Force Github action to run only a single job at a time (based on the group name) + # This is to prevent race-condition and inconsistencies with changelog push + concurrency: + group: changelog-build + runs-on: ubuntu-latest + permissions: + contents: write # create temporary branch with changelog + pull-requests: write # create PR + steps: + - name: Checkout repository # reusable workflows start clean, so we need to checkout again + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: "Generate latest changelog" + run: make changelog + - name: Create PR + id: create-pr + uses: ./.github/actions/create-pr + with: + files: ${{ env.FILES_TO_COMMIT }} + temp_branch_prefix: ${{ env.TEMP_BRANCH_PREFIX }} + pull_request_title: ${{ env.PULL_REQUEST_TITLE }} + github_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_publish_docs.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_publish_docs.yml new file mode 100644 index 0000000000000000000000000000000000000000..eb3fbde7f8c767d5df73d8fa52ad9b7b79f3aa08 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/reusable_publish_docs.yml @@ -0,0 +1,129 @@ +name: Reusable publish documentation + +# see .github/workflows/on_push_docs.yml for docs + +env: + ORIGIN: aws-powertools/powertools-lambda-python + +on: + workflow_call: + inputs: + version: + description: "Version to build and publish docs (1.28.0, develop)" + required: true + type: string + alias: + description: "Alias to associate version (latest, stage)" + required: true + type: string + detached_mode: + description: "Whether it's running in git detached mode to ensure git is sync'd" + required: false + default: false + type: boolean + git_ref: + description: "Branch or commit ID to checkout from" + required: false + type: string + default: develop + +permissions: + contents: read + +jobs: + publish_docs: + if: github.repository == 'aws-powertools/powertools-lambda-python' + # Force Github action to run only a single job at a time (based on the group name) + # This is to prevent "race-condition" in publishing a new version of doc to `gh-pages` + concurrency: + group: on-docs-rebuild + runs-on: ubuntu-latest + environment: "Docs" + permissions: + contents: write # push to gh-pages + id-token: write # trade JWT token for AWS credentials in AWS Docs account + pages: write # uncomment if mike fails as we migrated to S3 hosting + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + ref: ${{ inputs.git_ref }} + - name: Install poetry + run: pipx install poetry + - name: Set up Python + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: "3.12" + cache: "poetry" + - name: Install dependencies + run: make dev + - name: Git client setup + run: | + git config --global user.name Docs deploy + git config --global user.email aws-devax-open-source@amazon.com + - name: Git refresh tip (detached mode) + # Git Detached mode (release notes) doesn't have origin + if: ${{ inputs.detached_mode }} + run: | + git config pull.rebase true + git config remote.origin.url >&- || git remote add origin https://github.com/"$ORIGIN" + git pull origin "$BRANCH" + env: + BRANCH: ${{ inputs.git_ref }} + - name: Build docs website and API reference + env: + VERSION: ${{ inputs.version }} + ALIAS: ${{ inputs.alias }} + run: | + make release-docs VERSION="$VERSION" ALIAS="$ALIAS" + poetry run mike set-default --push latest + + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@5fd3084fc36e372ff1fff382a39b10d03659f355 + with: + aws-region: us-east-1 + role-to-assume: ${{ secrets.AWS_DOCS_ROLE_ARN }} + - name: Copy API Docs + run: | + cp -r api site/ + - name: Deploy Docs (Version) + env: + VERSION: ${{ inputs.version }} + ALIAS: ${{ inputs.alias }} + run: | + aws s3 sync \ + site/ \ + s3://${{ secrets.AWS_DOCS_BUCKET }}/lambda-python/${{ env.VERSION }}/ + - name: Deploy Docs (Alias) + env: + VERSION: ${{ inputs.version }} + ALIAS: ${{ inputs.alias }} + run: | + aws s3 sync \ + site/ \ + s3://${{ secrets.AWS_DOCS_BUCKET }}/lambda-python/${{ env.ALIAS }}/ + - name: Deploy Docs (Version JSON) + env: + VERSION: ${{ inputs.version }} + ALIAS: ${{ inputs.alias }} + # We originally used "mike" from PyPi to manage versions for us, but since we moved to S3, we can't use it to manage versions any more. + # Instead, we're using some shell script that manages the versions. + # + # Operations: + # 1. Download the versions.json file from S3 + # 2. Find any reference to the alias and delete it from the versions file + # 3. This is voodoo (don't use JQ): + # - we assign the input as $o and the new version/alias as $n, + # - we check if the version number exists in the file already (for republishing docs) + # - if it's an alias (stage/latest/*) or old version, we do nothing and output $o (original input) + # - if it's a new version number, we add it at position 0 in the array. + # 4. Once done, we'll upload it back to S3. + run: | + aws s3 cp \ + s3://${{ secrets.AWS_DOCS_BUCKET }}/lambda-python/versions.json \ + versions_old.json + jq 'del(.[].aliases[] | select(. == "${{ env.ALIAS }}"))' < versions_old.json > versions_proc.json + jq '. as $o | [{"title": "${{ env.VERSION }}", "version": "${{ env.VERSION }}", "aliases": ["${{ env.ALIAS }}"] }] as $n | $n | if .[0].title | test("[a-z]+") or any($o[].title == $n[0].title;.) then [($o | .[] | select(.title == $n[0].title).aliases += $n[0].aliases | . )] else $n + $o end' < versions_proc.json > versions.json + aws s3 cp \ + versions.json \ + s3://${{ secrets.AWS_DOCS_BUCKET }}/lambda-python/versions.json diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/run-e2e-tests.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/run-e2e-tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..b9909868caabd2e60142278888077e7bbe159d98 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/run-e2e-tests.yml @@ -0,0 +1,80 @@ +name: Run end-to-end tests + +# PROCESS +# +# 1. Install all dependencies and spin off containers for all supported Python versions +# 2. Install pinned CDK version +# 3. Trade JWT token for AWS credentials to Test account +# 4. Run E2E in parallel for each feature + +# USAGE +# +# see MAINTAINERS.md#internals for full details on mechanics. +# +# Always triggered on new PR merge. + +on: + workflow_dispatch: + + push: + branches: + - develop + - v3 + paths: + - "aws_lambda_powertools/**" + - "tests/e2e/**" + - "pyproject.toml" + - "poetry.lock" + - "mypy.ini" + - "parallel_run_e2e.py" + +# Maintenance: Add support for triggering on `run-e2e` label +# and enforce repo origin to prevent abuse + +env: + AWS_DEFAULT_REGION: us-east-1 + +concurrency: e2e + +permissions: + contents: read + +jobs: + run: + runs-on: aws-powertools_ubuntu-latest_8-core + permissions: + id-token: write # needed to request JWT with GitHub's OIDC Token endpoint. docs: https://bit.ly/3MNgQO9 + contents: read # checkout code + strategy: + fail-fast: false # needed so if a version fails, the others will still be able to complete and cleanup + matrix: + version: ["3.8", "3.9", "3.10", "3.11", "3.12","3.13"] + if: ${{ github.actor != 'dependabot[bot]' && github.repository == 'aws-powertools/powertools-lambda-python' }} + steps: + - name: "Checkout" + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Install poetry + run: pipx install poetry + - name: "Use Python" + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: ${{ matrix.version }} + architecture: "x64" + cache: "poetry" + - name: Setup Node.js + uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + with: + node-version: "20.10.0" + - name: Install CDK CLI + run: | + npm ci + npx cdk --version + - name: Install dependencies + run: make dev + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@5fd3084fc36e372ff1fff382a39b10d03659f355 # v2.2.0 + with: + role-to-assume: ${{ secrets.AWS_TEST_ROLE_ARN }} + aws-region: ${{ env.AWS_DEFAULT_REGION }} + - name: Test + run: make e2e-test diff --git a/testbed/aws-powertools__powertools-lambda-python/.github/workflows/secure_workflows.yml b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/secure_workflows.yml new file mode 100644 index 0000000000000000000000000000000000000000..59f0b04bf1faac11119d328e7a7369045aa2fee2 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/.github/workflows/secure_workflows.yml @@ -0,0 +1,39 @@ +name: Lockdown untrusted workflows + +# PROCESS +# +# 1. Scans for any external GitHub Action being used without version pinning (@<commit-sha> vs @v3) +# 2. Scans for insecure practices for inline bash scripts (shellcheck) +# 3. Fail CI and prevent PRs to be merged if any malpractice is found + +# USAGE +# +# Always triggered on new PR, PR changes and PR merge. + + +on: + push: + paths: + - ".github/workflows/**" + pull_request: + paths: + - ".github/workflows/**" + +permissions: + contents: read + +jobs: + enforce_pinned_workflows: + name: Harden Security + runs-on: ubuntu-latest + permissions: + contents: read # checkout code and subsequently GitHub action workflows + steps: + - name: Checkout code + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Ensure 3rd party workflows have SHA pinned + uses: zgosalvez/github-actions-ensure-sha-pinned-actions@38608ef4fb69adae7f1eac6eeb88e67b7d083bfd # v3.0.16 + with: + allowlist: | + slsa-framework/slsa-github-generator + aws-powertools/actions diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/__init__.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ffbb2abe4ae916131b966029f3876998543caf57 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/__init__.py @@ -0,0 +1,32 @@ +""" +Event handler decorators for common Lambda events +""" + +from aws_lambda_powertools.event_handler.api_gateway import ( + ALBResolver, + APIGatewayHttpResolver, + ApiGatewayResolver, + APIGatewayRestResolver, + CORSConfig, + Response, +) +from aws_lambda_powertools.event_handler.appsync import AppSyncResolver +from aws_lambda_powertools.event_handler.bedrock_agent import BedrockAgentResolver +from aws_lambda_powertools.event_handler.lambda_function_url import ( + LambdaFunctionUrlResolver, +) +from aws_lambda_powertools.event_handler.vpc_lattice import VPCLatticeResolver, VPCLatticeV2Resolver + +__all__ = [ + "AppSyncResolver", + "APIGatewayRestResolver", + "APIGatewayHttpResolver", + "ALBResolver", + "ApiGatewayResolver", + "BedrockAgentResolver", + "CORSConfig", + "LambdaFunctionUrlResolver", + "Response", + "VPCLatticeResolver", + "VPCLatticeV2Resolver", +] diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/api_gateway.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/api_gateway.py new file mode 100644 index 0000000000000000000000000000000000000000..fcb22addf6b04eef3a74556a97c30842d2f61ee0 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/api_gateway.py @@ -0,0 +1,2699 @@ +from __future__ import annotations + +import base64 +import json +import logging +import re +import traceback +import warnings +import zlib +from abc import ABC, abstractmethod +from enum import Enum +from functools import partial +from http import HTTPStatus +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Generic, Literal, Mapping, Match, Pattern, Sequence, TypeVar, cast + +from typing_extensions import override + +from aws_lambda_powertools.event_handler import content_types +from aws_lambda_powertools.event_handler.exceptions import NotFoundError, ServiceError +from aws_lambda_powertools.event_handler.openapi.constants import DEFAULT_API_VERSION, DEFAULT_OPENAPI_VERSION +from aws_lambda_powertools.event_handler.openapi.exceptions import RequestValidationError, SchemaValidationError +from aws_lambda_powertools.event_handler.openapi.types import ( + COMPONENT_REF_PREFIX, + METHODS_WITH_BODY, + OpenAPIResponse, + OpenAPIResponseContentModel, + OpenAPIResponseContentSchema, + validation_error_definition, + validation_error_response_definition, +) +from aws_lambda_powertools.event_handler.util import ( + _FrozenDict, + _FrozenListDict, + _validate_openapi_security_parameters, + extract_origin_header, +) +from aws_lambda_powertools.shared.cookies import Cookie +from aws_lambda_powertools.shared.functions import powertools_dev_is_set +from aws_lambda_powertools.shared.json_encoder import Encoder +from aws_lambda_powertools.utilities.data_classes import ( + ALBEvent, + APIGatewayProxyEvent, + APIGatewayProxyEventV2, + BedrockAgentEvent, + LambdaFunctionUrlEvent, + VPCLatticeEvent, + VPCLatticeEventV2, +) +from aws_lambda_powertools.utilities.data_classes.common import BaseProxyEvent + +logger = logging.getLogger(__name__) + +_DYNAMIC_ROUTE_PATTERN = r"(<\w+>)" +_SAFE_URI = "-._~()'!*:@,;=+&$" # https://www.ietf.org/rfc/rfc3986.txt +# API GW/ALB decode non-safe URI chars; we must support them too +_UNSAFE_URI = r"%<> \[\]{}|^" +_NAMED_GROUP_BOUNDARY_PATTERN = rf"(?P\1[{_SAFE_URI}{_UNSAFE_URI}\\w]+)" +_DEFAULT_OPENAPI_RESPONSE_DESCRIPTION = "Successful Response" +_ROUTE_REGEX = "^{}$" + +ResponseEventT = TypeVar("ResponseEventT", bound=BaseProxyEvent) +ResponseT = TypeVar("ResponseT") + +if TYPE_CHECKING: + from aws_lambda_powertools.event_handler.openapi.compat import ( + JsonSchemaValue, + ModelField, + ) + from aws_lambda_powertools.event_handler.openapi.models import ( + Contact, + License, + OpenAPI, + SecurityScheme, + Server, + Tag, + ) + from aws_lambda_powertools.event_handler.openapi.params import Dependant + from aws_lambda_powertools.event_handler.openapi.swagger_ui.oauth2 import ( + OAuth2Config, + ) + from aws_lambda_powertools.event_handler.openapi.types import ( + TypeModelOrEnum, + ) + from aws_lambda_powertools.shared.cookies import Cookie + from aws_lambda_powertools.utilities.typing import LambdaContext + + +class ProxyEventType(Enum): + """An enumerations of the supported proxy event types.""" + + APIGatewayProxyEvent = "APIGatewayProxyEvent" + APIGatewayProxyEventV2 = "APIGatewayProxyEventV2" + ALBEvent = "ALBEvent" + BedrockAgentEvent = "BedrockAgentEvent" + VPCLatticeEvent = "VPCLatticeEvent" + VPCLatticeEventV2 = "VPCLatticeEventV2" + LambdaFunctionUrlEvent = "LambdaFunctionUrlEvent" + + +class CORSConfig: + """CORS Config + + Examples + -------- + + Simple CORS example using the default permissive CORS, note that this should only be used during early prototyping. + + ```python + from aws_lambda_powertools.event_handler.api_gateway import ( + APIGatewayRestResolver, CORSConfig + ) + + app = APIGatewayRestResolver(cors=CORSConfig()) + + @app.get("/my/path") + def with_cors(): + return {"message": "Foo"} + ``` + + Using a custom CORSConfig where `with_cors` used the custom provided CORSConfig and `without_cors` + do not include any CORS headers. + + ```python + from aws_lambda_powertools.event_handler.api_gateway import ( + APIGatewayRestResolver, CORSConfig + ) + + cors_config = CORSConfig( + allow_origin="https://wwww.example.com/", + extra_origins=["https://dev.example.com/"], + expose_headers=["x-exposed-response-header"], + allow_headers=["x-custom-request-header"], + max_age=100, + allow_credentials=True, + ) + app = APIGatewayRestResolver(cors=cors_config) + + @app.get("/my/path") + def with_cors(): + return {"message": "Foo"} + + @app.get("/another-one", cors=False) + def without_cors(): + return {"message": "Foo"} + ``` + """ + + _REQUIRED_HEADERS = ["Authorization", "Content-Type", "X-Amz-Date", "X-Api-Key", "X-Amz-Security-Token"] + + def __init__( + self, + allow_origin: str = "*", + extra_origins: list[str] | None = None, + allow_headers: list[str] | None = None, + expose_headers: list[str] | None = None, + max_age: int | None = None, + allow_credentials: bool = False, + ): + """ + Parameters + ---------- + allow_origin: str + The value of the `Access-Control-Allow-Origin` to send in the response. Defaults to "*", but should + only be used during development. + extra_origins: list[str] | None + The list of additional allowed origins. + allow_headers: list[str] | None + The list of additional allowed headers. This list is added to list of + built-in allowed headers: `Authorization`, `Content-Type`, `X-Amz-Date`, + `X-Api-Key`, `X-Amz-Security-Token`. + expose_headers: list[str] | None + A list of values to return for the Access-Control-Expose-Headers + max_age: int | None + The value for the `Access-Control-Max-Age` + allow_credentials: bool + A boolean value that sets the value of `Access-Control-Allow-Credentials` + """ + + self._allowed_origins = [allow_origin] + + if extra_origins: + self._allowed_origins.extend(extra_origins) + + self.allow_headers = set(self._REQUIRED_HEADERS + (allow_headers or [])) + self.expose_headers = expose_headers or [] + self.max_age = max_age + self.allow_credentials = allow_credentials + + def to_dict(self, origin: str | None) -> dict[str, str]: + """Builds the configured Access-Control http headers""" + + # If there's no Origin, don't add any CORS headers + if not origin: + return {} + + # If the origin doesn't match any of the allowed origins, and we don't allow all origins ("*"), + # don't add any CORS headers + if origin not in self._allowed_origins and "*" not in self._allowed_origins: + return {} + + # The origin matched an allowed origin, so return the CORS headers + headers = { + "Access-Control-Allow-Origin": origin, + "Access-Control-Allow-Headers": CORSConfig.build_allow_methods(self.allow_headers), + } + + if self.expose_headers: + headers["Access-Control-Expose-Headers"] = ",".join(self.expose_headers) + if self.max_age is not None: + headers["Access-Control-Max-Age"] = str(self.max_age) + if origin != "*" and self.allow_credentials is True: + headers["Access-Control-Allow-Credentials"] = "true" + return headers + + def allowed_origin(self, extracted_origin: str) -> str | None: + if extracted_origin in self._allowed_origins: + return extracted_origin + if extracted_origin is not None and "*" in self._allowed_origins: + return "*" + + return None + + @staticmethod + def build_allow_methods(methods: set[str]) -> str: + """Build sorted comma delimited methods for Access-Control-Allow-Methods header + + Parameters + ---------- + methods : set[str] + Set of HTTP Methods + + Returns + ------- + set[str] + Formatted string with all HTTP Methods allowed for CORS e.g., `GET, OPTIONS` + + """ + return ",".join(sorted(methods)) + + +class Response(Generic[ResponseT]): + """Response data class that provides greater control over what is returned from the proxy event""" + + def __init__( + self, + status_code: int, + content_type: str | None = None, + body: ResponseT | None = None, + headers: Mapping[str, str | list[str]] | None = None, + cookies: list[Cookie] | None = None, + compress: bool | None = None, + ): + """ + + Parameters + ---------- + status_code: int + Http status code, example 200 + content_type: str + Optionally set the Content-Type header, example "application/json". Note this will be merged into any + provided http headers + body: str | bytes | None + Optionally set the response body. Note: bytes body will be automatically base64 encoded + headers: Mapping[str, str | list[str]] + Optionally set specific http headers. Setting "Content-Type" here would override the `content_type` value. + cookies: list[Cookie] + Optionally set cookies. + """ + self.status_code = status_code + self.body = body + self.base64_encoded = False + self.headers: dict[str, str | list[str]] = dict(headers) if headers else {} + self.cookies = cookies or [] + self.compress = compress + self.content_type = content_type + if content_type: + self.headers.setdefault("Content-Type", content_type) + + def is_json(self) -> bool: + """ + Returns True if the response is JSON, based on the Content-Type. + """ + content_type = self.headers.get("Content-Type", "") + if isinstance(content_type, list): + content_type = content_type[0] + return content_type.startswith("application/json") + + +class Route: + """Internally used Route Configuration""" + + def __init__( + self, + method: str, + path: str, + rule: Pattern, + func: Callable, + cors: bool, + compress: bool, + cache_control: str | None = None, + summary: str | None = None, + description: str | None = None, + responses: dict[int, OpenAPIResponse] | None = None, + response_description: str | None = None, + tags: list[str] | None = None, + operation_id: str | None = None, + include_in_schema: bool = True, + security: list[dict[str, list[str]]] | None = None, + openapi_extensions: dict[str, Any] | None = None, + middlewares: list[Callable[..., Response]] | None = None, + ): + """ + + Parameters + ---------- + + method: str + The HTTP method, example "GET" + path: str + The path of the route + rule: Pattern + The route rule, example "/my/path" + func: Callable + The route handler function + cors: bool + Whether or not to enable CORS for this route + compress: bool + Whether or not to enable gzip compression for this route + cache_control: str | None + The cache control header value, example "max-age=3600" + summary: str | None + The OpenAPI summary for this route + description: str | None + The OpenAPI description for this route + responses: dict[int, OpenAPIResponse] | None + The OpenAPI responses for this route + response_description: str | None + The OpenAPI response description for this route + tags: list[str] | None + The list of OpenAPI tags to be used for this route + operation_id: str | None + The OpenAPI operationId for this route + include_in_schema: bool + Whether or not to include this route in the OpenAPI schema + security: list[dict[str, list[str]]], optional + The OpenAPI security for this route + openapi_extensions: dict[str, Any], optional + Additional OpenAPI extensions as a dictionary. + middlewares: list[Callable[..., Response]] | None + The list of route middlewares to be called in order. + """ + self.method = method.upper() + self.path = "/" if path.strip() == "" else path + + # OpenAPI spec only understands paths with { }. So we'll have to convert Powertools' < >. + # https://swagger.io/specification/#path-templating + self.openapi_path = re.sub(r"<(.*?)>", lambda m: f"{{{''.join(m.group(1))}}}", self.path) + + self.rule = rule + self.func = func + self._middleware_stack = func + self.cors = cors + self.compress = compress + self.cache_control = cache_control + self.summary = summary + self.description = description + self.responses = responses + self.response_description = response_description + self.tags = tags or [] + self.include_in_schema = include_in_schema + self.security = security + self.openapi_extensions = openapi_extensions + self.middlewares = middlewares or [] + self.operation_id = operation_id or self._generate_operation_id() + + # _middleware_stack_built is used to ensure the middleware stack is only built once. + self._middleware_stack_built = False + + # _dependant is used to cache the dependant model for the handler function + self._dependant: Dependant | None = None + + # _body_field is used to cache the dependant model for the body field + self._body_field: ModelField | None = None + + def __call__( + self, + router_middlewares: list[Callable], + app: ApiGatewayResolver, + route_arguments: dict[str, str], + ) -> dict | tuple | Response: + """Calling the Router class instance will trigger the following actions: + 1. If Route Middleware stack has not been built, build it + 2. Call the Route Middleware stack wrapping the original function + handler with the app and route arguments. + + Parameters + ---------- + router_middlewares: list[Callable] + The list of Router Middlewares (assigned to ALL routes) + app: "ApiGatewayResolver" + The ApiGatewayResolver instance to pass into the middleware stack + route_arguments: dict[str, str] + The route arguments to pass to the app function (extracted from the Api Gateway + Lambda Message structure from AWS) + + Returns + ------- + dict | tuple | Response + API Response object in ALL cases, except when the original API route + handler is called which may also return a dict, tuple, or Response. + """ + + # Save CPU cycles by building middleware stack once + if not self._middleware_stack_built: + self._build_middleware_stack(router_middlewares=router_middlewares) + + # If debug is turned on then output the middleware stack to the console + if app._debug: + print(f"\nProcessing Route:::{self.func.__name__} ({app.context['_path']})") + # Collect ALL middleware for debug printing - include internal _registered_api_adapter + all_middlewares = router_middlewares + self.middlewares + [_registered_api_adapter] + print("\nMiddleware Stack:") + print("=================") + print("\n".join(getattr(item, "__name__", "Unknown") for item in all_middlewares)) + print("=================") + + # Add Route Arguments to app context + app.append_context(_route_args=route_arguments) + + # Call the Middleware Wrapped _call_stack function handler with the app + return self._middleware_stack(app) + + def _build_middleware_stack(self, router_middlewares: list[Callable[..., Any]]) -> None: + """ + Builds the middleware stack for the handler by wrapping each + handler in an instance of MiddlewareWrapper which is used to contain the state + of each middleware step. + + Middleware is represented by a standard Python Callable construct. Any Middleware + handler wanting to short-circuit the middlware call chain can raise an exception + to force the Python call stack created by the handler call-chain to naturally un-wind. + + This becomes a simple concept for developers to understand and reason with - no additional + gymanstics other than plain old try ... except. + + Notes + ----- + The Route Middleware stack is processed in reverse order. This is so the stack of + middleware handlers is applied in the order of being added to the handler. + """ + all_middlewares = router_middlewares + self.middlewares + logger.debug(f"Building middleware stack: {all_middlewares}") + + # IMPORTANT: + # this must be the last middleware in the stack (tech debt for backward + # compatibility purposes) + # + # This adapter will: + # 1. Call the registered API passing only the expected route arguments extracted from the path + # and not the middleware. + # 2. Adapt the response type of the route handler (dict | tuple | Response) + # and normalise into a Response object so middleware will always have a constant signature + all_middlewares.append(_registered_api_adapter) + + # Wrap the original route handler function in the middleware handlers + # using the MiddlewareWrapper class callable construct in reverse order to + # ensure middleware is applied in the order the user defined. + # + # Start with the route function and wrap from last to the first Middleware handler. + for handler in reversed(all_middlewares): + self._middleware_stack = MiddlewareFrame(current_middleware=handler, next_middleware=self._middleware_stack) + + self._middleware_stack_built = True + + @property + def dependant(self) -> Dependant: + if self._dependant is None: + from aws_lambda_powertools.event_handler.openapi.dependant import get_dependant + + self._dependant = get_dependant(path=self.openapi_path, call=self.func, responses=self.responses) + + return self._dependant + + @property + def body_field(self) -> ModelField | None: + if self._body_field is None: + from aws_lambda_powertools.event_handler.openapi.dependant import get_body_field + + self._body_field = get_body_field(dependant=self.dependant, name=self.operation_id) + + return self._body_field + + def _get_openapi_path( + self, + *, + dependant: Dependant, + operation_ids: set[str], + model_name_map: dict[TypeModelOrEnum, str], + field_mapping: dict[tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue], + ) -> tuple[dict[str, Any], dict[str, Any]]: + """ + Returns the OpenAPI path and definitions for the route. + """ + from aws_lambda_powertools.event_handler.openapi.dependant import get_flat_params + + path = {} + definitions: dict[str, Any] = {} + + # Gather all the route parameters + operation = self._openapi_operation_metadata(operation_ids=operation_ids) + parameters: list[dict[str, Any]] = [] + all_route_params = get_flat_params(dependant) + operation_params = self._openapi_operation_parameters( + all_route_params=all_route_params, + model_name_map=model_name_map, + field_mapping=field_mapping, + ) + parameters.extend(operation_params) + + # Add security if present + if self.security: + operation["security"] = self.security + + # Add OpenAPI extensions if present + if self.openapi_extensions: + operation.update(self.openapi_extensions) + + # Add the parameters to the OpenAPI operation + if parameters: + all_parameters = {(param["in"], param["name"]): param for param in parameters} + required_parameters = {(param["in"], param["name"]): param for param in parameters if param.get("required")} + all_parameters.update(required_parameters) + operation["parameters"] = list(all_parameters.values()) + + # Add the request body to the OpenAPI operation, if applicable + if self.method.upper() in METHODS_WITH_BODY: + request_body_oai = self._openapi_operation_request_body( + body_field=self.body_field, + model_name_map=model_name_map, + field_mapping=field_mapping, + ) + if request_body_oai: + operation["requestBody"] = request_body_oai + + # Validation failure response (422) will always be part of the schema + operation_responses: dict[int, OpenAPIResponse] = { + 422: { + "description": "Validation Error", + "content": { + "application/json": { + "schema": {"$ref": COMPONENT_REF_PREFIX + "HTTPValidationError"}, + }, + }, + }, + } + + # Add the response to the OpenAPI operation + if self.responses: + for status_code in list(self.responses): + response = self.responses[status_code] + + # Case 1: there is not 'content' key + if "content" not in response: + response["content"] = { + "application/json": self._openapi_operation_return( + param=dependant.return_param, + model_name_map=model_name_map, + field_mapping=field_mapping, + ), + } + + # Case 2: there is a 'content' key + else: + # Need to iterate to transform any 'model' into a 'schema' + for content_type, payload in response["content"].items(): + new_payload: OpenAPIResponseContentSchema + + # Case 2.1: the 'content' has a model + if "model" in payload: + # Find the model in the dependant's extra models + return_field = next( + filter( + lambda model: model.type_ is cast(OpenAPIResponseContentModel, payload)["model"], + self.dependant.response_extra_models, + ), + ) + if not return_field: + raise AssertionError("Model declared in custom responses was not found") + + new_payload = self._openapi_operation_return( + param=return_field, + model_name_map=model_name_map, + field_mapping=field_mapping, + ) + + # Case 2.2: the 'content' has a schema + else: + # Do nothing! We already have what we need! + new_payload = payload + + response["content"][content_type] = new_payload + + # Merge the user provided response with the default responses + operation_responses[status_code] = response + else: + # Set the default 200 response + response_schema = self._openapi_operation_return( + param=dependant.return_param, + model_name_map=model_name_map, + field_mapping=field_mapping, + ) + + # Add the response schema to the OpenAPI 200 response + operation_responses[200] = { + "description": self.response_description or _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION, + "content": {"application/json": response_schema}, + } + + operation["responses"] = operation_responses + path[self.method.lower()] = operation + + # Add the validation error schema to the definitions, but only if it hasn't been added yet + if "ValidationError" not in definitions: + definitions.update( + { + "ValidationError": validation_error_definition, + "HTTPValidationError": validation_error_response_definition, + }, + ) + + # Generate the response schema + return path, definitions + + def _openapi_operation_summary(self) -> str: + """ + Returns the OpenAPI operation summary. If the user has not provided a summary, we + generate one based on the route path and method. + """ + return self.summary or f"{self.method.upper()} {self.openapi_path}" + + def _openapi_operation_metadata(self, operation_ids: set[str]) -> dict[str, Any]: + """ + Returns the OpenAPI operation metadata. If the user has not provided a description, we + generate one based on the route path and method. + """ + operation: dict[str, Any] = {} + + # Ensure tags is added to the operation + if self.tags: + operation["tags"] = self.tags + + # Ensure summary is added to the operation + operation["summary"] = self._openapi_operation_summary() + + # Ensure description is added to the operation + if self.description: + operation["description"] = self.description + + # Ensure operationId is unique + if self.operation_id in operation_ids: + message = f"Duplicate Operation ID {self.operation_id} for function {self.func.__name__}" + file_name = getattr(self.func, "__globals__", {}).get("__file__") + if file_name: + message += f" in {file_name}" + warnings.warn(message, stacklevel=1) + + # Adds the operation + operation_ids.add(self.operation_id) + operation["operationId"] = self.operation_id + + return operation + + @staticmethod + def _openapi_operation_request_body( + *, + body_field: ModelField | None, + model_name_map: dict[TypeModelOrEnum, str], + field_mapping: dict[tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue], + ) -> dict[str, Any] | None: + """ + Returns the OpenAPI operation request body. + """ + from aws_lambda_powertools.event_handler.openapi.compat import ModelField, get_schema_from_model_field + from aws_lambda_powertools.event_handler.openapi.params import Body + + # Check that there is a body field and it's a Pydantic's model field + if not body_field: + return None + + if not isinstance(body_field, ModelField): + raise AssertionError(f"Expected ModelField, got {body_field}") + + # Generate the request body schema + body_schema = get_schema_from_model_field( + field=body_field, + model_name_map=model_name_map, + field_mapping=field_mapping, + ) + + field_info = cast(Body, body_field.field_info) + request_media_type = field_info.media_type + required = body_field.required + request_body_oai: dict[str, Any] = {} + if required: + request_body_oai["required"] = required + + if field_info.description: + request_body_oai["description"] = field_info.description + + # Generate the request body media type + request_media_content: dict[str, Any] = {"schema": body_schema} + request_body_oai["content"] = {request_media_type: request_media_content} + return request_body_oai + + @staticmethod + def _openapi_operation_parameters( + *, + all_route_params: Sequence[ModelField], + model_name_map: dict[TypeModelOrEnum, str], + field_mapping: dict[tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue], + ) -> list[dict[str, Any]]: + """ + Returns the OpenAPI operation parameters. + """ + from aws_lambda_powertools.event_handler.openapi.compat import ( + get_schema_from_model_field, + ) + from aws_lambda_powertools.event_handler.openapi.params import Param + + parameters = [] + parameter: dict[str, Any] = {} + + for param in all_route_params: + field_info = param.field_info + field_info = cast(Param, field_info) + if not field_info.include_in_schema: + continue + + param_schema = get_schema_from_model_field( + field=param, + model_name_map=model_name_map, + field_mapping=field_mapping, + ) + + parameter = { + "name": param.alias, + "in": field_info.in_.value, + "required": param.required, + "schema": param_schema, + } + + if field_info.description: + parameter["description"] = field_info.description + + if field_info.deprecated: + parameter["deprecated"] = field_info.deprecated + + parameters.append(parameter) + + return parameters + + @staticmethod + def _openapi_operation_return( + *, + param: ModelField | None, + model_name_map: dict[TypeModelOrEnum, str], + field_mapping: dict[tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue], + ) -> OpenAPIResponseContentSchema: + """ + Returns the OpenAPI operation return. + """ + if param is None: + return {} + + from aws_lambda_powertools.event_handler.openapi.compat import ( + get_schema_from_model_field, + ) + + return_schema = get_schema_from_model_field( + field=param, + model_name_map=model_name_map, + field_mapping=field_mapping, + ) + + return {"schema": return_schema} + + def _generate_operation_id(self) -> str: + operation_id = self.func.__name__ + self.openapi_path + operation_id = re.sub(r"\W", "_", operation_id) + operation_id = operation_id + "_" + self.method.lower() + return operation_id + + +class ResponseBuilder(Generic[ResponseEventT]): + """Internally used Response builder""" + + def __init__( + self, + response: Response, + serializer: Callable[[Any], str] = partial(json.dumps, separators=(",", ":"), cls=Encoder), + route: Route | None = None, + ): + self.response = response + self.serializer = serializer + self.route = route + + def _add_cors(self, event: ResponseEventT, cors: CORSConfig): + """Update headers to include the configured Access-Control headers""" + extracted_origin_header = extract_origin_header(event.resolved_headers_field) + + origin = cors.allowed_origin(extracted_origin_header) + if origin is not None: + self.response.headers.update(cors.to_dict(origin)) + + def _add_cache_control(self, cache_control: str): + """Set the specified cache control headers for 200 http responses. For non-200 `no-cache` is used.""" + cache_control = cache_control if self.response.status_code == 200 else "no-cache" + self.response.headers["Cache-Control"] = cache_control + + @staticmethod + def _has_compression_enabled( + route_compression: bool, + response_compression: bool | None, + event: ResponseEventT, + ) -> bool: + """ + Checks if compression is enabled. + + NOTE: Response compression takes precedence. + + Parameters + ---------- + route_compression: bool, optional + A boolean indicating whether compression is enabled or not in the route setting. + response_compression: bool, optional + A boolean indicating whether compression is enabled or not in the response setting. + event: ResponseEventT + The event object containing the request details. + + Returns + ------- + bool + True if compression is enabled and the "gzip" encoding is accepted, False otherwise. + """ + encoding = event.headers.get("accept-encoding", "") + if "gzip" in encoding: + if response_compression is not None: + return response_compression # e.g., Response(compress=False/True)) + if route_compression: + return True # e.g., @app.get(compress=True) + + return False + + def _compress(self): + """Compress the response body, but only if `Accept-Encoding` headers includes gzip.""" + self.response.headers["Content-Encoding"] = "gzip" + if isinstance(self.response.body, str): + logger.debug("Converting string response to bytes before compressing it") + self.response.body = bytes(self.response.body, "utf-8") + gzip = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16) + self.response.body = gzip.compress(self.response.body) + gzip.flush() + + def _route(self, event: ResponseEventT, cors: CORSConfig | None): + """Optionally handle any of the route's configure response handling""" + if self.route is None: + return + if self.route.cors: + self._add_cors(event, cors or CORSConfig()) + if self.route.cache_control: + self._add_cache_control(self.route.cache_control) + if self._has_compression_enabled( + route_compression=self.route.compress, + response_compression=self.response.compress, + event=event, + ): + self._compress() + + def build(self, event: ResponseEventT, cors: CORSConfig | None = None) -> dict[str, Any]: + """Build the full response dict to be returned by the lambda""" + + # We only apply the serializer when the content type is JSON and the + # body is not a str, to avoid double encoding + if self.response.is_json() and not isinstance(self.response.body, str): + self.response.body = self.serializer(self.response.body) + + self._route(event, cors) + + if isinstance(self.response.body, bytes): + logger.debug("Encoding bytes response with base64") + self.response.base64_encoded = True + self.response.body = base64.b64encode(self.response.body).decode() + + return { + "statusCode": self.response.status_code, + "body": self.response.body, + "isBase64Encoded": self.response.base64_encoded, + **event.header_serializer().serialize(headers=self.response.headers, cookies=self.response.cookies), + } + + +class BaseRouter(ABC): + current_event: BaseProxyEvent + lambda_context: LambdaContext + context: dict + _router_middlewares: list[Callable] = [] + processed_stack_frames: list[str] = [] + + @abstractmethod + def route( + self, + rule: str, + method: Any, + cors: bool | None = None, + compress: bool = False, + cache_control: str | None = None, + summary: str | None = None, + description: str | None = None, + responses: dict[int, OpenAPIResponse] | None = None, + response_description: str = _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION, + tags: list[str] | None = None, + operation_id: str | None = None, + include_in_schema: bool = True, + security: list[dict[str, list[str]]] | None = None, + openapi_extensions: dict[str, Any] | None = None, + middlewares: list[Callable[..., Any]] | None = None, + ): + raise NotImplementedError() + + def use(self, middlewares: list[Callable[..., Response]]) -> None: + """ + Add one or more global middlewares that run before/after route specific middleware. + + NOTE: Middlewares are called in insertion order. + + Parameters + ---------- + middlewares: list[Callable[..., Response]] + List of global middlewares to be used + + Examples + -------- + + Add middlewares to be used for every request processed by the Router. + + ```python + from aws_lambda_powertools import Logger + from aws_lambda_powertools.event_handler import APIGatewayRestResolver, Response + from aws_lambda_powertools.event_handler.middlewares import NextMiddleware + + logger = Logger() + app = APIGatewayRestResolver() + + def log_request_response(app: APIGatewayRestResolver, next_middleware: NextMiddleware) -> Response: + logger.info("Incoming request", path=app.current_event.path, request=app.current_event.raw_event) + + result = next_middleware(app) + logger.info("Response received", response=result.__dict__) + + return result + + app.use(middlewares=[log_request_response]) + + + def lambda_handler(event, context): + return app.resolve(event, context) + ``` + """ + self._router_middlewares = self._router_middlewares + middlewares + + def get( + self, + rule: str, + cors: bool | None = None, + compress: bool = False, + cache_control: str | None = None, + summary: str | None = None, + description: str | None = None, + responses: dict[int, OpenAPIResponse] | None = None, + response_description: str = _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION, + tags: list[str] | None = None, + operation_id: str | None = None, + include_in_schema: bool = True, + security: list[dict[str, list[str]]] | None = None, + openapi_extensions: dict[str, Any] | None = None, + middlewares: list[Callable[..., Any]] | None = None, + ): + """Get route decorator with GET `method` + + Examples + -------- + Simple example with a custom lambda handler using the Tracer capture_lambda_handler decorator + + ```python + from aws_lambda_powertools import Tracer + from aws_lambda_powertools.event_handler import APIGatewayRestResolver + + tracer = Tracer() + app = APIGatewayRestResolver() + + @app.get("/get-call") + def simple_get(): + return {"message": "Foo"} + + @tracer.capture_lambda_handler + def lambda_handler(event, context): + return app.resolve(event, context) + ``` + """ + return self.route( + rule, + "GET", + cors, + compress, + cache_control, + summary, + description, + responses, + response_description, + tags, + operation_id, + include_in_schema, + security, + openapi_extensions, + middlewares, + ) + + def post( + self, + rule: str, + cors: bool | None = None, + compress: bool = False, + cache_control: str | None = None, + summary: str | None = None, + description: str | None = None, + responses: dict[int, OpenAPIResponse] | None = None, + response_description: str = _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION, + tags: list[str] | None = None, + operation_id: str | None = None, + include_in_schema: bool = True, + security: list[dict[str, list[str]]] | None = None, + openapi_extensions: dict[str, Any] | None = None, + middlewares: list[Callable[..., Any]] | None = None, + ): + """Post route decorator with POST `method` + + Examples + -------- + Simple example with a custom lambda handler using the Tracer capture_lambda_handler decorator + + ```python + from aws_lambda_powertools import Tracer + from aws_lambda_powertools.event_handler import APIGatewayRestResolver + + tracer = Tracer() + app = APIGatewayRestResolver() + + @app.post("/post-call") + def simple_post(): + post_data: dict = app.current_event.json_body + return {"message": post_data["value"]} + + @tracer.capture_lambda_handler + def lambda_handler(event, context): + return app.resolve(event, context) + ``` + """ + return self.route( + rule, + "POST", + cors, + compress, + cache_control, + summary, + description, + responses, + response_description, + tags, + operation_id, + include_in_schema, + security, + openapi_extensions, + middlewares, + ) + + def put( + self, + rule: str, + cors: bool | None = None, + compress: bool = False, + cache_control: str | None = None, + summary: str | None = None, + description: str | None = None, + responses: dict[int, OpenAPIResponse] | None = None, + response_description: str = _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION, + tags: list[str] | None = None, + operation_id: str | None = None, + include_in_schema: bool = True, + security: list[dict[str, list[str]]] | None = None, + openapi_extensions: dict[str, Any] | None = None, + middlewares: list[Callable[..., Any]] | None = None, + ): + """Put route decorator with PUT `method` + + Examples + -------- + Simple example with a custom lambda handler using the Tracer capture_lambda_handler decorator + + ```python + from aws_lambda_powertools import Tracer + from aws_lambda_powertools.event_handler import APIGatewayRestResolver + + tracer = Tracer() + app = APIGatewayRestResolver() + + @app.put("/put-call") + def simple_put(): + put_data: dict = app.current_event.json_body + return {"message": put_data["value"]} + + @tracer.capture_lambda_handler + def lambda_handler(event, context): + return app.resolve(event, context) + ``` + """ + return self.route( + rule, + "PUT", + cors, + compress, + cache_control, + summary, + description, + responses, + response_description, + tags, + operation_id, + include_in_schema, + security, + openapi_extensions, + middlewares, + ) + + def delete( + self, + rule: str, + cors: bool | None = None, + compress: bool = False, + cache_control: str | None = None, + summary: str | None = None, + description: str | None = None, + responses: dict[int, OpenAPIResponse] | None = None, + response_description: str = _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION, + tags: list[str] | None = None, + operation_id: str | None = None, + include_in_schema: bool = True, + security: list[dict[str, list[str]]] | None = None, + openapi_extensions: dict[str, Any] | None = None, + middlewares: list[Callable[..., Any]] | None = None, + ): + """Delete route decorator with DELETE `method` + + Examples + -------- + Simple example with a custom lambda handler using the Tracer capture_lambda_handler decorator + + ```python + from aws_lambda_powertools import Tracer + from aws_lambda_powertools.event_handler import APIGatewayRestResolver + + tracer = Tracer() + app = APIGatewayRestResolver() + + @app.delete("/delete-call") + def simple_delete(): + return {"message": "deleted"} + + @tracer.capture_lambda_handler + def lambda_handler(event, context): + return app.resolve(event, context) + ``` + """ + return self.route( + rule, + "DELETE", + cors, + compress, + cache_control, + summary, + description, + responses, + response_description, + tags, + operation_id, + include_in_schema, + security, + openapi_extensions, + middlewares, + ) + + def patch( + self, + rule: str, + cors: bool | None = None, + compress: bool = False, + cache_control: str | None = None, + summary: str | None = None, + description: str | None = None, + responses: dict[int, OpenAPIResponse] | None = None, + response_description: str = _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION, + tags: list[str] | None = None, + operation_id: str | None = None, + include_in_schema: bool = True, + security: list[dict[str, list[str]]] | None = None, + openapi_extensions: dict[str, Any] | None = None, + middlewares: list[Callable] | None = None, + ): + """Patch route decorator with PATCH `method` + + Examples + -------- + Simple example with a custom lambda handler using the Tracer capture_lambda_handler decorator + + ```python + from aws_lambda_powertools import Tracer + from aws_lambda_powertools.event_handler import APIGatewayRestResolver + + tracer = Tracer() + app = APIGatewayRestResolver() + + @app.patch("/patch-call") + def simple_patch(): + patch_data: dict = app.current_event.json_body + patch_data["value"] = patched + + return {"message": patch_data} + + @tracer.capture_lambda_handler + def lambda_handler(event, context): + return app.resolve(event, context) + ``` + """ + return self.route( + rule, + "PATCH", + cors, + compress, + cache_control, + summary, + description, + responses, + response_description, + tags, + operation_id, + include_in_schema, + security, + openapi_extensions, + middlewares, + ) + + def head( + self, + rule: str, + cors: bool | None = None, + compress: bool = False, + cache_control: str | None = None, + summary: str | None = None, + description: str | None = None, + responses: dict[int, OpenAPIResponse] | None = None, + response_description: str = _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION, + tags: list[str] | None = None, + operation_id: str | None = None, + include_in_schema: bool = True, + security: list[dict[str, list[str]]] | None = None, + openapi_extensions: dict[str, Any] | None = None, + middlewares: list[Callable] | None = None, + ): + """Head route decorator with HEAD `method` + + Examples + -------- + Simple example with a custom lambda handler using the Tracer capture_lambda_handler decorator + + ```python + from aws_lambda_powertools import Tracer + from aws_lambda_powertools.event_handler import APIGatewayRestResolver, Response, content_types + + tracer = Tracer() + app = APIGatewayRestResolver() + + @app.head("/head-call") + def simple_head(): + return Response(status_code=200, + content_type=content_types.APPLICATION_JSON, + headers={"Content-Length": "123"}) + + @tracer.capture_lambda_handler + def lambda_handler(event, context): + return app.resolve(event, context) + ``` + """ + return self.route( + rule, + "HEAD", + cors, + compress, + cache_control, + summary, + description, + responses, + response_description, + tags, + operation_id, + include_in_schema, + security, + openapi_extensions, + middlewares, + ) + + def _push_processed_stack_frame(self, frame: str): + """ + Add Current Middleware to the Middleware Stack Frames + The stack frames will be used when exceptions are thrown and Powertools + debug is enabled by developers. + """ + self.processed_stack_frames.append(frame) + + def _reset_processed_stack(self): + """Reset the Processed Stack Frames""" + self.processed_stack_frames.clear() + + def append_context(self, **additional_context): + """Append key=value data as routing context""" + self.context.update(**additional_context) + + def clear_context(self): + """Resets routing context""" + self.context.clear() + + +class MiddlewareFrame: + """ + Creates a Middle Stack Wrapper instance to be used as a "Frame" in the overall stack of + middleware functions. Each instance contains the current middleware and the next + middleware function to be called in the stack. + + In this way the middleware stack is constructed in a recursive fashion, with each middleware + calling the next as a simple function call. The actual Python call-stack will contain + each MiddlewareStackWrapper "Frame", meaning any Middleware function can cause the + entire Middleware call chain to be exited early (short-circuited) by raising an exception + or by simply returning early with a custom Response. The decision to short-circuit the middleware + chain is at the user's discretion but instantly available due to the Wrapped nature of the + callable constructs in the Middleware stack and each Middleware function having complete control over + whether the "Next" handler in the stack is called or not. + + Parameters + ---------- + current_middleware : Callable + The current middleware function to be called as a request is processed. + next_middleware : Callable + The next middleware in the middleware stack. + """ + + def __init__( + self, + current_middleware: Callable[..., Any], + next_middleware: Callable[..., Any], + ) -> None: + self.current_middleware: Callable[..., Any] = current_middleware + self.next_middleware: Callable[..., Any] = next_middleware + self._next_middleware_name = next_middleware.__name__ + + @property + def __name__(self) -> str: # noqa: A003 + """Current middleware name + + It ensures backward compatibility with view functions being callable. This + improves debugging since we need both current and next middlewares/callable names. + """ + return self.current_middleware.__name__ + + def __str__(self) -> str: + """Identify current middleware identity and call chain for debugging purposes.""" + middleware_name = self.__name__ + return f"[{middleware_name}] next call chain is {middleware_name} -> {self._next_middleware_name}" + + def __call__(self, app: ApiGatewayResolver) -> dict | tuple | Response: + """ + Call the middleware Frame to process the request. + + Parameters + ---------- + app: BaseRouter + The router instance + + Returns + ------- + dict | tuple | Response + (tech-debt for backward compatibility). The response type should be a + Response object in all cases excepting when the original API route handler + is called which will return one of 3 outputs. + + """ + # Do debug printing and push processed stack frame AFTER calling middleware + # else the stack frame text of `current calling next` is confusing. + logger.debug("MiddlewareFrame: %s", self) + app._push_processed_stack_frame(str(self)) + + return self.current_middleware(app, self.next_middleware) + + +def _registered_api_adapter(app: ApiGatewayResolver, next_middleware: Callable[..., Any]) -> dict | tuple | Response: + """ + Calls the registered API using the "_route_args" from the Resolver context to ensure the last call + in the chain will match the API route function signature and ensure that Powertools passes the API + route handler the expected arguments. + + **IMPORTANT: This internal middleware ensures the actual API route is called with the correct call signature + and it MUST be the final frame in the middleware stack. This can only be removed when the API Route + function accepts `app: BaseRouter` as the first argument - which is the breaking change. + + Parameters + ---------- + app: ApiGatewayResolver + The API Gateway resolver + next_middleware: Callable[..., Any] + The function to handle the API + + Returns + ------- + Response + The API Response Object + + """ + route_args: dict = app.context.get("_route_args", {}) + logger.debug(f"Calling API Route Handler: {route_args}") + return app._to_response(next_middleware(**route_args)) + + +class ApiGatewayResolver(BaseRouter): + """API Gateway and ALB proxy resolver + + Examples + -------- + Simple example with a custom lambda handler using the Tracer capture_lambda_handler decorator + + ```python + from aws_lambda_powertools import Tracer + from aws_lambda_powertools.event_handler import APIGatewayRestResolver + + tracer = Tracer() + app = APIGatewayRestResolver() + + @app.get("/get-call") + def simple_get(): + return {"message": "Foo"} + + @app.post("/post-call") + def simple_post(): + post_data: dict = app.current_event.json_body + return {"message": post_data["value"]} + + @tracer.capture_lambda_handler + def lambda_handler(event, context): + return app.resolve(event, context) + ``` + """ + + def __init__( + self, + proxy_type: Enum = ProxyEventType.APIGatewayProxyEvent, + cors: CORSConfig | None = None, + debug: bool | None = None, + serializer: Callable[[dict], str] | None = None, + strip_prefixes: list[str | Pattern] | None = None, + enable_validation: bool = False, + ): + """ + Parameters + ---------- + proxy_type: ProxyEventType + Proxy request type, defaults to API Gateway V1 + cors: CORSConfig + Optionally configure and enabled CORS. Not each route will need to have to cors=True + debug: bool | None + Enables debug mode, by default False. Can be also be enabled by "POWERTOOLS_DEV" + environment variable + serializer: Callable, optional + function to serialize `obj` to a JSON formatted `str`, by default json.dumps + strip_prefixes: list[str | Pattern], optional + optional list of prefixes to be removed from the request path before doing the routing. + This is often used with api gateways with multiple custom mappings. + Each prefix can be a static string or a compiled regex pattern + enable_validation: bool | None + Enables validation of the request body against the route schema, by default False. + """ + self._proxy_type = proxy_type + self._dynamic_routes: list[Route] = [] + self._static_routes: list[Route] = [] + self._route_keys: list[str] = [] + self._exception_handlers: dict[type, Callable] = {} + self._cors = cors + self._cors_enabled: bool = cors is not None + self._cors_methods: set[str] = {"OPTIONS"} + self._debug = self._has_debug(debug) + self._enable_validation = enable_validation + self._strip_prefixes = strip_prefixes + self.context: dict = {} # early init as customers might add context before event resolution + self.processed_stack_frames = [] + self._response_builder_class = ResponseBuilder[BaseProxyEvent] + + # Allow for a custom serializer or a concise json serialization + self._serializer = serializer or partial(json.dumps, separators=(",", ":"), cls=Encoder) + + if self._enable_validation: + from aws_lambda_powertools.event_handler.middlewares.openapi_validation import OpenAPIValidationMiddleware + + # Note the serializer argument: only use custom serializer if provided by the caller + # Otherwise, fully rely on the internal Pydantic based mechanism to serialize responses for validation. + self.use([OpenAPIValidationMiddleware(validation_serializer=serializer)]) + + def get_openapi_schema( + self, + *, + title: str = "Powertools API", + version: str = DEFAULT_API_VERSION, + openapi_version: str = DEFAULT_OPENAPI_VERSION, + summary: str | None = None, + description: str | None = None, + tags: list[Tag | str] | None = None, + servers: list[Server] | None = None, + terms_of_service: str | None = None, + contact: Contact | None = None, + license_info: License | None = None, + security_schemes: dict[str, SecurityScheme] | None = None, + security: list[dict[str, list[str]]] | None = None, + openapi_extensions: dict[str, Any] | None = None, + ) -> OpenAPI: + """ + Returns the OpenAPI schema as a pydantic model. + + Parameters + ---------- + title: str + The title of the application. + version: str + The version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API + openapi_version: str, default = "3.0.0" + The version of the OpenAPI Specification (which the document uses). + summary: str, optional + A short summary of what the application does. + description: str, optional + A verbose explanation of the application behavior. + tags: list[Tag | str], optional + A list of tags used by the specification with additional metadata. + servers: list[Server], optional + An array of Server Objects, which provide connectivity information to a target server. + terms_of_service: str, optional + A URL to the Terms of Service for the API. MUST be in the format of a URL. + contact: Contact, optional + The contact information for the exposed API. + license_info: License, optional + The license information for the exposed API. + security_schemes: dict[str, SecurityScheme]], optional + A declaration of the security schemes available to be used in the specification. + security: list[dict[str, list[str]]], optional + A declaration of which security mechanisms are applied globally across the API. + openapi_extensions: Dict[str, Any], optional + Additional OpenAPI extensions as a dictionary. + + Returns + ------- + OpenAPI: pydantic model + The OpenAPI schema as a pydantic model. + """ + + from aws_lambda_powertools.event_handler.openapi.compat import ( + GenerateJsonSchema, + get_compat_model_name_map, + get_definitions, + ) + from aws_lambda_powertools.event_handler.openapi.models import OpenAPI, PathItem, Tag + from aws_lambda_powertools.event_handler.openapi.types import ( + COMPONENT_REF_TEMPLATE, + ) + + openapi_version = self._determine_openapi_version(openapi_version) + + # Start with the bare minimum required for a valid OpenAPI schema + info: dict[str, Any] = {"title": title, "version": version} + + optional_fields = { + "summary": summary, + "description": description, + "termsOfService": terms_of_service, + "contact": contact, + "license": license_info, + } + + info.update({field: value for field, value in optional_fields.items() if value}) + + if not isinstance(openapi_extensions, dict): + openapi_extensions = {} + + output: dict[str, Any] = { + "openapi": openapi_version, + "info": info, + "servers": self._get_openapi_servers(servers), + "security": self._get_openapi_security(security, security_schemes), + **openapi_extensions, + } + + components: dict[str, dict[str, Any]] = {} + paths: dict[str, dict[str, Any]] = {} + operation_ids: set[str] = set() + + all_routes = self._dynamic_routes + self._static_routes + all_fields = self._get_fields_from_routes(all_routes) + model_name_map = get_compat_model_name_map(all_fields) + + # Collect all models and definitions + schema_generator = GenerateJsonSchema(ref_template=COMPONENT_REF_TEMPLATE) + field_mapping, definitions = get_definitions( + fields=all_fields, + schema_generator=schema_generator, + model_name_map=model_name_map, + ) + + # Add routes to the OpenAPI schema + for route in all_routes: + + if route.security and not _validate_openapi_security_parameters( + security=route.security, + security_schemes=security_schemes, + ): + raise SchemaValidationError( + "Security configuration was not found in security_schemas or security_schema was not defined. " + "See: https://docs.powertools.aws.dev/lambda/python/latest/core/event_handler/api_gateway/#security-schemes", + ) + + if not route.include_in_schema: + continue + + result = route._get_openapi_path( + dependant=route.dependant, + operation_ids=operation_ids, + model_name_map=model_name_map, + field_mapping=field_mapping, + ) + if result: + path, path_definitions = result + if path: + paths.setdefault(route.openapi_path, {}).update(path) + if path_definitions: + definitions.update(path_definitions) + + if definitions: + components["schemas"] = {k: definitions[k] for k in sorted(definitions)} + if security_schemes: + components["securitySchemes"] = security_schemes + if components: + output["components"] = components + if tags: + output["tags"] = [Tag(name=tag) if isinstance(tag, str) else tag for tag in tags] + + output["paths"] = {k: PathItem(**v) for k, v in paths.items()} + + return OpenAPI(**output) + + @staticmethod + def _get_openapi_servers(servers: list[Server] | None) -> list[Server]: + from aws_lambda_powertools.event_handler.openapi.models import Server + + # If the 'servers' property is not provided or is an empty array, + # the default behavior is to return a Server Object with a URL value of "/". + return servers if servers else [Server(url="/")] + + @staticmethod + def _get_openapi_security( + security: list[dict[str, list[str]]] | None, + security_schemes: dict[str, SecurityScheme] | None, + ) -> list[dict[str, list[str]]] | None: + if not security: + return None + + if not _validate_openapi_security_parameters(security=security, security_schemes=security_schemes): + raise SchemaValidationError( + "Security configuration was not found in security_schemas or security_schema was not defined. " + "See: https://docs.powertools.aws.dev/lambda/python/latest/core/event_handler/api_gateway/#security-schemes", + ) + + return security + + @staticmethod + def _determine_openapi_version(openapi_version: str): + + # Pydantic V2 has no support for OpenAPI schema 3.0 + if not openapi_version.startswith("3.1"): + warnings.warn( + "You are using Pydantic v2, which is incompatible with OpenAPI schema 3.0. Forcing OpenAPI 3.1", + stacklevel=2, + ) + openapi_version = "3.1.0" + return openapi_version + + def get_openapi_json_schema( + self, + *, + title: str = "Powertools API", + version: str = DEFAULT_API_VERSION, + openapi_version: str = DEFAULT_OPENAPI_VERSION, + summary: str | None = None, + description: str | None = None, + tags: list[Tag | str] | None = None, + servers: list[Server] | None = None, + terms_of_service: str | None = None, + contact: Contact | None = None, + license_info: License | None = None, + security_schemes: dict[str, SecurityScheme] | None = None, + security: list[dict[str, list[str]]] | None = None, + openapi_extensions: dict[str, Any] | None = None, + ) -> str: + """ + Returns the OpenAPI schema as a JSON serializable dict + + Parameters + ---------- + title: str + The title of the application. + version: str + The version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API + openapi_version: str, default = "3.0.0" + The version of the OpenAPI Specification (which the document uses). + summary: str, optional + A short summary of what the application does. + description: str, optional + A verbose explanation of the application behavior. + tags: list[Tag, str], optional + A list of tags used by the specification with additional metadata. + servers: list[Server], optional + An array of Server Objects, which provide connectivity information to a target server. + terms_of_service: str, optional + A URL to the Terms of Service for the API. MUST be in the format of a URL. + contact: Contact, optional + The contact information for the exposed API. + license_info: License, optional + The license information for the exposed API. + security_schemes: dict[str, SecurityScheme]], optional + A declaration of the security schemes available to be used in the specification. + security: list[dict[str, list[str]]], optional + A declaration of which security mechanisms are applied globally across the API. + openapi_extensions: Dict[str, Any], optional + Additional OpenAPI extensions as a dictionary. + + Returns + ------- + str + The OpenAPI schema as a JSON serializable dict. + """ + from aws_lambda_powertools.event_handler.openapi.compat import model_json + + return model_json( + self.get_openapi_schema( + title=title, + version=version, + openapi_version=openapi_version, + summary=summary, + description=description, + tags=tags, + servers=servers, + terms_of_service=terms_of_service, + contact=contact, + license_info=license_info, + security_schemes=security_schemes, + security=security, + openapi_extensions=openapi_extensions, + ), + by_alias=True, + exclude_none=True, + indent=2, + ) + + def enable_swagger( + self, + *, + path: str = "/swagger", + title: str = "Powertools for AWS Lambda (Python) API", + version: str = DEFAULT_API_VERSION, + openapi_version: str = DEFAULT_OPENAPI_VERSION, + summary: str | None = None, + description: str | None = None, + tags: list[Tag | str] | None = None, + servers: list[Server] | None = None, + terms_of_service: str | None = None, + contact: Contact | None = None, + license_info: License | None = None, + swagger_base_url: str | None = None, + middlewares: list[Callable[..., Response]] | None = None, + compress: bool = False, + security_schemes: dict[str, SecurityScheme] | None = None, + security: list[dict[str, list[str]]] | None = None, + oauth2_config: OAuth2Config | None = None, + persist_authorization: bool = False, + openapi_extensions: dict[str, Any] | None = None, + ): + """ + Returns the OpenAPI schema as a JSON serializable dict + + Parameters + ---------- + path: str, default = "/swagger" + The path to the swagger UI. + title: str + The title of the application. + version: str + The version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API + openapi_version: str, default = "3.0.0" + The version of the OpenAPI Specification (which the document uses). + summary: str, optional + A short summary of what the application does. + description: str, optional + A verbose explanation of the application behavior. + tags: list[Tag, str], optional + A list of tags used by the specification with additional metadata. + servers: list[Server], optional + An array of Server Objects, which provide connectivity information to a target server. + terms_of_service: str, optional + A URL to the Terms of Service for the API. MUST be in the format of a URL. + contact: Contact, optional + The contact information for the exposed API. + license_info: License, optional + The license information for the exposed API. + swagger_base_url: str, optional + The base url for the swagger UI. If not provided, we will serve a recent version of the Swagger UI. + middlewares: list[Callable[..., Response]], optional + List of middlewares to be used for the swagger route. + compress: bool, default = False + Whether or not to enable gzip compression swagger route. + security_schemes: dict[str, "SecurityScheme"], optional + A declaration of the security schemes available to be used in the specification. + security: list[dict[str, list[str]]], optional + A declaration of which security mechanisms are applied globally across the API. + oauth2_config: OAuth2Config, optional + The OAuth2 configuration for the Swagger UI. + persist_authorization: bool, optional + Whether to persist authorization data on browser close/refresh. + openapi_extensions: dict[str, Any], optional + Additional OpenAPI extensions as a dictionary. + """ + from aws_lambda_powertools.event_handler.openapi.compat import model_json + from aws_lambda_powertools.event_handler.openapi.models import Server + from aws_lambda_powertools.event_handler.openapi.swagger_ui import ( + generate_oauth2_redirect_html, + generate_swagger_html, + ) + + @self.get(path, middlewares=middlewares, include_in_schema=False, compress=compress) + def swagger_handler(): + query_params = self.current_event.query_string_parameters or {} + + # Check for query parameters; if "format" is specified as "oauth2-redirect", + # send the oauth2-redirect HTML stanza so OAuth2 can be used + # Source: https://github.com/swagger-api/swagger-ui/blob/master/dist/oauth2-redirect.html + if query_params.get("format") == "oauth2-redirect": + return Response( + status_code=200, + content_type="text/html", + body=generate_oauth2_redirect_html(), + ) + + base_path = self._get_base_path() + + if swagger_base_url: + swagger_js = f"{swagger_base_url}/swagger-ui-bundle.min.js" + swagger_css = f"{swagger_base_url}/swagger-ui.min.css" + else: + # We now inject CSS and JS into the SwaggerUI file + swagger_js = Path.open( + Path(__file__).parent / "openapi" / "swagger_ui" / "swagger-ui-bundle.min.js", + ).read() + swagger_css = Path.open(Path(__file__).parent / "openapi" / "swagger_ui" / "swagger-ui.min.css").read() + + openapi_servers = servers or [Server(url=(base_path or "/"))] + + spec = self.get_openapi_schema( + title=title, + version=version, + openapi_version=openapi_version, + summary=summary, + description=description, + tags=tags, + servers=openapi_servers, + terms_of_service=terms_of_service, + contact=contact, + license_info=license_info, + security_schemes=security_schemes, + security=security, + openapi_extensions=openapi_extensions, + ) + + # The .replace('</', '<\\/') part is necessary to prevent a potential issue where the JSON string contains + # </script> or similar tags. Escaping the forward slash in </ as <\/ ensures that the JSON does not + # inadvertently close the script tag, and the JSON remains a valid string within the JavaScript code. + escaped_spec = model_json( + spec, + by_alias=True, + exclude_none=True, + indent=2, + ).replace("</", "<\\/") + + # Check for query parameters; if "format" is specified as "json", + # respond with the JSON used in the OpenAPI spec + # Example: https://www.example.com/swagger?format=json + if query_params.get("format") == "json": + return Response( + status_code=200, + content_type="application/json", + body=escaped_spec, + ) + + body = generate_swagger_html( + escaped_spec, + swagger_js, + swagger_css, + swagger_base_url, + oauth2_config, + persist_authorization, + ) + + return Response( + status_code=200, + content_type="text/html", + body=body, + ) + + def route( + self, + rule: str, + method: str | list[str] | tuple[str], + cors: bool | None = None, + compress: bool = False, + cache_control: str | None = None, + summary: str | None = None, + description: str | None = None, + responses: dict[int, OpenAPIResponse] | None = None, + response_description: str = _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION, + tags: list[str] | None = None, + operation_id: str | None = None, + include_in_schema: bool = True, + security: list[dict[str, list[str]]] | None = None, + openapi_extensions: dict[str, Any] | None = None, + middlewares: list[Callable[..., Any]] | None = None, + ): + """Route decorator includes parameter `method`""" + + def register_resolver(func: Callable): + methods = (method,) if isinstance(method, str) else method + logger.debug(f"Adding route using rule {rule} and methods: {','.join(m.upper() for m in methods)}") + + cors_enabled = self._cors_enabled if cors is None else cors + + for item in methods: + _route = Route( + item, + rule, + self._compile_regex(rule), + func, + cors_enabled, + compress, + cache_control, + summary, + description, + responses, + response_description, + tags, + operation_id, + include_in_schema, + security, + openapi_extensions, + middlewares, + ) + + # The more specific route wins. + # We store dynamic (/studies/{studyid}) and static routes (/studies/fetch) separately. + # Then attempt a match for static routes before dynamic routes. + # This ensures that the most specific route is prioritized and processed first (studies/fetch). + if _route.rule.groups > 0: + self._dynamic_routes.append(_route) + else: + self._static_routes.append(_route) + + self._create_route_key(item, rule) + + if cors_enabled: + logger.debug(f"Registering method {item.upper()} to Allow Methods in CORS") + self._cors_methods.add(item.upper()) + + return func + + return register_resolver + + def resolve(self, event, context) -> dict[str, Any]: + """Resolves the response based on the provide event and decorator routes + + ## Internals + + Request processing chain is triggered by a Route object being called _(`_call_route` -> `__call__`)_: + + 1. **When a route is matched** + 1.1. Exception handlers _(if any exception bubbled up and caught)_ + 1.2. Global middlewares _(before, and after on the way back)_ + 1.3. Path level middleware _(before, and after on the way back)_ + 1.4. Middleware adapter to ensure Response is homogenous (_registered_api_adapter) + 1.5. Run actual route + 2. **When a route is NOT matched** + 2.1. Exception handlers _(if any exception bubbled up and caught)_ + 2.2. Global middlewares _(before, and after on the way back)_ + 2.3. Path level middleware _(before, and after on the way back)_ + 2.4. Middleware adapter to ensure Response is homogenous (_registered_api_adapter) + 2.5. Run 404 route handler + 3. **When a route is a pre-flight CORS (often not matched)** + 3.1. Exception handlers _(if any exception bubbled up and caught)_ + 3.2. Global middlewares _(before, and after on the way back)_ + 3.3. Path level middleware _(before, and after on the way back)_ + 3.4. Middleware adapter to ensure Response is homogenous (_registered_api_adapter) + 3.5. Return 204 with appropriate CORS headers + 4. **When a route is matched with Data Validation enabled** + 4.1. Exception handlers _(if any exception bubbled up and caught)_ + 4.2. Data Validation middleware _(before, and after on the way back)_ + 4.3. Global middlewares _(before, and after on the way back)_ + 4.4. Path level middleware _(before, and after on the way back)_ + 4.5. Middleware adapter to ensure Response is homogenous (_registered_api_adapter) + 4.6. Run actual route + + Parameters + ---------- + event: dict[str, Any] + Event + context: LambdaContext + Lambda context + Returns + ------- + dict + Returns the dict response + """ + if isinstance(event, BaseProxyEvent): + warnings.warn( + "You don't need to serialize event to Event Source Data Class when using Event Handler; " + "see issue #1152", + stacklevel=2, + ) + event = event.raw_event + + if self._debug: + print(self._serializer(event)) + + # Populate router(s) dependencies without keeping a reference to each registered router + BaseRouter.current_event = self._to_proxy_event(event) + BaseRouter.lambda_context = context + + response = self._resolve().build(self.current_event, self._cors) + + # Debug print Processed Middlewares + if self._debug: + print("\nProcessed Middlewares:") + print("======================") + print("\n".join(self.processed_stack_frames)) + print("======================") + + self.clear_context() + + return response + + def __call__(self, event, context) -> Any: + return self.resolve(event, context) + + def _create_route_key(self, item: str, rule: str): + route_key = item + rule + if route_key in self._route_keys: + warnings.warn( + f"A route like this was already registered. method: '{item}' rule: '{rule}'", + stacklevel=2, + ) + self._route_keys.append(route_key) + + def _get_base_path(self) -> str: + raise NotImplementedError() + + @staticmethod + def _has_debug(debug: bool | None = None) -> bool: + # It might have been explicitly switched off (debug=False) + if debug is not None: + return debug + + return powertools_dev_is_set() + + @staticmethod + def _compile_regex(rule: str, base_regex: str = _ROUTE_REGEX): + """Precompile regex pattern + + Logic + ----- + + 1. Find any dynamic routes defined as <pattern> + e.g. @app.get("/accounts/<account_id>") + 2. Create a new regex by substituting every dynamic route found as a named group (?P<group>), + and match whole words only (word boundary) instead of a greedy match + + non-greedy example with word boundary + + rule: '/accounts/<account_id>' + regex: r'/accounts/(?P<account_id>\\w+\\b)' + + value: /accounts/123/some_other_path + account_id: 123 + + greedy example without word boundary + + regex: r'/accounts/(?P<account_id>.+)' + + value: /accounts/123/some_other_path + account_id: 123/some_other_path + 3. Compiles a regex and include start (^) and end ($) in between for an exact match + + NOTE: See #520 for context + """ + rule_regex: str = re.sub(_DYNAMIC_ROUTE_PATTERN, _NAMED_GROUP_BOUNDARY_PATTERN, rule) + return re.compile(base_regex.format(rule_regex)) + + def _to_proxy_event(self, event: dict) -> BaseProxyEvent: # noqa: PLR0911 # ignore many returns + """Convert the event dict to the corresponding data class""" + if self._proxy_type == ProxyEventType.APIGatewayProxyEvent: + logger.debug("Converting event to API Gateway REST API contract") + return APIGatewayProxyEvent(event) + if self._proxy_type == ProxyEventType.APIGatewayProxyEventV2: + logger.debug("Converting event to API Gateway HTTP API contract") + return APIGatewayProxyEventV2(event) + if self._proxy_type == ProxyEventType.BedrockAgentEvent: + logger.debug("Converting event to Bedrock Agent contract") + return BedrockAgentEvent(event) + if self._proxy_type == ProxyEventType.LambdaFunctionUrlEvent: + logger.debug("Converting event to Lambda Function URL contract") + return LambdaFunctionUrlEvent(event) + if self._proxy_type == ProxyEventType.VPCLatticeEvent: + logger.debug("Converting event to VPC Lattice contract") + return VPCLatticeEvent(event) + if self._proxy_type == ProxyEventType.VPCLatticeEventV2: + logger.debug("Converting event to VPC LatticeV2 contract") + return VPCLatticeEventV2(event) + logger.debug("Converting event to ALB contract") + return ALBEvent(event) + + def _resolve(self) -> ResponseBuilder: + """Resolves the response or return the not found response""" + method = self.current_event.http_method.upper() + path = self._remove_prefix(self.current_event.path) + + registered_routes = self._static_routes + self._dynamic_routes + + for route in registered_routes: + if method != route.method: + continue + match_results: Match | None = route.rule.match(path) + if match_results: + logger.debug("Found a registered route. Calling function") + # Add matched Route reference into the Resolver context + self.append_context(_route=route, _path=path) + + route_keys = self._convert_matches_into_route_keys(match_results) + return self._call_route(route, route_keys) # pass fn args + + return self._handle_not_found(method=method, path=path) + + def _remove_prefix(self, path: str) -> str: + """Remove the configured prefix from the path""" + if not isinstance(self._strip_prefixes, list): + return path + + for prefix in self._strip_prefixes: + if isinstance(prefix, str): + if path == prefix: + return "/" + + if self._path_starts_with(path, prefix): + return path[len(prefix) :] + + if isinstance(prefix, Pattern): + path = re.sub(prefix, "", path) + + # When using regexes, we might get into a point where everything is removed + # from the string, so we check if it's empty and return /, since there's nothing + # else to strip anymore. + if not path: + return "/" + + return path + + def _convert_matches_into_route_keys(self, match: Match) -> dict[str, str]: + """Converts the regex match into a dict of route keys""" + return match.groupdict() + + @staticmethod + def _path_starts_with(path: str, prefix: str): + """Returns true if the `path` starts with a prefix plus a `/`""" + if not isinstance(prefix, str) or prefix == "": + return False + + return path.startswith(prefix + "/") + + def _handle_not_found(self, method: str, path: str) -> ResponseBuilder: + """Called when no matching route was found and includes support for the cors preflight response""" + logger.debug(f"No match found for path {path} and method {method}") + + def not_found_handler(): + """Route handler for 404s + + It handles in the following order: + + 1. Pre-flight CORS requests (OPTIONS) + 2. Detects and calls custom HTTP 404 handler + 3. Returns standard 404 along with CORS headers + + Returns + ------- + Response + HTTP 404 response + """ + _headers: dict[str, Any] = {} + + # Pre-flight request? Return immediately to avoid browser error + if self._cors and method == "OPTIONS": + logger.debug("Pre-flight request detected. Returning CORS with empty response") + _headers["Access-Control-Allow-Methods"] = CORSConfig.build_allow_methods(self._cors_methods) + + return Response(status_code=204, content_type=None, headers=_headers, body="") + + # Customer registered 404 route? Call it. + custom_not_found_handler = self._lookup_exception_handler(NotFoundError) + if custom_not_found_handler: + return custom_not_found_handler(NotFoundError()) + + # No CORS and no custom 404 fn? Default response + return Response( + status_code=HTTPStatus.NOT_FOUND.value, + content_type=content_types.APPLICATION_JSON, + headers=_headers, + body={"statusCode": HTTPStatus.NOT_FOUND.value, "message": "Not found"}, + ) + + # We create a route to trigger entire request chain (middleware+exception handlers) + route = Route( + rule=self._compile_regex(r".*"), + method=method, + path=path, + func=not_found_handler, + cors=self._cors_enabled, + compress=False, + ) + + # Add matched Route reference into the Resolver context + self.append_context(_route=route, _path=path) + + # Kick-off request chain: + # -> exception_handlers() + # --> middlewares() + # ---> not_found_route() + return self._call_route(route=route, route_arguments={}) + + def _call_route(self, route: Route, route_arguments: dict[str, str]) -> ResponseBuilder: + """Actually call the matching route with any provided keyword arguments.""" + try: + # Reset Processed stack for Middleware (for debugging purposes) + self._reset_processed_stack() + + return self._response_builder_class( + response=self._to_response( + route(router_middlewares=self._router_middlewares, app=self, route_arguments=route_arguments), + ), + serializer=self._serializer, + route=route, + ) + except Exception as exc: + # If exception is handled then return the response builder to reduce noise + response_builder = self._call_exception_handler(exc, route) + if response_builder: + return response_builder + + logger.exception(exc) + if self._debug: + # If the user has turned on debug mode, + # we'll let the original exception propagate, so + # they get more information about what went wrong. + return self._response_builder_class( + response=Response( + status_code=500, + content_type=content_types.TEXT_PLAIN, + body="".join(traceback.format_exc()), + ), + serializer=self._serializer, + route=route, + ) + + raise + + def not_found(self, func: Callable | None = None): + if func is None: + return self.exception_handler(NotFoundError) + return self.exception_handler(NotFoundError)(func) + + def exception_handler(self, exc_class: type[Exception] | list[type[Exception]]): + def register_exception_handler(func: Callable): + if isinstance(exc_class, list): # pragma: no cover + for exp in exc_class: + self._exception_handlers[exp] = func + else: + self._exception_handlers[exc_class] = func + return func + + return register_exception_handler + + def _lookup_exception_handler(self, exp_type: type) -> Callable | None: + # Use "Method Resolution Order" to allow for matching against a base class + # of an exception + for cls in exp_type.__mro__: + if cls in self._exception_handlers: + return self._exception_handlers[cls] + return None + + def _call_exception_handler(self, exp: Exception, route: Route) -> ResponseBuilder | None: + handler = self._lookup_exception_handler(type(exp)) + if handler: + try: + return self._response_builder_class(response=handler(exp), serializer=self._serializer, route=route) + except ServiceError as service_error: + exp = service_error + + if isinstance(exp, RequestValidationError): + # For security reasons, we hide msg details (don't leak Python, Pydantic or file names) + errors = [{"loc": e["loc"], "type": e["type"]} for e in exp.errors()] + + return self._response_builder_class( + response=Response( + status_code=HTTPStatus.UNPROCESSABLE_ENTITY, + content_type=content_types.APPLICATION_JSON, + body={"statusCode": HTTPStatus.UNPROCESSABLE_ENTITY, "detail": errors}, + ), + serializer=self._serializer, + route=route, + ) + + if isinstance(exp, ServiceError): + return self._response_builder_class( + response=Response( + status_code=exp.status_code, + content_type=content_types.APPLICATION_JSON, + body={"statusCode": exp.status_code, "message": exp.msg}, + ), + serializer=self._serializer, + route=route, + ) + + return None + + def _to_response(self, result: dict | tuple | Response) -> Response: + """Convert the route's result to a Response + + 3 main result types are supported: + + - dict[str, Any]: Rest api response with just the dict to json stringify and content-type is set to + application/json + - tuple[dict, int]: Same dict handling as above but with the option of including a status code + - Response: returned as is, and allows for more flexibility + """ + status_code = HTTPStatus.OK + if isinstance(result, Response): + return result + elif isinstance(result, tuple) and len(result) == 2: + # Unpack result dict and status code from tuple + result, status_code = result + + logger.debug("Simple response detected, serializing return before constructing final response") + return Response( + status_code=status_code, + content_type=content_types.APPLICATION_JSON, + body=result, + ) + + def include_router(self, router: Router, prefix: str | None = None) -> None: + """Adds all routes and context defined in a router + + Parameters + ---------- + router : Router + The Router containing a list of routes to be registered after the existing routes + prefix : str, optional + An optional prefix to be added to the originally defined rule + """ + + # Add reference to parent ApiGatewayResolver to support use cases where people subclass it to add custom logic + router.api_resolver = self + + logger.debug("Merging App context with Router context") + self.context.update(**router.context) + + logger.debug("Appending Router middlewares into App middlewares.") + self._router_middlewares = self._router_middlewares + router._router_middlewares + + logger.debug("Appending Router exception_handler into App exception_handler.") + self._exception_handlers.update(router._exception_handlers) + + # use pointer to allow context clearance after event is processed e.g., resolve(evt, ctx) + router.context = self.context + + # Iterate through the routes defined in the router to configure and apply middlewares for each route + for route, func in router._routes.items(): + new_route = route + + if prefix: + rule = route[0] + rule = prefix if rule == "/" else f"{prefix}{rule}" + new_route = (rule, *route[1:]) + + # Middlewares are stored by route separately - must grab them to include + # Middleware store the route without prefix, so we must not include prefix when grabbing + middlewares = router._routes_with_middleware.get(route) + + # Need to use "type: ignore" here since mypy does not like a named parameter after + # tuple expansion since may cause duplicate named parameters in the function signature. + # In this case this is not possible since the tuple expansion is from a hashable source + # and the `middlewares` list is a non-hashable structure so will never be included. + # Still need to ignore for mypy checks or will cause failures (false-positive) + self.route(*new_route, middlewares=middlewares)(func) # type: ignore + + @staticmethod + def _get_fields_from_routes(routes: Sequence[Route]) -> list[ModelField]: + """ + Returns a list of fields from the routes + """ + + from aws_lambda_powertools.event_handler.openapi.compat import ModelField + from aws_lambda_powertools.event_handler.openapi.dependant import ( + get_flat_params, + ) + + body_fields_from_routes: list[ModelField] = [] + responses_from_routes: list[ModelField] = [] + request_fields_from_routes: list[ModelField] = [] + + for route in routes: + if route.body_field: + if not isinstance(route.body_field, ModelField): + raise AssertionError("A request body myst be a Pydantic Field") + body_fields_from_routes.append(route.body_field) + + params = get_flat_params(route.dependant) + request_fields_from_routes.extend(params) + + if route.dependant.return_param: + responses_from_routes.append(route.dependant.return_param) + + if route.dependant.response_extra_models: + responses_from_routes.extend(route.dependant.response_extra_models) + + flat_models = list(responses_from_routes + request_fields_from_routes + body_fields_from_routes) + return flat_models + + +class Router(BaseRouter): + """Router helper class to allow splitting ApiGatewayResolver into multiple files""" + + def __init__(self): + self._routes: dict[tuple, Callable] = {} + self._routes_with_middleware: dict[tuple, list[Callable]] = {} + self.api_resolver: BaseRouter | None = None + self.context = {} # early init as customers might add context before event resolution + self._exception_handlers: dict[type, Callable] = {} + + def route( + self, + rule: str, + method: str | list[str] | tuple[str], + cors: bool | None = None, + compress: bool = False, + cache_control: str | None = None, + summary: str | None = None, + description: str | None = None, + responses: dict[int, OpenAPIResponse] | None = None, + response_description: str | None = _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION, + tags: list[str] | None = None, + operation_id: str | None = None, + include_in_schema: bool = True, + security: list[dict[str, list[str]]] | None = None, + openapi_extensions: dict[str, Any] | None = None, + middlewares: list[Callable[..., Any]] | None = None, + ): + def register_route(func: Callable): + # All dict keys needs to be hashable. So we'll need to do some conversions: + methods = (method,) if isinstance(method, str) else tuple(method) + frozen_responses = _FrozenDict(responses) if responses else None + frozen_tags = frozenset(tags) if tags else None + frozen_security = _FrozenListDict(security) if security else None + fronzen_openapi_extensions = _FrozenDict(openapi_extensions) if openapi_extensions else None + + route_key = ( + rule, + methods, + cors, + compress, + cache_control, + summary, + description, + frozen_responses, + response_description, + frozen_tags, + operation_id, + include_in_schema, + frozen_security, + fronzen_openapi_extensions, + ) + + # Collate Middleware for routes + if middlewares is not None: + for handler in middlewares: + if self._routes_with_middleware.get(route_key) is None: + self._routes_with_middleware[route_key] = [handler] + else: + self._routes_with_middleware[route_key].append(handler) + else: + self._routes_with_middleware[route_key] = [] + + self._routes[route_key] = func + + return func + + return register_route + + def exception_handler(self, exc_class: type[Exception] | list[type[Exception]]): + def register_exception_handler(func: Callable): + if isinstance(exc_class, list): + for exp in exc_class: + self._exception_handlers[exp] = func + else: + self._exception_handlers[exc_class] = func + return func + + return register_exception_handler + + +class APIGatewayRestResolver(ApiGatewayResolver): + current_event: APIGatewayProxyEvent + + def __init__( + self, + cors: CORSConfig | None = None, + debug: bool | None = None, + serializer: Callable[[dict], str] | None = None, + strip_prefixes: list[str | Pattern] | None = None, + enable_validation: bool = False, + ): + """Amazon API Gateway REST and HTTP API v1 payload resolver""" + super().__init__( + ProxyEventType.APIGatewayProxyEvent, + cors, + debug, + serializer, + strip_prefixes, + enable_validation, + ) + + def _get_base_path(self) -> str: + # 3 different scenarios: + # + # 1. SAM local: even though a stage variable is sent to the Lambda function, it's not used in the path + # 2. API Gateway REST API: stage variable is used in the path + # 3. API Gateway REST Custom Domain: stage variable is not used in the path + # + # To solve the 3 scenarios, we try to match the beginning of the path with the stage variable + stage = self.current_event.request_context.stage + if stage and stage != "$default" and self.current_event.request_context.path.startswith(f"/{stage}"): + return f"/{stage}" + return "" + + # override route to ignore trailing "/" in routes for REST API + def route( + self, + rule: str, + method: str | list[str] | tuple[str], + cors: bool | None = None, + compress: bool = False, + cache_control: str | None = None, + summary: str | None = None, + description: str | None = None, + responses: dict[int, OpenAPIResponse] | None = None, + response_description: str = _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION, + tags: list[str] | None = None, + operation_id: str | None = None, + include_in_schema: bool = True, + security: list[dict[str, list[str]]] | None = None, + openapi_extensions: dict[str, Any] | None = None, + middlewares: list[Callable[..., Any]] | None = None, + ): + # NOTE: see #1552 for more context. + return super().route( + rule.rstrip("/"), + method, + cors, + compress, + cache_control, + summary, + description, + responses, + response_description, + tags, + operation_id, + include_in_schema, + security, + openapi_extensions, + middlewares, + ) + + # Override _compile_regex to exclude trailing slashes for route resolution + @staticmethod + def _compile_regex(rule: str, base_regex: str = _ROUTE_REGEX): + return super(APIGatewayRestResolver, APIGatewayRestResolver)._compile_regex(rule, "^{}/*$") + + +class APIGatewayHttpResolver(ApiGatewayResolver): + current_event: APIGatewayProxyEventV2 + + def __init__( + self, + cors: CORSConfig | None = None, + debug: bool | None = None, + serializer: Callable[[dict], str] | None = None, + strip_prefixes: list[str | Pattern] | None = None, + enable_validation: bool = False, + ): + """Amazon API Gateway HTTP API v2 payload resolver""" + super().__init__( + ProxyEventType.APIGatewayProxyEventV2, + cors, + debug, + serializer, + strip_prefixes, + enable_validation, + ) + + def _get_base_path(self) -> str: + # 3 different scenarios: + # + # 1. SAM local: even though a stage variable is sent to the Lambda function, it's not used in the path + # 2. API Gateway HTTP API: stage variable is used in the path + # 3. API Gateway HTTP Custom Domain: stage variable is not used in the path + # + # To solve the 3 scenarios, we try to match the beginning of the path with the stage variable + stage = self.current_event.request_context.stage + if stage and stage != "$default" and self.current_event.request_context.http.path.startswith(f"/{stage}"): + return f"/{stage}" + return "" + + +class ALBResolver(ApiGatewayResolver): + current_event: ALBEvent + + def __init__( + self, + cors: CORSConfig | None = None, + debug: bool | None = None, + serializer: Callable[[dict], str] | None = None, + strip_prefixes: list[str | Pattern] | None = None, + enable_validation: bool = False, + ): + """Amazon Application Load Balancer (ALB) resolver""" + super().__init__(ProxyEventType.ALBEvent, cors, debug, serializer, strip_prefixes, enable_validation) + + def _get_base_path(self) -> str: + # ALB doesn't have a stage variable, so we just return an empty string + return "" + + @override + def _to_response(self, result: dict | tuple | Response) -> Response: + """Convert the route's result to a Response + + ALB requires a non-null body otherwise it converts as HTTP 5xx + + 3 main result types are supported: + + - Dict[str, Any]: Rest api response with just the Dict to json stringify and content-type is set to + application/json + - Tuple[dict, int]: Same dict handling as above but with the option of including a status code + - Response: returned as is, and allows for more flexibility + """ + + # NOTE: Minor override for early return on Response with null body for ALB + if isinstance(result, Response) and result.body is None: + logger.debug("ALB doesn't allow None responses; converting to empty string") + result.body = "" + + return super()._to_response(result) diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/appsync.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/appsync.py new file mode 100644 index 0000000000000000000000000000000000000000..6f1cb72d067ada47cc5360dc9d3995f2aebfdb81 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/appsync.py @@ -0,0 +1,472 @@ +from __future__ import annotations + +import asyncio +import logging +import warnings +from typing import TYPE_CHECKING, Any, Callable + +from aws_lambda_powertools.event_handler.graphql_appsync.exceptions import InvalidBatchResponse, ResolverNotFoundError +from aws_lambda_powertools.event_handler.graphql_appsync.router import Router +from aws_lambda_powertools.utilities.data_classes import AppSyncResolverEvent + +if TYPE_CHECKING: + from aws_lambda_powertools.utilities.typing import LambdaContext + +from aws_lambda_powertools.warnings import PowertoolsUserWarning + +logger = logging.getLogger(__name__) + + +class AppSyncResolver(Router): + """ + AppSync GraphQL API Resolver + + Example + ------- + ```python + from aws_lambda_powertools.event_handler import AppSyncResolver + + app = AppSyncResolver() + + @app.resolver(type_name="Query", field_name="listLocations") + def list_locations(page: int = 0, size: int = 10) -> list: + # Your logic to fetch locations with arguments passed in + return [{"id": 100, "name": "Smooth Grooves"}] + + @app.resolver(type_name="Merchant", field_name="extraInfo") + def get_extra_info() -> dict: + # Can use "app.current_event.source" to filter within the parent context + account_type = app.current_event.source["accountType"] + method = "BTC" if account_type == "NEW" else "USD" + return {"preferredPaymentMethod": method} + + @app.resolver(field_name="commonField") + def common_field() -> str: + # Would match all fieldNames matching 'commonField' + return str(uuid.uuid4()) + ``` + """ + + def __init__(self): + """ + Initialize a new instance of the AppSyncResolver. + """ + super().__init__() + self.context = {} # early init as customers might add context before event resolution + + def __call__( + self, + event: dict, + context: LambdaContext, + data_model: type[AppSyncResolverEvent] = AppSyncResolverEvent, + ) -> Any: + """Implicit lambda handler which internally calls `resolve`""" + return self.resolve(event, context, data_model) + + def resolve( + self, + event: dict | list[dict], + context: LambdaContext, + data_model: type[AppSyncResolverEvent] = AppSyncResolverEvent, + ) -> Any: + """Resolves the response based on the provide event and decorator routes + + Parameters + ---------- + event : dict | list[Dict] + Lambda event either coming from batch processing endpoint or from standard processing endpoint + context : LambdaContext + Lambda context + data_model: + Your data data_model to decode AppSync event, by default AppSyncResolverEvent + + Example + ------- + + ```python + from aws_lambda_powertools.event_handler import AppSyncResolver + from aws_lambda_powertools.utilities.typing import LambdaContext + + @app.resolver(field_name="createSomething") + def create_something(id: str): # noqa AA03 VNE003 + return id + + def handler(event, context: LambdaContext): + return app.resolve(event, context) + ``` + + **Bringing custom models** + + ```python + from aws_lambda_powertools import Logger, Tracer + + from aws_lambda_powertools.logging import correlation_paths + from aws_lambda_powertools.event_handler import AppSyncResolver + + tracer = Tracer(service="sample_resolver") + logger = Logger(service="sample_resolver") + app = AppSyncResolver() + + + class MyCustomModel(AppSyncResolverEvent): + @property + def country_viewer(self) -> str: + return self.request_headers.get("cloudfront-viewer-country", "") + + + @app.resolver(field_name="listLocations") + @app.resolver(field_name="locations") + def get_locations(name: str, description: str = ""): + if app.current_event.country_viewer == "US": + ... + return name + description + + + @logger.inject_lambda_context(correlation_id_path=correlation_paths.APPSYNC_RESOLVER) + @tracer.capture_lambda_handler + def lambda_handler(event, context): + return app.resolve(event, context, data_model=MyCustomModel) + ``` + + Returns + ------- + Any + Returns the result of the resolver + + Raises + ------- + ValueError + If we could not find a field resolver + """ + + self.lambda_context = context + Router.lambda_context = context + + if isinstance(event, list): + Router.current_batch_event = [data_model(e) for e in event] + response = self._call_batch_resolver(event=event, data_model=data_model) + else: + Router.current_event = data_model(event) + response = self._call_single_resolver(event=event, data_model=data_model) + + # We don't clear the context for coroutines because we don't have control over the event loop. + # If we clean the context immediately, it might not be available when the coroutine is actually executed. + # For single async operations, the context should be cleaned up manually after the coroutine completes. + # See: https://github.com/aws-powertools/powertools-lambda-python/issues/5290 + # REVIEW: Review this support in Powertools V4 + if not asyncio.iscoroutine(response): + self.clear_context() + + return response + + def _call_single_resolver(self, event: dict, data_model: type[AppSyncResolverEvent]) -> Any: + """Call single event resolver + + Parameters + ---------- + event : dict + Event + data_model : type[AppSyncResolverEvent] + Data_model to decode AppSync event, by default it is of AppSyncResolverEvent type or subclass of it + """ + + logger.debug("Processing direct resolver event") + + self.current_event = data_model(event) + resolver = self._resolver_registry.find_resolver(self.current_event.type_name, self.current_event.field_name) + if not resolver: + raise ValueError(f"No resolver found for '{self.current_event.type_name}.{self.current_event.field_name}'") + return resolver["func"](**self.current_event.arguments) + + def _call_sync_batch_resolver( + self, + resolver: Callable, + raise_on_error: bool = False, + aggregate: bool = True, + ) -> list[Any]: + """ + Calls a synchronous batch resolver function for each event in the current batch. + + Parameters + ---------- + resolver: Callable + The callable function to resolve events. + raise_on_error: bool + A flag indicating whether to raise an error when processing batches + with failed items. Defaults to False, which means errors are handled without raising exceptions. + aggregate: bool + A flag indicating whether the batch items should be processed at once or individually. + If True (default), the batch resolver will process all items in the batch as a single event. + If False, the batch resolver will process each item in the batch individually. + + Returns + ------- + list[Any] + A list of results corresponding to the resolved events. + """ + + logger.debug(f"Graceful error handling flag {raise_on_error=}") + + # Checks whether the entire batch should be processed at once + if aggregate: + # Process the entire batch + response = resolver(event=self.current_batch_event) + + if not isinstance(response, list): + raise InvalidBatchResponse("The response must be a List when using batch resolvers") + + return response + + # Non aggregated events, so we call this event list x times + # Stop on first exception we encounter + if raise_on_error: + return [ + resolver(event=appconfig_event, **appconfig_event.arguments) + for appconfig_event in self.current_batch_event + ] + + # By default, we gracefully append `None` for any records that failed processing + results = [] + for idx, event in enumerate(self.current_batch_event): + try: + results.append(resolver(event=event, **event.arguments)) + except Exception: + logger.debug(f"Failed to process event number {idx} from field '{event.info.field_name}'") + results.append(None) + + return results + + async def _call_async_batch_resolver( + self, + resolver: Callable, + raise_on_error: bool = False, + aggregate: bool = True, + ) -> list[Any]: + """ + Asynchronously call a batch resolver for each event in the current batch. + + Parameters + ---------- + resolver: Callable + The asynchronous resolver function. + raise_on_error: bool + A flag indicating whether to raise an error when processing batches + with failed items. Defaults to False, which means errors are handled without raising exceptions. + aggregate: bool + A flag indicating whether the batch items should be processed at once or individually. + If True (default), the batch resolver will process all items in the batch as a single event. + If False, the batch resolver will process each item in the batch individually. + + Returns + ------- + list[Any] + A list of results corresponding to the resolved events. + """ + + logger.debug(f"Graceful error handling flag {raise_on_error=}") + + # Checks whether the entire batch should be processed at once + if aggregate: + # Process the entire batch + ret = await resolver(event=self.current_batch_event) + if not isinstance(ret, list): + raise InvalidBatchResponse("The response must be a List when using batch resolvers") + + return ret + + response: list = [] + + # Prime coroutines + tasks = [resolver(event=e, **e.arguments) for e in self.current_batch_event] + + # Aggregate results or raise at first error + if raise_on_error: + response.extend(await asyncio.gather(*tasks)) + return response + + # Aggregate results and exceptions, then filter them out + # Use `None` upon exception for graceful error handling at GraphQL engine level + # + # NOTE: asyncio.gather(return_exceptions=True) catches and includes exceptions in the results + # this will become useful when we support exception handling in AppSync resolver + results = await asyncio.gather(*tasks, return_exceptions=True) + response.extend(None if isinstance(ret, Exception) else ret for ret in results) + + return response + + def _call_batch_resolver(self, event: list[dict], data_model: type[AppSyncResolverEvent]) -> list[Any]: + """Call batch event resolver for sync and async methods + + Parameters + ---------- + event : list[dict] + Batch event + data_model : type[AppSyncResolverEvent] + Data_model to decode AppSync event, by default AppSyncResolverEvent or a subclass + + Returns + ------- + list[Any] + Results of the resolver execution. + + Raises + ------ + InconsistentPayloadError: + When all events in the batch do not have the same fieldName. + + ResolverNotFoundError: + When no resolver is found for the specified type and field. + """ + logger.debug("Processing batch resolver event") + + self.current_batch_event = [data_model(e) for e in event] + type_name, field_name = self.current_batch_event[0].type_name, self.current_batch_event[0].field_name + + resolver = self._batch_resolver_registry.find_resolver(type_name, field_name) + async_resolver = self._async_batch_resolver_registry.find_resolver(type_name, field_name) + + if resolver and async_resolver: + warnings.warn( + f"Both synchronous and asynchronous resolvers found for the same event and field." + f"The synchronous resolver takes precedence. Executing: {resolver['func'].__name__}", + stacklevel=2, + category=PowertoolsUserWarning, + ) + + if resolver: + logger.debug(f"Found sync resolver. {resolver=}, {field_name=}") + return self._call_sync_batch_resolver( + resolver=resolver["func"], + raise_on_error=resolver["raise_on_error"], + aggregate=resolver["aggregate"], + ) + + if async_resolver: + logger.debug(f"Found async resolver. {resolver=}, {field_name=}") + return asyncio.run( + self._call_async_batch_resolver( + resolver=async_resolver["func"], + raise_on_error=async_resolver["raise_on_error"], + aggregate=async_resolver["aggregate"], + ), + ) + + raise ResolverNotFoundError(f"No resolver found for '{type_name}.{field_name}'") + + def include_router(self, router: Router) -> None: + """Adds all resolvers defined in a router + + Parameters + ---------- + router : Router + A router containing a dict of field resolvers + """ + + # Merge app and router context + logger.debug("Merging router and app context") + self.context.update(**router.context) + + # use pointer to allow context clearance after event is processed e.g., resolve(evt, ctx) + router.context = self.context + + logger.debug("Merging router resolver registries") + self._resolver_registry.merge(router._resolver_registry) + self._batch_resolver_registry.merge(router._batch_resolver_registry) + self._async_batch_resolver_registry.merge(router._async_batch_resolver_registry) + + def resolver(self, type_name: str = "*", field_name: str | None = None) -> Callable: + """Registers direct resolver function for GraphQL type and field name. + + Parameters + ---------- + type_name : str, optional + GraphQL type e.g., Query, Mutation, by default "*" meaning any + field_name : Optional[str], optional + GraphQL field e.g., getTodo, createTodo, by default None + + Returns + ------- + Callable + Registered resolver + + Example + ------- + + ```python + from aws_lambda_powertools.event_handler import AppSyncResolver + + from typing import TypedDict + + app = AppSyncResolver() + + class Todo(TypedDict, total=False): + id: str + userId: str + title: str + completed: bool + + # resolve any GraphQL `getTodo` queries + # arguments are injected as function arguments as-is + @app.resolver(type_name="Query", field_name="getTodo") + def get_todo(id: str = "", status: str = "open") -> Todo: + todos: Response = requests.get(f"https://jsonplaceholder.typicode.com/todos/{id}") + todos.raise_for_status() + + return todos.json() + + def lambda_handler(event, context): + return app.resolve(event, context) + ``` + """ + return self._resolver_registry.register(field_name=field_name, type_name=type_name) + + def batch_resolver( + self, + type_name: str = "*", + field_name: str | None = None, + raise_on_error: bool = False, + aggregate: bool = True, + ) -> Callable: + """Registers batch resolver function for GraphQL type and field name. + + By default, we handle errors gracefully by returning `None`. If you want + to short-circuit and fail the entire batch use `raise_on_error=True`. + + Parameters + ---------- + type_name : str, optional + GraphQL type e.g., Query, Mutation, by default "*" meaning any + field_name : Optional[str], optional + GraphQL field e.g., getTodo, createTodo, by default None + raise_on_error : bool, optional + Whether to fail entire batch upon error, or handle errors gracefully (None), by default False + aggregate: bool + A flag indicating whether the batch items should be processed at once or individually. + If True (default), the batch resolver will process all items in the batch as a single event. + If False, the batch resolver will process each item in the batch individually. + + Returns + ------- + Callable + Registered resolver + """ + return self._batch_resolver_registry.register( + field_name=field_name, + type_name=type_name, + raise_on_error=raise_on_error, + aggregate=aggregate, + ) + + def async_batch_resolver( + self, + type_name: str = "*", + field_name: str | None = None, + raise_on_error: bool = False, + aggregate: bool = True, + ) -> Callable: + return self._async_batch_resolver_registry.register( + field_name=field_name, + type_name=type_name, + raise_on_error=raise_on_error, + aggregate=aggregate, + ) diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/bedrock_agent.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/bedrock_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..8af5520a188b8e3d00ae8933f18eeeda2711ab62 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/bedrock_agent.py @@ -0,0 +1,396 @@ +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any, Callable + +from typing_extensions import override + +from aws_lambda_powertools.event_handler import ApiGatewayResolver +from aws_lambda_powertools.event_handler.api_gateway import ( + _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION, + ProxyEventType, + ResponseBuilder, +) +from aws_lambda_powertools.event_handler.openapi.constants import DEFAULT_API_VERSION, DEFAULT_OPENAPI_VERSION + +if TYPE_CHECKING: + from re import Match + + from aws_lambda_powertools.event_handler.openapi.models import Contact, License, SecurityScheme, Server, Tag + from aws_lambda_powertools.event_handler.openapi.types import OpenAPIResponse + from aws_lambda_powertools.utilities.data_classes import BedrockAgentEvent + + +class BedrockResponseBuilder(ResponseBuilder): + """ + Bedrock Response Builder. This builds the response dict to be returned by Lambda when using Bedrock Agents. + + Since the payload format is different from the standard API Gateway Proxy event, we override the build method. + """ + + @override + def build(self, event: BedrockAgentEvent, *args) -> dict[str, Any]: + """Build the full response dict to be returned by the lambda""" + self._route(event, None) + + body = self.response.body + if self.response.is_json() and not isinstance(self.response.body, str): + body = self.serializer(self.response.body) + + return { + "messageVersion": "1.0", + "response": { + "actionGroup": event.action_group, + "apiPath": event.api_path, + "httpMethod": event.http_method, + "httpStatusCode": self.response.status_code, + "responseBody": { + self.response.content_type: { + "body": body, + }, + }, + }, + } + + +class BedrockAgentResolver(ApiGatewayResolver): + """Bedrock Agent Resolver + + See https://aws.amazon.com/bedrock/agents/ for more information. + + Examples + -------- + Simple example with a custom lambda handler using the Tracer capture_lambda_handler decorator + + ```python + from aws_lambda_powertools import Tracer + from aws_lambda_powertools.event_handler import BedrockAgentResolver + + tracer = Tracer() + app = BedrockAgentResolver() + + @app.get("/claims") + def simple_get(): + return "You have 3 claims" + + @tracer.capture_lambda_handler + def lambda_handler(event, context): + return app.resolve(event, context) + ``` + + """ + + current_event: BedrockAgentEvent + + def __init__(self, debug: bool = False, enable_validation: bool = True): + super().__init__( + proxy_type=ProxyEventType.BedrockAgentEvent, + cors=None, + debug=debug, + serializer=None, + strip_prefixes=None, + enable_validation=enable_validation, + ) + self._response_builder_class = BedrockResponseBuilder + + # Note: we need ignore[override] because we are making the optional `description` field required. + @override + def get( # type: ignore[override] + self, + rule: str, + description: str, + cors: bool | None = None, + compress: bool = False, + cache_control: str | None = None, + summary: str | None = None, + responses: dict[int, OpenAPIResponse] | None = None, + response_description: str = _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION, + tags: list[str] | None = None, + operation_id: str | None = None, + include_in_schema: bool = True, + middlewares: list[Callable[..., Any]] | None = None, + ) -> Callable[[Callable[..., Any]], Callable[..., Any]]: + + openapi_extensions = None + security = None + + return super().get( + rule, + cors, + compress, + cache_control, + summary, + description, + responses, + response_description, + tags, + operation_id, + include_in_schema, + security, + openapi_extensions, + middlewares, + ) + + # Note: we need ignore[override] because we are making the optional `description` field required. + @override + def post( # type: ignore[override] + self, + rule: str, + description: str, + cors: bool | None = None, + compress: bool = False, + cache_control: str | None = None, + summary: str | None = None, + responses: dict[int, OpenAPIResponse] | None = None, + response_description: str = _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION, + tags: list[str] | None = None, + operation_id: str | None = None, + include_in_schema: bool = True, + middlewares: list[Callable[..., Any]] | None = None, + ): + openapi_extensions = None + security = None + + return super().post( + rule, + cors, + compress, + cache_control, + summary, + description, + responses, + response_description, + tags, + operation_id, + include_in_schema, + security, + openapi_extensions, + middlewares, + ) + + # Note: we need ignore[override] because we are making the optional `description` field required. + @override + def put( # type: ignore[override] + self, + rule: str, + description: str, + cors: bool | None = None, + compress: bool = False, + cache_control: str | None = None, + summary: str | None = None, + responses: dict[int, OpenAPIResponse] | None = None, + response_description: str = _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION, + tags: list[str] | None = None, + operation_id: str | None = None, + include_in_schema: bool = True, + middlewares: list[Callable[..., Any]] | None = None, + ): + openapi_extensions = None + security = None + + return super().put( + rule, + cors, + compress, + cache_control, + summary, + description, + responses, + response_description, + tags, + operation_id, + include_in_schema, + security, + openapi_extensions, + middlewares, + ) + + # Note: we need ignore[override] because we are making the optional `description` field required. + @override + def patch( # type: ignore[override] + self, + rule: str, + description: str, + cors: bool | None = None, + compress: bool = False, + cache_control: str | None = None, + summary: str | None = None, + responses: dict[int, OpenAPIResponse] | None = None, + response_description: str = _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION, + tags: list[str] | None = None, + operation_id: str | None = None, + include_in_schema: bool = True, + middlewares: list[Callable] | None = None, + ): + openapi_extensions = None + security = None + + return super().patch( + rule, + cors, + compress, + cache_control, + summary, + description, + responses, + response_description, + tags, + operation_id, + include_in_schema, + security, + openapi_extensions, + middlewares, + ) + + # Note: we need ignore[override] because we are making the optional `description` field required. + @override + def delete( # type: ignore[override] + self, + rule: str, + description: str, + cors: bool | None = None, + compress: bool = False, + cache_control: str | None = None, + summary: str | None = None, + responses: dict[int, OpenAPIResponse] | None = None, + response_description: str = _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION, + tags: list[str] | None = None, + operation_id: str | None = None, + include_in_schema: bool = True, + middlewares: list[Callable[..., Any]] | None = None, + ): + openapi_extensions = None + security = None + + return super().delete( + rule, + cors, + compress, + cache_control, + summary, + description, + responses, + response_description, + tags, + operation_id, + include_in_schema, + security, + openapi_extensions, + middlewares, + ) + + @override + def _convert_matches_into_route_keys(self, match: Match) -> dict[str, str]: + # In Bedrock Agents, all the parameters come inside the "parameters" key, not on the apiPath + # So we have to search for route parameters in the parameters key + parameters: dict[str, str] = {} + if match.groupdict() and self.current_event.parameters: + parameters = {parameter["name"]: parameter["value"] for parameter in self.current_event.parameters} + return parameters + + @override + def get_openapi_json_schema( # type: ignore[override] + self, + *, + title: str = "Powertools API", + version: str = DEFAULT_API_VERSION, + openapi_version: str = DEFAULT_OPENAPI_VERSION, + summary: str | None = None, + description: str | None = None, + tags: list[Tag | str] | None = None, + servers: list[Server] | None = None, + terms_of_service: str | None = None, + contact: Contact | None = None, + license_info: License | None = None, + security_schemes: dict[str, SecurityScheme] | None = None, + security: list[dict[str, list[str]]] | None = None, + ) -> str: + """ + Returns the OpenAPI schema as a JSON serializable dict. + Since Bedrock Agents only support OpenAPI 3.0.0, we convert OpenAPI 3.1.0 schemas + and enforce 3.0.0 compatibility for seamless integration. + + Parameters + ---------- + title: str + The title of the application. + version: str + The version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API + openapi_version: str, default = "3.0.0" + The version of the OpenAPI Specification (which the document uses). + summary: str, optional + A short summary of what the application does. + description: str, optional + A verbose explanation of the application behavior. + tags: list[Tag, str], optional + A list of tags used by the specification with additional metadata. + servers: list[Server], optional + An array of Server Objects, which provide connectivity information to a target server. + terms_of_service: str, optional + A URL to the Terms of Service for the API. MUST be in the format of a URL. + contact: Contact, optional + The contact information for the exposed API. + license_info: License, optional + The license information for the exposed API. + security_schemes: dict[str, SecurityScheme]], optional + A declaration of the security schemes available to be used in the specification. + security: list[dict[str, list[str]]], optional + A declaration of which security mechanisms are applied globally across the API. + + Returns + ------- + str + The OpenAPI schema as a JSON serializable dict. + """ + from aws_lambda_powertools.event_handler.openapi.compat import model_json + + openapi_extensions = None + + schema = super().get_openapi_schema( + title=title, + version=version, + openapi_version=openapi_version, + summary=summary, + description=description, + tags=tags, + servers=servers, + terms_of_service=terms_of_service, + contact=contact, + license_info=license_info, + security_schemes=security_schemes, + security=security, + openapi_extensions=openapi_extensions, + ) + schema.openapi = "3.0.3" + + # Transform OpenAPI 3.1 into 3.0 + def inner(yaml_dict): + if isinstance(yaml_dict, dict): + if "anyOf" in yaml_dict and isinstance((anyOf := yaml_dict["anyOf"]), list): + for i, item in enumerate(anyOf): + if isinstance(item, dict) and item.get("type") == "null": + anyOf.pop(i) + yaml_dict["nullable"] = True + if "examples" in yaml_dict: + examples = yaml_dict["examples"] + del yaml_dict["examples"] + if isinstance(examples, list) and len(examples): + yaml_dict["example"] = examples[0] + for value in yaml_dict.values(): + inner(value) + elif isinstance(yaml_dict, list): + for item in yaml_dict: + inner(item) + + model = json.loads( + model_json( + schema, + by_alias=True, + exclude_none=True, + indent=2, + ), + ) + + inner(model) + + return json.dumps(model) diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/content_types.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/content_types.py new file mode 100644 index 0000000000000000000000000000000000000000..0f55b1088ad80861668b2493232f2b09c1d45356 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/content_types.py @@ -0,0 +1,5 @@ +# use mimetypes library to be certain, e.g., mimetypes.types_map[".json"] + +APPLICATION_JSON = "application/json" +TEXT_PLAIN = "text/plain" +TEXT_HTML = "text/html" diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/exceptions.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..ca5dbbc9830e22601ce5247edecedab63de660b2 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/exceptions.py @@ -0,0 +1,45 @@ +from http import HTTPStatus + + +class ServiceError(Exception): + """API Gateway and ALB HTTP Service Error""" + + def __init__(self, status_code: int, msg: str): + """ + Parameters + ---------- + status_code: int + Http status code + msg: str + Error message + """ + self.status_code = status_code + self.msg = msg + + +class BadRequestError(ServiceError): + """API Gateway and ALB Bad Request Error (400)""" + + def __init__(self, msg: str): + super().__init__(HTTPStatus.BAD_REQUEST, msg) + + +class UnauthorizedError(ServiceError): + """API Gateway and ALB Unauthorized Error (401)""" + + def __init__(self, msg: str): + super().__init__(HTTPStatus.UNAUTHORIZED, msg) + + +class NotFoundError(ServiceError): + """API Gateway and ALB Not Found Error (404)""" + + def __init__(self, msg: str = "Not found"): + super().__init__(HTTPStatus.NOT_FOUND, msg) + + +class InternalServerError(ServiceError): + """API Gateway and ALB Internal Server Error (500)""" + + def __init__(self, message: str): + super().__init__(HTTPStatus.INTERNAL_SERVER_ERROR, message) diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/graphql_appsync/__init__.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/graphql_appsync/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/graphql_appsync/_registry.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/graphql_appsync/_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..9c8dd395a9f0580a166a499fc4d4cb57a6642a0d --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/graphql_appsync/_registry.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +import logging +from typing import Any, Callable + +logger = logging.getLogger(__name__) + + +class ResolverRegistry: + def __init__(self): + self.resolvers: dict[str, dict[str, Any]] = {} + + def register( + self, + type_name: str = "*", + field_name: str | None = None, + raise_on_error: bool = False, + aggregate: bool = True, + ) -> Callable: + """Registers the resolver for field_name + + Parameters + ---------- + type_name : str + Type name + field_name : str + Field name + raise_on_error: bool + A flag indicating whether to raise an error when processing batches + with failed items. Defaults to False, which means errors are handled without raising exceptions. + aggregate: bool + A flag indicating whether the batch items should be processed at once or individually. + If True (default), the batch resolver will process all items in the batch as a single event. + If False, the batch resolver will process each item in the batch individually. + + Return + ---------- + Callable + A Callable + """ + + def _register(func) -> Callable: + logger.debug(f"Adding resolver `{func.__name__}` for field `{type_name}.{field_name}`") + self.resolvers[f"{type_name}.{field_name}"] = { + "func": func, + "raise_on_error": raise_on_error, + "aggregate": aggregate, + } + return func + + return _register + + def find_resolver(self, type_name: str, field_name: str) -> dict | None: + """Find resolver based on type_name and field_name + + Parameters + ---------- + type_name : str + Type name + field_name : str + Field name + Return + ---------- + Optional[Dict] + A dictionary with the resolver and if raise exception on error + """ + logger.debug(f"Looking for resolver for type={type_name}, field={field_name}.") + return self.resolvers.get(f"{type_name}.{field_name}", self.resolvers.get(f"*.{field_name}")) + + def merge(self, other_registry: ResolverRegistry): + """Update current registry with incoming registry + + Parameters + ---------- + other_registry : ResolverRegistry + Registry to merge from + """ + self.resolvers.update(**other_registry.resolvers) diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/graphql_appsync/base.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/graphql_appsync/base.py new file mode 100644 index 0000000000000000000000000000000000000000..f0fe4d78d196ded781cca4f058d49e78ee754084 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/graphql_appsync/base.py @@ -0,0 +1,160 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import Callable + + +class BaseRouter(ABC): + """Abstract base class for Router (resolvers)""" + + @abstractmethod + def resolver(self, type_name: str = "*", field_name: str | None = None) -> Callable: + """ + Retrieve a resolver function for a specific type and field. + + Parameters + ----------- + type_name: str + The name of the type. + field_name: str, optional + The name of the field (default is None). + + Examples + -------- + ```python + from typing import Optional + + from aws_lambda_powertools.event_handler import AppSyncResolver + from aws_lambda_powertools.utilities.data_classes import AppSyncResolverEvent + from aws_lambda_powertools.utilities.typing import LambdaContext + + app = AppSyncResolver() + + @app.resolver(type_name="Query", field_name="getPost") + def related_posts(event: AppSyncResolverEvent) -> Optional[list]: + return {"success": "ok"} + + def lambda_handler(event, context: LambdaContext) -> dict: + return app.resolve(event, context) + ``` + + Returns + ------- + Callable + The resolver function. + """ + raise NotImplementedError + + @abstractmethod + def batch_resolver( + self, + type_name: str = "*", + field_name: str | None = None, + raise_on_error: bool = False, + aggregate: bool = True, + ) -> Callable: + """ + Retrieve a batch resolver function for a specific type and field. + + Parameters + ----------- + type_name: str + The name of the type. + field_name: str, optional + The name of the field (default is None). + raise_on_error: bool + A flag indicating whether to raise an error when processing batches + with failed items. Defaults to False, which means errors are handled without raising exceptions. + aggregate: bool + A flag indicating whether the batch items should be processed at once or individually. + If True (default), the batch resolver will process all items in the batch as a single event. + If False, the batch resolver will process each item in the batch individually. + + Examples + -------- + ```python + from typing import Optional + + from aws_lambda_powertools.event_handler import AppSyncResolver + from aws_lambda_powertools.utilities.data_classes import AppSyncResolverEvent + from aws_lambda_powertools.utilities.typing import LambdaContext + + app = AppSyncResolver() + + @app.batch_resolver(type_name="Query", field_name="getPost") + def related_posts(event: AppSyncResolverEvent, id) -> Optional[list]: + return {"post_id": id} + + def lambda_handler(event, context: LambdaContext) -> dict: + return app.resolve(event, context) + ``` + + Returns + ------- + Callable + The batch resolver function. + """ + raise NotImplementedError + + @abstractmethod + def async_batch_resolver( + self, + type_name: str = "*", + field_name: str | None = None, + raise_on_error: bool = False, + aggregate: bool = True, + ) -> Callable: + """ + Retrieve a batch resolver function for a specific type and field and runs async. + + Parameters + ----------- + type_name: str + The name of the type. + field_name: str, optional + The name of the field (default is None). + raise_on_error: bool + A flag indicating whether to raise an error when processing batches + with failed items. Defaults to False, which means errors are handled without raising exceptions. + aggregate: bool + A flag indicating whether the batch items should be processed at once or individually. + If True (default), the batch resolver will process all items in the batch as a single event. + If False, the batch resolver will process each item in the batch individually. + + Examples + -------- + ```python + from typing import Optional + + from aws_lambda_powertools.event_handler import AppSyncResolver + from aws_lambda_powertools.utilities.data_classes import AppSyncResolverEvent + from aws_lambda_powertools.utilities.typing import LambdaContext + + app = AppSyncResolver() + + @app.async_batch_resolver(type_name="Query", field_name="getPost") + async def related_posts(event: AppSyncResolverEvent, id) -> Optional[list]: + return {"post_id": id} + + def lambda_handler(event, context: LambdaContext) -> dict: + return app.resolve(event, context) + ``` + + Returns + ------- + Callable + The batch resolver function. + """ + raise NotImplementedError + + @abstractmethod + def append_context(self, **additional_context) -> None: + """ + Appends context information available under any route. + + Parameters + ----------- + **additional_context: dict + Additional context key-value pairs to append. + """ + raise NotImplementedError diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/graphql_appsync/exceptions.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/graphql_appsync/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..f98a75b6f17c3ec6d73a54f63d4856aabbfdca94 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/graphql_appsync/exceptions.py @@ -0,0 +1,10 @@ +class ResolverNotFoundError(Exception): + """ + When a resolver is not found during a lookup. + """ + + +class InvalidBatchResponse(Exception): + """ + When a batch response something different from a List + """ diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/graphql_appsync/router.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/graphql_appsync/router.py new file mode 100644 index 0000000000000000000000000000000000000000..cb0dce1adc7395b9e21ddba20e0f5c194a86a8d7 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/graphql_appsync/router.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Callable + +from aws_lambda_powertools.event_handler.graphql_appsync._registry import ResolverRegistry +from aws_lambda_powertools.event_handler.graphql_appsync.base import BaseRouter + +if TYPE_CHECKING: + from aws_lambda_powertools.utilities.data_classes.appsync_resolver_event import AppSyncResolverEvent + from aws_lambda_powertools.utilities.typing.lambda_context import LambdaContext + + +class Router(BaseRouter): + context: dict + current_batch_event: list[AppSyncResolverEvent] = [] + current_event: AppSyncResolverEvent | None = None + lambda_context: LambdaContext | None = None + + def __init__(self): + self.context = {} # early init as customers might add context before event resolution + self._resolver_registry = ResolverRegistry() + self._batch_resolver_registry = ResolverRegistry() + self._async_batch_resolver_registry = ResolverRegistry() + + def resolver(self, type_name: str = "*", field_name: str | None = None) -> Callable: + return self._resolver_registry.register(field_name=field_name, type_name=type_name) + + def batch_resolver( + self, + type_name: str = "*", + field_name: str | None = None, + raise_on_error: bool = False, + aggregate: bool = True, + ) -> Callable: + return self._batch_resolver_registry.register( + field_name=field_name, + type_name=type_name, + raise_on_error=raise_on_error, + aggregate=aggregate, + ) + + def async_batch_resolver( + self, + type_name: str = "*", + field_name: str | None = None, + raise_on_error: bool = False, + aggregate: bool = True, + ) -> Callable: + return self._async_batch_resolver_registry.register( + field_name=field_name, + type_name=type_name, + raise_on_error=raise_on_error, + aggregate=aggregate, + ) + + def append_context(self, **additional_context): + """Append key=value data as routing context""" + self.context.update(**additional_context) + + def clear_context(self): + """Resets routing context""" + self.context.clear() diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/lambda_function_url.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/lambda_function_url.py new file mode 100644 index 0000000000000000000000000000000000000000..c7075cd9fc64c7d5d697721a82a36fdc1d515986 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/lambda_function_url.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Callable, Pattern + +from aws_lambda_powertools.event_handler.api_gateway import ( + ApiGatewayResolver, + ProxyEventType, +) + +if TYPE_CHECKING: + from aws_lambda_powertools.event_handler import CORSConfig + from aws_lambda_powertools.utilities.data_classes import LambdaFunctionUrlEvent + + +class LambdaFunctionUrlResolver(ApiGatewayResolver): + """AWS Lambda Function URL resolver + + Notes: + ----- + Lambda Function URL follows the API Gateway HTTP APIs Payload Format Version 2.0. + + Documentation: + - https://docs.aws.amazon.com/lambda/latest/dg/urls-configuration.html + - https://docs.aws.amazon.com/lambda/latest/dg/urls-invocation.html#urls-payloads + + Examples + -------- + Simple example integrating with Tracer + + ```python + from aws_lambda_powertools import Tracer + from aws_lambda_powertools.event_handler import LambdaFunctionUrlResolver + + tracer = Tracer() + app = LambdaFunctionUrlResolver() + + @app.get("/get-call") + def simple_get(): + return {"message": "Foo"} + + @app.post("/post-call") + def simple_post(): + post_data: dict = app.current_event.json_body + return {"message": post_data} + + @tracer.capture_lambda_handler + def lambda_handler(event, context): + return app.resolve(event, context) + """ + + current_event: LambdaFunctionUrlEvent + + def __init__( + self, + cors: CORSConfig | None = None, + debug: bool | None = None, + serializer: Callable[[dict], str] | None = None, + strip_prefixes: list[str | Pattern] | None = None, + enable_validation: bool = False, + ): + super().__init__( + ProxyEventType.LambdaFunctionUrlEvent, + cors, + debug, + serializer, + strip_prefixes, + enable_validation, + ) + + def _get_base_path(self) -> str: + stage = self.current_event.request_context.stage + if stage and stage != "$default" and self.current_event.request_context.http.method.startswith(f"/{stage}"): + return f"/{stage}" + return "" diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/middlewares/__init__.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/middlewares/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..068ce9c04b72b2defa03d3870bd5e62830a43152 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/middlewares/__init__.py @@ -0,0 +1,3 @@ +from aws_lambda_powertools.event_handler.middlewares.base import BaseMiddlewareHandler, NextMiddleware + +__all__ = ["BaseMiddlewareHandler", "NextMiddleware"] diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/middlewares/base.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/middlewares/base.py new file mode 100644 index 0000000000000000000000000000000000000000..3998c7c80bdc339de017a31b8e87a24eb388684a --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/middlewares/base.py @@ -0,0 +1,121 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Generic, Protocol + +from aws_lambda_powertools.event_handler.types import EventHandlerInstance + +if TYPE_CHECKING: + from aws_lambda_powertools.event_handler.api_gateway import Response + + +class NextMiddleware(Protocol): + def __call__(self, app: EventHandlerInstance) -> Response: + """Protocol for callback regardless of next_middleware(app), get_response(app) etc""" + ... + + def __name__(self) -> str: # noqa A003 + """Protocol for name of the Middleware""" + ... + + +class BaseMiddlewareHandler(Generic[EventHandlerInstance], ABC): + """Base implementation for Middlewares to run code before and after in a chain. + + + This is the middleware handler function where middleware logic is implemented. + The next middleware handler is represented by `next_middleware`, returning a Response object. + + Examples + -------- + + **Correlation ID Middleware** + + ```python + import requests + + from aws_lambda_powertools import Logger + from aws_lambda_powertools.event_handler import APIGatewayRestResolver, Response + from aws_lambda_powertools.event_handler.middlewares import BaseMiddlewareHandler, NextMiddleware + + app = APIGatewayRestResolver() + logger = Logger() + + + class CorrelationIdMiddleware(BaseMiddlewareHandler): + def __init__(self, header: str): + super().__init__() + self.header = header + + def handler(self, app: APIGatewayRestResolver, next_middleware: NextMiddleware) -> Response: + # BEFORE logic + request_id = app.current_event.request_context.request_id + correlation_id = app.current_event.headers.get(self.header, request_id) + + # Call next middleware or route handler ('/todos') + response = next_middleware(app) + + # AFTER logic + response.headers[self.header] = correlation_id + + return response + + + @app.get("/todos", middlewares=[CorrelationIdMiddleware(header="x-correlation-id")]) + def get_todos(): + todos: requests.Response = requests.get("https://jsonplaceholder.typicode.com/todos") + todos.raise_for_status() + + # for brevity, we'll limit to the first 10 only + return {"todos": todos.json()[:10]} + + + @logger.inject_lambda_context + def lambda_handler(event, context): + return app.resolve(event, context) + + ``` + + """ + + @abstractmethod + def handler(self, app: EventHandlerInstance, next_middleware: NextMiddleware) -> Response: + """ + The Middleware Handler + + Parameters + ---------- + app: EventHandlerInstance + An instance of an Event Handler that implements ApiGatewayResolver + next_middleware: NextMiddleware + The next middleware handler in the chain + + Returns + ------- + Response + The response from the next middleware handler in the chain + + """ + raise NotImplementedError() + + @property + def __name__(self) -> str: # noqa A003 + return str(self.__class__.__name__) + + def __call__(self, app: EventHandlerInstance, next_middleware: NextMiddleware) -> Response: + """ + The Middleware handler function. + + Parameters + ---------- + app: ApiGatewayResolver + An instance of an Event Handler that implements ApiGatewayResolver + next_middleware: NextMiddleware + The next middleware handler in the chain + + Returns + ------- + Response + The response from the next middleware handler in the chain + """ + return self.handler(app, next_middleware) diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/middlewares/openapi_validation.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/middlewares/openapi_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..a73fd4544580155d1eedc1b2b0af1bc898bcc253 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/middlewares/openapi_validation.py @@ -0,0 +1,440 @@ +from __future__ import annotations + +import dataclasses +import json +import logging +from copy import deepcopy +from typing import TYPE_CHECKING, Any, Callable, Mapping, MutableMapping, Sequence + +from pydantic import BaseModel + +from aws_lambda_powertools.event_handler.middlewares import BaseMiddlewareHandler +from aws_lambda_powertools.event_handler.openapi.compat import ( + _model_dump, + _normalize_errors, + _regenerate_error_with_loc, + get_missing_field_error, +) +from aws_lambda_powertools.event_handler.openapi.dependant import is_scalar_field +from aws_lambda_powertools.event_handler.openapi.encoders import jsonable_encoder +from aws_lambda_powertools.event_handler.openapi.exceptions import RequestValidationError +from aws_lambda_powertools.event_handler.openapi.params import Param + +if TYPE_CHECKING: + from aws_lambda_powertools.event_handler import Response + from aws_lambda_powertools.event_handler.api_gateway import Route + from aws_lambda_powertools.event_handler.middlewares import NextMiddleware + from aws_lambda_powertools.event_handler.openapi.compat import ModelField + from aws_lambda_powertools.event_handler.openapi.types import IncEx + from aws_lambda_powertools.event_handler.types import EventHandlerInstance + +logger = logging.getLogger(__name__) + + +class OpenAPIValidationMiddleware(BaseMiddlewareHandler): + """ + OpenAPIValidationMiddleware is a middleware that validates the request against the OpenAPI schema defined by the + Lambda handler. It also validates the response against the OpenAPI schema defined by the Lambda handler. It + should not be used directly, but rather through the `enable_validation` parameter of the `ApiGatewayResolver`. + + Examples + -------- + + ```python + from pydantic import BaseModel + + from aws_lambda_powertools.event_handler.api_gateway import ( + APIGatewayRestResolver, + ) + + class Todo(BaseModel): + name: str + + app = APIGatewayRestResolver(enable_validation=True) + + @app.get("/todos") + def get_todos(): list[Todo]: + return [Todo(name="hello world")] + ``` + """ + + def __init__(self, validation_serializer: Callable[[Any], str] | None = None): + """ + Initialize the OpenAPIValidationMiddleware. + + Parameters + ---------- + validation_serializer : Callable, optional + Optional serializer to use when serializing the response for validation. + Use it when you have a custom type that cannot be serialized by the default jsonable_encoder. + """ + self._validation_serializer = validation_serializer + + def handler(self, app: EventHandlerInstance, next_middleware: NextMiddleware) -> Response: + logger.debug("OpenAPIValidationMiddleware handler") + + route: Route = app.context["_route"] + + values: dict[str, Any] = {} + errors: list[Any] = [] + + # Process path values, which can be found on the route_args + path_values, path_errors = _request_params_to_args( + route.dependant.path_params, + app.context["_route_args"], + ) + + # Normalize query values before validate this + query_string = _normalize_multi_query_string_with_param( + app.current_event.resolved_query_string_parameters, + route.dependant.query_params, + ) + + # Process query values + query_values, query_errors = _request_params_to_args( + route.dependant.query_params, + query_string, + ) + + # Normalize header values before validate this + headers = _normalize_multi_header_values_with_param( + app.current_event.resolved_headers_field, + route.dependant.header_params, + ) + + # Process header values + header_values, header_errors = _request_params_to_args( + route.dependant.header_params, + headers, + ) + + values.update(path_values) + values.update(query_values) + values.update(header_values) + errors += path_errors + query_errors + header_errors + + # Process the request body, if it exists + if route.dependant.body_params: + (body_values, body_errors) = _request_body_to_args( + required_params=route.dependant.body_params, + received_body=self._get_body(app), + ) + values.update(body_values) + errors.extend(body_errors) + + if errors: + # Raise the validation errors + raise RequestValidationError(_normalize_errors(errors)) + else: + # Re-write the route_args with the validated values, and call the next middleware + app.context["_route_args"] = values + + # Call the handler by calling the next middleware + response = next_middleware(app) + + # Process the response + return self._handle_response(route=route, response=response) + + def _handle_response(self, *, route: Route, response: Response): + # Process the response body if it exists + if response.body: + # Validate and serialize the response, if it's JSON + if response.is_json(): + response.body = self._serialize_response( + field=route.dependant.return_param, + response_content=response.body, + ) + + return response + + def _serialize_response( + self, + *, + field: ModelField | None = None, + response_content: Any, + include: IncEx | None = None, + exclude: IncEx | None = None, + by_alias: bool = True, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + ) -> Any: + """ + Serialize the response content according to the field type. + """ + if field: + errors: list[dict[str, Any]] = [] + # MAINTENANCE: remove this when we drop pydantic v1 + if not hasattr(field, "serializable"): + response_content = self._prepare_response_content( + response_content, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + value = _validate_field(field=field, value=response_content, loc=("response",), existing_errors=errors) + if errors: + raise RequestValidationError(errors=_normalize_errors(errors), body=response_content) + + if hasattr(field, "serialize"): + return field.serialize( + value, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + return jsonable_encoder( + value, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + custom_serializer=self._validation_serializer, + ) + else: + # Just serialize the response content returned from the handler + return jsonable_encoder(response_content, custom_serializer=self._validation_serializer) + + def _prepare_response_content( + self, + res: Any, + *, + exclude_unset: bool, + exclude_defaults: bool = False, + exclude_none: bool = False, + ) -> Any: + """ + Prepares the response content for serialization. + """ + if isinstance(res, BaseModel): + return _model_dump( + res, + by_alias=True, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + elif isinstance(res, list): + return [ + self._prepare_response_content(item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults) + for item in res + ] + elif isinstance(res, dict): + return { + k: self._prepare_response_content(v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults) + for k, v in res.items() + } + elif dataclasses.is_dataclass(res): + return dataclasses.asdict(res) # type: ignore[arg-type] + return res + + def _get_body(self, app: EventHandlerInstance) -> dict[str, Any]: + """ + Get the request body from the event, and parse it as JSON. + """ + + content_type = app.current_event.headers.get("content-type") + if not content_type or content_type.strip().startswith("application/json"): + try: + return app.current_event.json_body + except json.JSONDecodeError as e: + raise RequestValidationError( + [ + { + "type": "json_invalid", + "loc": ("body", e.pos), + "msg": "JSON decode error", + "input": {}, + "ctx": {"error": e.msg}, + }, + ], + body=e.doc, + ) from e + else: + raise NotImplementedError("Only JSON body is supported") + + +def _request_params_to_args( + required_params: Sequence[ModelField], + received_params: Mapping[str, Any], +) -> tuple[dict[str, Any], list[Any]]: + """ + Convert the request params to a dictionary of values using validation, and returns a list of errors. + """ + values = {} + errors = [] + + for field in required_params: + field_info = field.field_info + + # To ensure early failure, we check if it's not an instance of Param. + if not isinstance(field_info, Param): + raise AssertionError(f"Expected Param field_info, got {field_info}") + + value = received_params.get(field.alias) + + loc = (field_info.in_.value, field.alias) + + # If we don't have a value, see if it's required or has a default + if value is None: + if field.required: + errors.append(get_missing_field_error(loc=loc)) + else: + values[field.name] = deepcopy(field.default) + continue + + # Finally, validate the value + values[field.name] = _validate_field(field=field, value=value, loc=loc, existing_errors=errors) + + return values, errors + + +def _request_body_to_args( + required_params: list[ModelField], + received_body: dict[str, Any] | None, +) -> tuple[dict[str, Any], list[dict[str, Any]]]: + """ + Convert the request body to a dictionary of values using validation, and returns a list of errors. + """ + values: dict[str, Any] = {} + errors: list[dict[str, Any]] = [] + + received_body, field_alias_omitted = _get_embed_body( + field=required_params[0], + required_params=required_params, + received_body=received_body, + ) + + for field in required_params: + # This sets the location to: + # { "user": { object } } if field.alias == user + # { { object } if field_alias is omitted + loc: tuple[str, ...] = ("body", field.alias) + if field_alias_omitted: + loc = ("body",) + + value: Any | None = None + + # Now that we know what to look for, try to get the value from the received body + if received_body is not None: + try: + value = received_body.get(field.alias) + except AttributeError: + errors.append(get_missing_field_error(loc)) + continue + + # Determine if the field is required + if value is None: + if field.required: + errors.append(get_missing_field_error(loc)) + else: + values[field.name] = deepcopy(field.default) + continue + + # MAINTENANCE: Handle byte and file fields + + # Finally, validate the value + values[field.name] = _validate_field(field=field, value=value, loc=loc, existing_errors=errors) + + return values, errors + + +def _validate_field( + *, + field: ModelField, + value: Any, + loc: tuple[str, ...], + existing_errors: list[dict[str, Any]], +): + """ + Validate a field, and append any errors to the existing_errors list. + """ + validated_value, errors = field.validate(value, value, loc=loc) + + if isinstance(errors, list): + processed_errors = _regenerate_error_with_loc(errors=errors, loc_prefix=()) + existing_errors.extend(processed_errors) + elif errors: + existing_errors.append(errors) + + return validated_value + + +def _get_embed_body( + *, + field: ModelField, + required_params: list[ModelField], + received_body: dict[str, Any] | None, +) -> tuple[dict[str, Any] | None, bool]: + field_info = field.field_info + embed = getattr(field_info, "embed", None) + + # If the field is an embed, and the field alias is omitted, we need to wrap the received body in the field alias. + field_alias_omitted = len(required_params) == 1 and not embed + if field_alias_omitted: + received_body = {field.alias: received_body} + + return received_body, field_alias_omitted + + +def _normalize_multi_query_string_with_param( + query_string: dict[str, list[str]], + params: Sequence[ModelField], +) -> dict[str, Any]: + """ + Extract and normalize resolved_query_string_parameters + + Parameters + ---------- + query_string: dict + A dictionary containing the initial query string parameters. + params: Sequence[ModelField] + A sequence of ModelField objects representing parameters. + + Returns + ------- + A dictionary containing the processed multi_query_string_parameters. + """ + resolved_query_string: dict[str, Any] = query_string + for param in filter(is_scalar_field, params): + try: + # if the target parameter is a scalar, we keep the first value of the query string + # regardless if there are more in the payload + resolved_query_string[param.alias] = query_string[param.alias][0] + except KeyError: + pass + return resolved_query_string + + +def _normalize_multi_header_values_with_param(headers: MutableMapping[str, Any], params: Sequence[ModelField]): + """ + Extract and normalize resolved_headers_field + + Parameters + ---------- + headers: MutableMapping[str, Any] + A dictionary containing the initial header parameters. + params: Sequence[ModelField] + A sequence of ModelField objects representing parameters. + + Returns + ------- + A dictionary containing the processed headers. + """ + if headers: + for param in filter(is_scalar_field, params): + try: + if len(headers[param.alias]) == 1: + # if the target parameter is a scalar and the list contains only 1 element + # we keep the first value of the headers regardless if there are more in the payload + headers[param.alias] = headers[param.alias][0] + except KeyError: + pass + return headers diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/middlewares/schema_validation.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/middlewares/schema_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..c31d15bec03c0a9253defee2353b40b3f58a954c --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/middlewares/schema_validation.py @@ -0,0 +1,128 @@ +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING + +from aws_lambda_powertools.event_handler.exceptions import BadRequestError, InternalServerError +from aws_lambda_powertools.event_handler.middlewares import BaseMiddlewareHandler, NextMiddleware +from aws_lambda_powertools.utilities.validation import validate +from aws_lambda_powertools.utilities.validation.exceptions import InvalidSchemaFormatError, SchemaValidationError + +if TYPE_CHECKING: + from aws_lambda_powertools.event_handler.api_gateway import Response + from aws_lambda_powertools.event_handler.types import EventHandlerInstance + +logger = logging.getLogger(__name__) + + +class SchemaValidationMiddleware(BaseMiddlewareHandler): + """Middleware to validate API request and response against JSON Schema using the [Validation utility](https://docs.powertools.aws.dev/lambda/python/latest/utilities/validation/). + + Examples + -------- + **Validating incoming event** + + ```python + import requests + + from aws_lambda_powertools import Logger + from aws_lambda_powertools.event_handler import APIGatewayRestResolver, Response + from aws_lambda_powertools.event_handler.middlewares import BaseMiddlewareHandler, NextMiddleware + from aws_lambda_powertools.event_handler.middlewares.schema_validation import SchemaValidationMiddleware + + app = APIGatewayRestResolver() + logger = Logger() + json_schema_validation = SchemaValidationMiddleware(inbound_schema=INCOMING_JSON_SCHEMA) + + + @app.get("/todos", middlewares=[json_schema_validation]) + def get_todos(): + todos: requests.Response = requests.get("https://jsonplaceholder.typicode.com/todos") + todos.raise_for_status() + + # for brevity, we'll limit to the first 10 only + return {"todos": todos.json()[:10]} + + + @logger.inject_lambda_context + def lambda_handler(event, context): + return app.resolve(event, context) + ``` + """ + + def __init__( + self, + inbound_schema: dict, + inbound_formats: dict | None = None, + outbound_schema: dict | None = None, + outbound_formats: dict | None = None, + ): + """See [Validation utility](https://docs.powertools.aws.dev/lambda/python/latest/utilities/validation/) docs for examples on all parameters. + + Parameters + ---------- + inbound_schema : dict + JSON Schema to validate incoming event + inbound_formats : dict | None, optional + Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool, by default None + JSON Schema to validate outbound event, by default None + outbound_formats : dict | None, optional + Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool, by default None + """ # noqa: E501 + super().__init__() + self.inbound_schema = inbound_schema + self.inbound_formats = inbound_formats + self.outbound_schema = outbound_schema + self.outbound_formats = outbound_formats + + def bad_response(self, error: SchemaValidationError) -> Response: + message: str = f"Bad Response: {error.message}" + logger.debug(message) + raise BadRequestError(message) + + def bad_request(self, error: SchemaValidationError) -> Response: + message: str = f"Bad Request: {error.message}" + logger.debug(message) + raise BadRequestError(message) + + def bad_config(self, error: InvalidSchemaFormatError) -> Response: + logger.debug(f"Invalid Schema Format: {error}") + raise InternalServerError("Internal Server Error") + + def handler(self, app: EventHandlerInstance, next_middleware: NextMiddleware) -> Response: + """Validates incoming JSON payload (body) against JSON Schema provided. + + Parameters + ---------- + app : EventHandlerInstance + An instance of an Event Handler + next_middleware : NextMiddleware + Callable to get response from the next middleware or route handler in the chain + + Returns + ------- + Response + It can return three types of response objects + + - Original response: Propagates HTTP response returned from the next middleware if validation succeeds + - HTTP 400: Payload or response failed JSON Schema validation + - HTTP 500: JSON Schema provided has incorrect format + """ + try: + validate(event=app.current_event.json_body, schema=self.inbound_schema, formats=self.inbound_formats) + except SchemaValidationError as error: + return self.bad_request(error) + except InvalidSchemaFormatError as error: + return self.bad_config(error) + + result = next_middleware(app) + + if self.outbound_formats is not None: + try: + validate(event=result.body, schema=self.inbound_schema, formats=self.inbound_formats) + except SchemaValidationError as error: + return self.bad_response(error) + except InvalidSchemaFormatError as error: + return self.bad_config(error) + + return result diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/__init__.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/compat.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..b59e90b1655c278f17aa968075eb41e4d2b71e2b --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/compat.py @@ -0,0 +1,328 @@ +# mypy: ignore-errors +# flake8: noqa +from __future__ import annotations + +from collections import deque +from copy import copy + +# MAINTENANCE: remove when deprecating Pydantic v1. Mypy doesn't handle two different code paths that import different +# versions of a module, so we need to ignore errors here. + +from dataclasses import dataclass, is_dataclass +from enum import Enum +from typing import TYPE_CHECKING, Any, Deque, FrozenSet, List, Mapping, Sequence, Set, Tuple, Union + +from typing_extensions import Annotated, Literal, get_origin, get_args + +from pydantic import BaseModel, create_model +from pydantic.fields import FieldInfo + +from aws_lambda_powertools.event_handler.openapi.types import COMPONENT_REF_PREFIX, UnionType + +from pydantic import TypeAdapter, ValidationError + +# Importing from internal libraries in Pydantic may introduce potential risks, as these internal libraries +# are not part of the public API and may change without notice in future releases. +# We use this for forward reference, as it allows us to handle forward references in type annotations. +from pydantic._internal._typing_extra import eval_type_lenient +from pydantic.fields import FieldInfo +from pydantic._internal._utils import lenient_issubclass +from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue +from pydantic_core import PydanticUndefined, PydanticUndefinedType + +if TYPE_CHECKING: + from aws_lambda_powertools.event_handler.openapi.types import IncEx, ModelNameMap + +Undefined = PydanticUndefined +Required = PydanticUndefined +UndefinedType = PydanticUndefinedType + +evaluate_forwardref = eval_type_lenient + +sequence_annotation_to_type = { + Sequence: list, + List: list, + list: list, + Tuple: tuple, + tuple: tuple, + Set: set, + set: set, + FrozenSet: frozenset, + frozenset: frozenset, + Deque: deque, + deque: deque, +} + +sequence_types = tuple(sequence_annotation_to_type.keys()) + +RequestErrorModel: type[BaseModel] = create_model("Request") + + +class ErrorWrapper(Exception): + pass + + +@dataclass +class ModelField: + field_info: FieldInfo + name: str + mode: Literal["validation", "serialization"] = "validation" + + @property + def alias(self) -> str: + value = self.field_info.alias + return value if value is not None else self.name + + @property + def required(self) -> bool: + return self.field_info.is_required() + + @property + def default(self) -> Any: + return self.get_default() + + @property + def type_(self) -> Any: + return self.field_info.annotation + + def __post_init__(self) -> None: + self._type_adapter: TypeAdapter[Any] = TypeAdapter( + Annotated[self.field_info.annotation, self.field_info], + ) + + def get_default(self) -> Any: + if self.field_info.is_required(): + return Undefined + return self.field_info.get_default(call_default_factory=True) + + def serialize( + self, + value: Any, + *, + mode: Literal["json", "python"] = "json", + include: IncEx | None = None, + exclude: IncEx | None = None, + by_alias: bool = True, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + ) -> Any: + return self._type_adapter.dump_python( + value, + mode=mode, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + def validate( + self, value: Any, values: dict[str, Any] = {}, *, loc: tuple[int | str, ...] = () + ) -> tuple[Any, list[dict[str, Any]] | None]: + try: + return (self._type_adapter.validate_python(value, from_attributes=True), None) + except ValidationError as exc: + return None, _regenerate_error_with_loc(errors=exc.errors(), loc_prefix=loc) + + def __hash__(self) -> int: + # Each ModelField is unique for our purposes + return id(self) + + +def get_schema_from_model_field( + *, + field: ModelField, + model_name_map: ModelNameMap, + field_mapping: dict[ + tuple[ModelField, Literal["validation", "serialization"]], + JsonSchemaValue, + ], +) -> dict[str, Any]: + json_schema = field_mapping[(field, field.mode)] + if "$ref" not in json_schema: + # MAINTENANCE: remove when deprecating Pydantic v1 + # Ref: https://github.com/pydantic/pydantic/blob/d61792cc42c80b13b23e3ffa74bc37ec7c77f7d1/pydantic/schema.py#L207 + json_schema["title"] = field.field_info.title or field.alias.title().replace("_", " ") + return json_schema + + +def get_definitions( + *, + fields: list[ModelField], + schema_generator: GenerateJsonSchema, + model_name_map: ModelNameMap, +) -> tuple[ + dict[ + tuple[ModelField, Literal["validation", "serialization"]], + dict[str, Any], + ], + dict[str, dict[str, Any]], +]: + inputs = [(field, field.mode, field._type_adapter.core_schema) for field in fields] + field_mapping, definitions = schema_generator.generate_definitions(inputs=inputs) + + return field_mapping, definitions + + +def get_compat_model_name_map(fields: list[ModelField]) -> ModelNameMap: + return {} + + +def get_annotation_from_field_info(annotation: Any, field_info: FieldInfo, field_name: str) -> Any: + return annotation + + +def model_rebuild(model: type[BaseModel]) -> None: + model.model_rebuild() + + +def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: + return type(field_info).from_annotation(annotation) + + +def get_missing_field_error(loc: tuple[str, ...]) -> dict[str, Any]: + error = ValidationError.from_exception_data( + "Field required", [{"type": "missing", "loc": loc, "input": {}}] + ).errors()[0] + error["input"] = None + return error + + +def is_scalar_field(field: ModelField) -> bool: + from aws_lambda_powertools.event_handler.openapi.params import Body + + return field_annotation_is_scalar(field.field_info.annotation) and not isinstance(field.field_info, Body) + + +def is_scalar_sequence_field(field: ModelField) -> bool: + return field_annotation_is_scalar_sequence(field.field_info.annotation) + + +def is_sequence_field(field: ModelField) -> bool: + return field_annotation_is_sequence(field.field_info.annotation) + + +def is_bytes_field(field: ModelField) -> bool: + return is_bytes_or_nonable_bytes_annotation(field.type_) + + +def is_bytes_sequence_field(field: ModelField) -> bool: + return is_bytes_sequence_annotation(field.type_) + + +def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: + origin_type = get_origin(field.field_info.annotation) or field.field_info.annotation + if not issubclass(origin_type, sequence_types): # type: ignore[arg-type] + raise AssertionError(f"Expected sequence type, got {origin_type}") + return sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return] + + +def _normalize_errors(errors: Sequence[Any]) -> list[dict[str, Any]]: + return errors # type: ignore[return-value] + + +def create_body_model(*, fields: Sequence[ModelField], model_name: str) -> type[BaseModel]: + field_params = {f.name: (f.field_info.annotation, f.field_info) for f in fields} + model: type[BaseModel] = create_model(model_name, **field_params) + return model + + +def _model_dump(model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any) -> Any: + return model.model_dump(mode=mode, **kwargs) + + +def model_json(model: BaseModel, **kwargs: Any) -> Any: + return model.model_dump_json(**kwargs) + + +# Common code for both versions + + +def field_annotation_is_complex(annotation: type[Any] | None) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + return any(field_annotation_is_complex(arg) for arg in get_args(annotation)) + + return ( + _annotation_is_complex(annotation) + or _annotation_is_complex(origin) + or hasattr(origin, "__pydantic_core_schema__") + or hasattr(origin, "__get_pydantic_core_schema__") + ) + + +def field_annotation_is_scalar(annotation: Any) -> bool: + return annotation is Ellipsis or not field_annotation_is_complex(annotation) + + +def field_annotation_is_sequence(annotation: type[Any] | None) -> bool: + return _annotation_is_sequence(annotation) or _annotation_is_sequence(get_origin(annotation)) + + +def field_annotation_is_scalar_sequence(annotation: type[Any] | None) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + at_least_one_scalar_sequence = False + for arg in get_args(annotation): + if field_annotation_is_scalar_sequence(arg): + at_least_one_scalar_sequence = True + continue + elif not field_annotation_is_scalar(arg): + return False + return at_least_one_scalar_sequence + return field_annotation_is_sequence(annotation) and all( + field_annotation_is_scalar(sub_annotation) for sub_annotation in get_args(annotation) + ) + + +def is_bytes_or_nonable_bytes_annotation(annotation: Any) -> bool: + if lenient_issubclass(annotation, bytes): + return True + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + for arg in get_args(annotation): + if lenient_issubclass(arg, bytes): + return True + return False + + +def is_bytes_sequence_annotation(annotation: Any) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + at_least_one = False + for arg in get_args(annotation): + if is_bytes_sequence_annotation(arg): + at_least_one = True + break + return at_least_one + return field_annotation_is_sequence(annotation) and all( + is_bytes_or_nonable_bytes_annotation(sub_annotation) for sub_annotation in get_args(annotation) + ) + + +def value_is_sequence(value: Any) -> bool: + return isinstance(value, sequence_types) and not isinstance(value, (str, bytes)) # type: ignore[arg-type] + + +def _annotation_is_complex(annotation: type[Any] | None) -> bool: + return ( + lenient_issubclass(annotation, (BaseModel, Mapping)) # TODO: UploadFile + or _annotation_is_sequence(annotation) + or is_dataclass(annotation) + ) + + +def _annotation_is_sequence(annotation: type[Any] | None) -> bool: + if lenient_issubclass(annotation, (str, bytes)): + return False + return lenient_issubclass(annotation, sequence_types) + + +def _regenerate_error_with_loc(*, errors: Sequence[Any], loc_prefix: tuple[str | int, ...]) -> list[dict[str, Any]]: + updated_loc_errors: list[Any] = [ + {**err, "loc": loc_prefix + err.get("loc", ())} for err in _normalize_errors(errors) + ] + + return updated_loc_errors diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/constants.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..f5d72d47f7ee5c1077ac977af65e4b8deca1278e --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/constants.py @@ -0,0 +1,2 @@ +DEFAULT_API_VERSION = "1.0.0" +DEFAULT_OPENAPI_VERSION = "3.1.0" diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/dependant.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/dependant.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f2f822ce1fae9b80e47dfeff0fd136a69925a0 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/dependant.py @@ -0,0 +1,382 @@ +from __future__ import annotations + +import inspect +import re +from typing import TYPE_CHECKING, Any, Callable, ForwardRef, cast + +from aws_lambda_powertools.event_handler.openapi.compat import ( + ModelField, + create_body_model, + evaluate_forwardref, + is_scalar_field, + is_scalar_sequence_field, +) +from aws_lambda_powertools.event_handler.openapi.params import ( + Body, + Dependant, + Header, + Param, + ParamTypes, + Query, + _File, + _Form, + analyze_param, + create_response_field, + get_flat_dependant, +) +from aws_lambda_powertools.event_handler.openapi.types import OpenAPIResponse, OpenAPIResponseContentModel + +if TYPE_CHECKING: + from pydantic import BaseModel + +""" +This turns the opaque function signature into typed, validated models. + +It relies on Pydantic's typing and validation to achieve this in a declarative way. +This enables traits like autocompletion, validation, and declarative structure vs imperative parsing. + +This code parses an OpenAPI operation handler function signature into Pydantic models. It uses inspect to get the +signature and regex to parse path parameters. Each parameter is analyzed to extract its type annotation and generate +a corresponding Pydantic field, which are added to a Dependant model. Return values are handled similarly. + +This modeling allows for type checking, automatic parameter name/location/type extraction, and input validation - +turning the opaque signature into validated models. It relies on Pydantic's typing and validation for a declarative +approach over imperative parsing, enabling autocompletion, validation and structure. +""" + + +def add_param_to_fields( + *, + field: ModelField, + dependant: Dependant, +) -> None: + """ + Adds a parameter to the list of parameters in the dependant model. + + Parameters + ---------- + field: ModelField + The field to add + dependant: Dependant + The dependant model to add the field to + + """ + field_info = cast(Param, field.field_info) + + # Dictionary to map ParamTypes to their corresponding lists in dependant + param_type_map = { + ParamTypes.path: dependant.path_params, + ParamTypes.query: dependant.query_params, + ParamTypes.header: dependant.header_params, + ParamTypes.cookie: dependant.cookie_params, + } + + # Check if field_info.in_ is a valid key in param_type_map and append the field to the corresponding list + # or raise an exception if it's not a valid key. + if field_info.in_ in param_type_map: + param_type_map[field_info.in_].append(field) + else: + raise AssertionError(f"Unsupported param type: {field_info.in_}") + + +def get_typed_annotation(annotation: Any, globalns: dict[str, Any]) -> Any: + """ + Evaluates a type annotation, which can be a string or a ForwardRef. + """ + if isinstance(annotation, str): + annotation = ForwardRef(annotation) + annotation = evaluate_forwardref(annotation, globalns, globalns) + return annotation + + +def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: + """ + Returns a typed signature for a callable, resolving forward references. + + Parameters + ---------- + call: Callable[..., Any] + The callable to get the signature for + + Returns + ------- + inspect.Signature + The typed signature + """ + signature = inspect.signature(call) + + # Gets the global namespace for the call. This is used to resolve forward references. + globalns = getattr(call, "__global__", {}) + + typed_params = [ + inspect.Parameter( + name=param.name, + kind=param.kind, + default=param.default, + annotation=get_typed_annotation(param.annotation, globalns), + ) + for param in signature.parameters.values() + ] + + # If the return annotation is not empty, add it to the signature. + if signature.return_annotation is not inspect.Signature.empty: + return_param = inspect.Parameter( + name="Return", + kind=inspect.Parameter.POSITIONAL_OR_KEYWORD, + default=None, + annotation=get_typed_annotation(signature.return_annotation, globalns), + ) + return inspect.Signature(typed_params, return_annotation=return_param.annotation) + else: + return inspect.Signature(typed_params) + + +def get_path_param_names(path: str) -> set[str]: + """ + Returns the path parameter names from a path template. Those are the strings between { and }. + + Parameters + ---------- + path: str + The path template + + Returns + ------- + set[str] + The path parameter names + + """ + return set(re.findall("{(.*?)}", path)) + + +def get_dependant( + *, + path: str, + call: Callable[..., Any], + name: str | None = None, + responses: dict[int, OpenAPIResponse] | None = None, +) -> Dependant: + """ + Returns a dependant model for a handler function. A dependant model is a model that contains + the parameters and return value of a handler function. + + Parameters + ---------- + path: str + The path template + call: Callable[..., Any] + The handler function + name: str, optional + The name of the handler function + responses: list[dict[int, OpenAPIResponse]], optional + The list of extra responses for the handler function + + Returns + ------- + Dependant + The dependant model for the handler function + """ + path_param_names = get_path_param_names(path) + endpoint_signature = get_typed_signature(call) + signature_params = endpoint_signature.parameters + + dependant = Dependant( + call=call, + name=name, + path=path, + ) + + # Add each parameter to the dependant model + for param_name, param in signature_params.items(): + # If the parameter is a path parameter, we need to set the in_ field to "path". + is_path_param = param_name in path_param_names + + # Analyze the parameter to get the Pydantic field. + param_field = analyze_param( + param_name=param_name, + annotation=param.annotation, + value=param.default, + is_path_param=is_path_param, + is_response_param=False, + ) + if param_field is None: + raise AssertionError(f"Parameter field is None for param: {param_name}") + + if is_body_param(param_field=param_field, is_path_param=is_path_param): + dependant.body_params.append(param_field) + else: + add_param_to_fields(field=param_field, dependant=dependant) + + _add_return_annotation(dependant, endpoint_signature) + _add_extra_responses(dependant, responses) + + return dependant + + +def _add_extra_responses(dependant: Dependant, responses: dict[int, OpenAPIResponse] | None): + # Also add the optional extra responses to the dependant model. + if not responses: + return + + for response in responses.values(): + for schema in response.get("content", {}).values(): + if "model" in schema: + response_field = analyze_param( + param_name="return", + annotation=cast(OpenAPIResponseContentModel, schema)["model"], + value=None, + is_path_param=False, + is_response_param=True, + ) + if response_field is None: + raise AssertionError("Response field is None for response model") + + dependant.response_extra_models.append(response_field) + + +def _add_return_annotation(dependant: Dependant, endpoint_signature: inspect.Signature): + # If the return annotation is not empty, add it to the dependant model. + return_annotation = endpoint_signature.return_annotation + if return_annotation is not inspect.Signature.empty: + param_field = analyze_param( + param_name="return", + annotation=return_annotation, + value=None, + is_path_param=False, + is_response_param=True, + ) + if param_field is None: + raise AssertionError("Param field is None for return annotation") + + dependant.return_param = param_field + + +def is_body_param(*, param_field: ModelField, is_path_param: bool) -> bool: + """ + Returns whether a parameter is a request body parameter, by checking if it is a scalar field or a body field. + + Parameters + ---------- + param_field: ModelField + The parameter field + is_path_param: bool + Whether the parameter is a path parameter + + Returns + ------- + bool + Whether the parameter is a request body parameter + """ + if is_path_param: + if not is_scalar_field(field=param_field): + raise AssertionError("Path params must be of one of the supported types") + return False + elif is_scalar_field(field=param_field): + return False + elif isinstance(param_field.field_info, (Query, Header)) and is_scalar_sequence_field(param_field): + return False + else: + if not isinstance(param_field.field_info, Body): + raise AssertionError(f"Param: {param_field.name} can only be a request body, use Body()") + return True + + +def get_flat_params(dependant: Dependant) -> list[ModelField]: + """ + Get a list of all the parameters from a Dependant object. + + Parameters + ---------- + dependant : Dependant + The Dependant object containing the parameters. + + Returns + ------- + list[ModelField] + A list of ModelField objects containing the flat parameters from the Dependant object. + + """ + flat_dependant = get_flat_dependant(dependant) + return ( + flat_dependant.path_params + + flat_dependant.query_params + + flat_dependant.header_params + + flat_dependant.cookie_params + ) + + +def get_body_field(*, dependant: Dependant, name: str) -> ModelField | None: + """ + Get the Body field for a given Dependant object. + """ + + flat_dependant = get_flat_dependant(dependant) + if not flat_dependant.body_params: + return None + + first_param = flat_dependant.body_params[0] + field_info = first_param.field_info + + # Handle the case where there is only one body parameter and it is embedded + embed = getattr(field_info, "embed", None) + body_param_names_set = {param.name for param in flat_dependant.body_params} + if len(body_param_names_set) == 1 and not embed: + return first_param + + # If one field requires to embed, all have to be embedded + for param in flat_dependant.body_params: + setattr(param.field_info, "embed", True) # noqa: B010 + + # Generate a custom body model for this endpoint + model_name = "Body_" + name + body_model = create_body_model(fields=flat_dependant.body_params, model_name=model_name) + + required = any(True for f in flat_dependant.body_params if f.required) + + body_field_info, body_field_info_kwargs = get_body_field_info( + body_model=body_model, + flat_dependant=flat_dependant, + required=required, + ) + + final_field = create_response_field( + name="body", + type_=body_model, + required=required, + alias="body", + field_info=body_field_info(**body_field_info_kwargs), + ) + return final_field + + +def get_body_field_info( + *, + body_model: type[BaseModel], + flat_dependant: Dependant, + required: bool, +) -> tuple[type[Body], dict[str, Any]]: + """ + Get the Body field info and kwargs for a given body model. + """ + + body_field_info_kwargs: dict[str, Any] = {"annotation": body_model, "alias": "body"} + + if not required: + body_field_info_kwargs["default"] = None + + if any(isinstance(f.field_info, _File) for f in flat_dependant.body_params): + # MAINTENANCE: body_field_info: type[Body] = _File + raise NotImplementedError("_File fields are not supported in request bodies") + elif any(isinstance(f.field_info, _Form) for f in flat_dependant.body_params): + # MAINTENANCE: body_field_info: type[Body] = _Form + raise NotImplementedError("_Form fields are not supported in request bodies") + else: + body_field_info = Body + + body_param_media_types = [ + f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, Body) + ] + if len(set(body_param_media_types)) == 1: + body_field_info_kwargs["media_type"] = body_param_media_types[0] + + return body_field_info, body_field_info_kwargs diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/encoders.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/encoders.py new file mode 100644 index 0000000000000000000000000000000000000000..b62ecb856ed97d16cccc78c956fb3de08e8a933b --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/encoders.py @@ -0,0 +1,377 @@ +from __future__ import annotations + +import dataclasses +import datetime +from collections import defaultdict, deque +from decimal import Decimal +from enum import Enum +from pathlib import Path, PurePath +from re import Pattern +from types import GeneratorType +from typing import TYPE_CHECKING, Any, Callable +from uuid import UUID + +from pydantic import BaseModel +from pydantic.types import SecretBytes, SecretStr + +from aws_lambda_powertools.event_handler.openapi.compat import _model_dump + +if TYPE_CHECKING: + from aws_lambda_powertools.event_handler.openapi.types import IncEx + +from aws_lambda_powertools.event_handler.openapi.exceptions import SerializationError + +""" +This module contains the encoders used by jsonable_encoder to convert Python objects to JSON serializable data types. +""" + + +def jsonable_encoder( # noqa: PLR0911 + obj: Any, + include: IncEx | None = None, + exclude: IncEx | None = None, + by_alias: bool = True, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + custom_serializer: Callable[[Any], str] | None = None, +) -> Any: + """ + JSON encodes an arbitrary Python object into JSON serializable data types. + + This is a modified version of fastapi.encoders.jsonable_encoder that supports + encoding of pydantic.BaseModel objects. + + Parameters + ---------- + obj : Any + The object to encode + include : IncEx | None, optional + A set or dictionary of strings that specifies which properties should be included, by default None, + meaning everything is included + exclude : IncEx | None, optional + A set or dictionary of strings that specifies which properties should be excluded, by default None, + meaning nothing is excluded + by_alias : bool, optional + Whether field aliases should be respected, by default True + exclude_unset : bool, optional + Whether fields that are not set should be excluded, by default False + exclude_defaults : bool, optional + Whether fields that are equal to their default value (as specified in the model) should be excluded, + by default False + exclude_none : bool, optional + Whether fields that are equal to None should be excluded, by default False + custom_serializer : Callable, optional + A custom serializer to use for encoding the object, when everything else fails. + + Returns + ------- + Any + The JSON serializable data types + """ + if include is not None and not isinstance(include, (set, dict)): + include = set(include) + if exclude is not None and not isinstance(exclude, (set, dict)): + exclude = set(exclude) + + try: + # Pydantic models + if isinstance(obj, BaseModel): + return _dump_base_model( + obj=obj, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_none=exclude_none, + exclude_defaults=exclude_defaults, + ) + + # Dataclasses + if dataclasses.is_dataclass(obj): + obj_dict = dataclasses.asdict(obj) # type: ignore[arg-type] + return jsonable_encoder( + obj_dict, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + custom_serializer=custom_serializer, + ) + + # Enums + if isinstance(obj, Enum): + return obj.value + + # Paths + if isinstance(obj, PurePath): + return str(obj) + + # Scalars + if isinstance(obj, (str, int, float, type(None))): + return obj + + # Dictionaries + if isinstance(obj, dict): + return _dump_dict( + obj=obj, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_none=exclude_none, + custom_serializer=custom_serializer, + ) + + # Sequences + if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)): + return _dump_sequence( + obj=obj, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_none=exclude_none, + exclude_defaults=exclude_defaults, + exclude_unset=exclude_unset, + custom_serializer=custom_serializer, + ) + + # Other types + if type(obj) in ENCODERS_BY_TYPE: + return ENCODERS_BY_TYPE[type(obj)](obj) + + for encoder, classes_tuple in encoders_by_class_tuples.items(): + if isinstance(obj, classes_tuple): + return encoder(obj) + + # Use custom serializer if present + if custom_serializer: + return custom_serializer(obj) + + # Default + return _dump_other( + obj=obj, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_none=exclude_none, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + custom_serializer=custom_serializer, + ) + except ValueError as exc: + raise SerializationError( + f"Unable to serialize the object {obj} as it is not a supported type. Error details: {exc}", + "See: https://docs.powertools.aws.dev/lambda/python/latest/core/event_handler/api_gateway/#serializing-objects", + ) from exc + + +def _dump_base_model( + *, + obj: Any, + include: IncEx | None = None, + exclude: IncEx | None = None, + by_alias: bool = True, + exclude_unset: bool = False, + exclude_none: bool = False, + exclude_defaults: bool = False, +): + """ + Dump a BaseModel object to a dict, using the same parameters as jsonable_encoder + """ + obj_dict = _model_dump( + obj, + mode="json", + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_none=exclude_none, + exclude_defaults=exclude_defaults, + ) + if "__root__" in obj_dict: + obj_dict = obj_dict["__root__"] + + return jsonable_encoder( + obj_dict, + exclude_none=exclude_none, + exclude_defaults=exclude_defaults, + ) + + +def _dump_dict( + *, + obj: Any, + include: IncEx | None = None, + exclude: IncEx | None = None, + by_alias: bool = True, + exclude_unset: bool = False, + exclude_none: bool = False, + custom_serializer: Callable[[Any], str] | None = None, +) -> dict[str, Any]: + """ + Dump a dict to a dict, using the same parameters as jsonable_encoder + + Parameters + ---------- + custom_serializer : Callable, optional + A custom serializer to use for encoding the object, when everything else fails. + """ + encoded_dict = {} + allowed_keys = set(obj.keys()) + if include is not None: + allowed_keys &= set(include) + if exclude is not None: + allowed_keys -= set(exclude) + for key, value in obj.items(): + if ( + (not isinstance(key, str) or not key.startswith("_sa")) + and (value is not None or not exclude_none) + and key in allowed_keys + ): + encoded_key = jsonable_encoder( + key, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_none=exclude_none, + custom_serializer=custom_serializer, + ) + encoded_value = jsonable_encoder( + value, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_none=exclude_none, + custom_serializer=custom_serializer, + ) + encoded_dict[encoded_key] = encoded_value + return encoded_dict + + +def _dump_sequence( + *, + obj: Any, + include: IncEx | None = None, + exclude: IncEx | None = None, + by_alias: bool = True, + exclude_unset: bool = False, + exclude_none: bool = False, + exclude_defaults: bool = False, + custom_serializer: Callable[[Any], str] | None = None, +) -> list[Any]: + """ + Dump a sequence to a list, using the same parameters as jsonable_encoder. + """ + encoded_list = [] + for item in obj: + encoded_list.append( + jsonable_encoder( + item, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + custom_serializer=custom_serializer, + ), + ) + return encoded_list + + +def _dump_other( + *, + obj: Any, + include: IncEx | None = None, + exclude: IncEx | None = None, + by_alias: bool = True, + exclude_unset: bool = False, + exclude_none: bool = False, + exclude_defaults: bool = False, + custom_serializer: Callable[[Any], str] | None = None, +) -> Any: + """ + Dump an object to a hashable object, using the same parameters as jsonable_encoder + """ + try: + data = dict(obj) + except Exception as e: + errors: list[Exception] = [e] + try: + data = vars(obj) + except Exception as e: + errors.append(e) + raise ValueError(errors) from e + return jsonable_encoder( + data, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + custom_serializer=custom_serializer, + ) + + +def iso_format(o: datetime.date | datetime.time) -> str: + """ + ISO format for date and time + """ + return o.isoformat() + + +def decimal_encoder(dec_value: Decimal) -> int | float: + """ + Encodes a Decimal as int of there's no exponent, otherwise float + + This is useful when we use ConstrainedDecimal to represent Numeric(x,0) + where an integer (but not int typed) is used. Encoding this as a float + results in failed round-tripping between encode and parse. + + >>> decimal_encoder(Decimal("1.0")) + 1.0 + + >>> decimal_encoder(Decimal("1")) + 1 + """ + if dec_value.as_tuple().exponent >= 0: # type: ignore[operator] + return int(dec_value) + else: + return float(dec_value) + + +# Encoders for types that are not JSON serializable +ENCODERS_BY_TYPE: dict[type[Any], Callable[[Any], Any]] = { + bytes: lambda o: o.decode(), + datetime.date: iso_format, + datetime.datetime: iso_format, + datetime.time: iso_format, + datetime.timedelta: lambda td: td.total_seconds(), + Decimal: decimal_encoder, + Enum: lambda o: o.value, + frozenset: list, + deque: list, + GeneratorType: list, + Path: str, + Pattern: lambda o: o.pattern, + SecretBytes: str, + SecretStr: str, + set: list, + UUID: str, +} + + +# Generates a mapping of encoders to a tuple of classes that they can encode +def generate_encoders_by_class_tuples( + type_encoder_map: dict[Any, Callable[[Any], Any]], +) -> dict[Callable[[Any], Any], tuple[Any, ...]]: + encoders: dict[Callable[[Any], Any], tuple[Any, ...]] = defaultdict(tuple) + for type_, encoder in type_encoder_map.items(): + encoders[encoder] += (type_,) + return encoders + + +# Mapping of encoders to a tuple of classes that they can encode +encoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE) diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/exceptions.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e1ed33e67fddc7bc5c03f10432788a084b48173f --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/exceptions.py @@ -0,0 +1,35 @@ +from typing import Any, Sequence + + +class ValidationException(Exception): + """ + Base exception for all validation errors + """ + + def __init__(self, errors: Sequence[Any]) -> None: + self._errors = errors + + def errors(self) -> Sequence[Any]: + return self._errors + + +class RequestValidationError(ValidationException): + """ + Raised when the request body does not match the OpenAPI schema + """ + + def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None: + super().__init__(errors) + self.body = body + + +class SerializationError(Exception): + """ + Base exception for all encoding errors + """ + + +class SchemaValidationError(ValidationException): + """ + Raised when the OpenAPI schema validation fails + """ diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/models.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/models.py new file mode 100644 index 0000000000000000000000000000000000000000..afeb0a77750cbd0b4aec6f3c81adf85f5a82592c --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/models.py @@ -0,0 +1,487 @@ +# ruff: noqa: FA100 +from enum import Enum +from typing import Any, Dict, List, Literal, Optional, Set, Union + +from pydantic import AnyUrl, BaseModel, ConfigDict, Field, model_validator +from typing_extensions import Annotated + +from aws_lambda_powertools.event_handler.openapi.compat import model_rebuild +from aws_lambda_powertools.event_handler.openapi.exceptions import SchemaValidationError + +MODEL_CONFIG_ALLOW = ConfigDict(extra="allow") +MODEL_CONFIG_IGNORE = ConfigDict(extra="ignore") + +""" +The code defines Pydantic models for the various OpenAPI objects like OpenAPI, PathItem, Operation, Parameter etc. +These models can be used to parse OpenAPI JSON/YAML files into Python objects, or generate OpenAPI from Python data. +""" + + +class OpenAPIExtensions(BaseModel): + """ + This class serves as a Pydantic proxy model to add OpenAPI extensions. + + OpenAPI extensions are arbitrary fields, so we remove openapi_extensions when dumping + and add only the provided value in the schema. + """ + + openapi_extensions: Optional[Dict[str, Any]] = None + + # If the 'openapi_extensions' field is present in the 'values' dictionary, + # And if the extension starts with x- (must respect the RFC) + # update the 'values' dictionary with the contents of 'openapi_extensions', + # and then remove the 'openapi_extensions' field from the 'values' dictionary + model_config = {"extra": "allow"} + + @model_validator(mode="before") + def serialize_openapi_extension_v2(self): + if isinstance(self, dict) and self.get("openapi_extensions"): + + openapi_extension_value = self.get("openapi_extensions") + + for extension_key in openapi_extension_value: + if not str(extension_key).startswith("x-"): + raise SchemaValidationError("An OpenAPI extension key must start with x-") + + self.update(openapi_extension_value) + self.pop("openapi_extensions", None) + + return self + + +# https://swagger.io/specification/#contact-object +class Contact(BaseModel): + name: Optional[str] = None + url: Optional[AnyUrl] = None + email: Optional[str] = None + + model_config = MODEL_CONFIG_ALLOW + + +# https://swagger.io/specification/#license-object +class License(BaseModel): + name: str + identifier: Optional[str] = None + url: Optional[AnyUrl] = None + + model_config = MODEL_CONFIG_ALLOW + + +# https://swagger.io/specification/#info-object +class Info(BaseModel): + title: str + description: Optional[str] = None + termsOfService: Optional[str] = None + contact: Optional[Contact] = None + license: Optional[License] = None # noqa: A003 + version: str + summary: Optional[str] = None + + model_config = MODEL_CONFIG_IGNORE + + +# https://swagger.io/specification/#server-variable-object +class ServerVariable(BaseModel): + enum: Annotated[Optional[List[str]], Field(min_length=1)] = None + default: str + description: Optional[str] = None + + model_config = MODEL_CONFIG_ALLOW + + +# https://swagger.io/specification/#server-object +class Server(OpenAPIExtensions): + url: Union[AnyUrl, str] + description: Optional[str] = None + variables: Optional[Dict[str, ServerVariable]] = None + + model_config = MODEL_CONFIG_ALLOW + + +# https://swagger.io/specification/#reference-object +class Reference(BaseModel): + ref: str = Field(alias="$ref") + + +# https://swagger.io/specification/#discriminator-object +class Discriminator(BaseModel): + propertyName: str + mapping: Optional[Dict[str, str]] = None + + +# https://swagger.io/specification/#xml-object +class XML(BaseModel): + name: Optional[str] = None + namespace: Optional[str] = None + prefix: Optional[str] = None + attribute: Optional[bool] = None + wrapped: Optional[bool] = None + + model_config = MODEL_CONFIG_ALLOW + + +# https://swagger.io/specification/#external-documentation-object +class ExternalDocumentation(BaseModel): + description: Optional[str] = None + url: AnyUrl + + model_config = MODEL_CONFIG_ALLOW + + +# https://swagger.io/specification/#schema-object +class Schema(BaseModel): + # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-the-json-schema-core-vocabu + # Core Vocabulary + schema_: Optional[str] = Field(default=None, alias="$schema") + vocabulary: Optional[str] = Field(default=None, alias="$vocabulary") + id: Optional[str] = Field(default=None, alias="$id") # noqa: A003 + anchor: Optional[str] = Field(default=None, alias="$anchor") + dynamicAnchor: Optional[str] = Field(default=None, alias="$dynamicAnchor") + ref: Optional[str] = Field(default=None, alias="$ref") + dynamicRef: Optional[str] = Field(default=None, alias="$dynamicRef") + defs: Optional[Dict[str, "SchemaOrBool"]] = Field(default=None, alias="$defs") + comment: Optional[str] = Field(default=None, alias="$comment") + # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-a-vocabulary-for-applying-s + # A Vocabulary for Applying Subschemas + allOf: Optional[List["SchemaOrBool"]] = None + anyOf: Optional[List["SchemaOrBool"]] = None + oneOf: Optional[List["SchemaOrBool"]] = None + not_: Optional["SchemaOrBool"] = Field(default=None, alias="not") + if_: Optional["SchemaOrBool"] = Field(default=None, alias="if") + then: Optional["SchemaOrBool"] = None + else_: Optional["SchemaOrBool"] = Field(default=None, alias="else") + dependentSchemas: Optional[Dict[str, "SchemaOrBool"]] = None + prefixItems: Optional[List["SchemaOrBool"]] = None + # MAINTENANCE: uncomment and remove below when deprecating Pydantic v1 + # MAINTENANCE: It generates a list of schemas for tuples, before prefixItems was available + # MAINTENANCE: items: Optional["SchemaOrBool"] = None + items: Optional[Union["SchemaOrBool", List["SchemaOrBool"]]] = None + contains: Optional["SchemaOrBool"] = None + properties: Optional[Dict[str, "SchemaOrBool"]] = None + patternProperties: Optional[Dict[str, "SchemaOrBool"]] = None + additionalProperties: Optional["SchemaOrBool"] = None + propertyNames: Optional["SchemaOrBool"] = None + unevaluatedItems: Optional["SchemaOrBool"] = None + unevaluatedProperties: Optional["SchemaOrBool"] = None + # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-structural + # A Vocabulary for Structural Validation + type: Optional[str] = None # noqa: A003 + enum: Optional[List[Any]] = None + const: Optional[Any] = None + multipleOf: Optional[float] = Field(default=None, gt=0) + maximum: Optional[float] = None + exclusiveMaximum: Optional[float] = None + minimum: Optional[float] = None + exclusiveMinimum: Optional[float] = None + maxLength: Optional[int] = Field(default=None, ge=0) + minLength: Optional[int] = Field(default=None, ge=0) + pattern: Optional[str] = None + maxItems: Optional[int] = Field(default=None, ge=0) + minItems: Optional[int] = Field(default=None, ge=0) + uniqueItems: Optional[bool] = None + maxContains: Optional[int] = Field(default=None, ge=0) + minContains: Optional[int] = Field(default=None, ge=0) + maxProperties: Optional[int] = Field(default=None, ge=0) + minProperties: Optional[int] = Field(default=None, ge=0) + required: Optional[List[str]] = None + dependentRequired: Optional[Dict[str, Set[str]]] = None + # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-vocabularies-for-semantic-c + # Vocabularies for Semantic Content With "format" + format: Optional[str] = None # noqa: A003 + # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-the-conten + # A Vocabulary for the Contents of String-Encoded Data + contentEncoding: Optional[str] = None + contentMediaType: Optional[str] = None + contentSchema: Optional["SchemaOrBool"] = None + # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-basic-meta + # A Vocabulary for Basic Meta-Data Annotations + title: Optional[str] = None + description: Optional[str] = None + default: Optional[Any] = None + deprecated: Optional[bool] = None + readOnly: Optional[bool] = None + writeOnly: Optional[bool] = None + examples: Optional[List[Any]] = None + # Ref: OpenAPI 3.0.0: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#schema-object + # Schema Object + discriminator: Optional[Discriminator] = None + xml: Optional[XML] = None + externalDocs: Optional[ExternalDocumentation] = None + + model_config = MODEL_CONFIG_ALLOW + + +# Ref: https://json-schema.org/draft/2020-12/json-schema-core.html#name-json-schema-documents +# A JSON Schema MUST be an object or a boolean. +SchemaOrBool = Union[Schema, bool] + + +# https://swagger.io/specification/#example-object +class Example(BaseModel): + summary: Optional[str] = None + description: Optional[str] = None + value: Optional[Any] = None + externalValue: Optional[AnyUrl] = None + + model_config = MODEL_CONFIG_ALLOW + + +class ParameterInType(Enum): + query = "query" + header = "header" + path = "path" + cookie = "cookie" + + +# https://swagger.io/specification/#encoding-object +class Encoding(BaseModel): + contentType: Optional[str] = None + headers: Optional[Dict[str, Union["Header", Reference]]] = None + style: Optional[str] = None + explode: Optional[bool] = None + allowReserved: Optional[bool] = None + + model_config = MODEL_CONFIG_ALLOW + + +# https://swagger.io/specification/#media-type-object +class MediaType(BaseModel): + schema_: Optional[Union[Schema, Reference]] = Field(default=None, alias="schema") + examples: Optional[Dict[str, Union[Example, Reference]]] = None + encoding: Optional[Dict[str, Encoding]] = None + + model_config = MODEL_CONFIG_ALLOW + + +# https://swagger.io/specification/#parameter-object +class ParameterBase(BaseModel): + description: Optional[str] = None + required: Optional[bool] = None + deprecated: Optional[bool] = None + # Serialization rules for simple scenarios + style: Optional[str] = None + explode: Optional[bool] = None + allowReserved: Optional[bool] = None + schema_: Optional[Union[Schema, Reference]] = Field(default=None, alias="schema") + examples: Optional[Dict[str, Union[Example, Reference]]] = None + # Serialization rules for more complex scenarios + content: Optional[Dict[str, MediaType]] = None + + model_config = MODEL_CONFIG_ALLOW + + +class Parameter(ParameterBase): + name: str + in_: ParameterInType = Field(alias="in") + + +class Header(ParameterBase): + pass + + +# https://swagger.io/specification/#request-body-object +class RequestBody(BaseModel): + description: Optional[str] = None + content: Dict[str, MediaType] + required: Optional[bool] = None + + model_config = MODEL_CONFIG_ALLOW + + +# https://swagger.io/specification/#link-object +class Link(BaseModel): + operationRef: Optional[str] = None + operationId: Optional[str] = None + parameters: Optional[Dict[str, Union[Any, str]]] = None + requestBody: Optional[Union[Any, str]] = None + description: Optional[str] = None + server: Optional[Server] = None + + model_config = MODEL_CONFIG_ALLOW + + +# https://swagger.io/specification/#response-object +class Response(BaseModel): + description: str + headers: Optional[Dict[str, Union[Header, Reference]]] = None + content: Optional[Dict[str, MediaType]] = None + links: Optional[Dict[str, Union[Link, Reference]]] = None + + model_config = MODEL_CONFIG_ALLOW + + +# https://swagger.io/specification/#tag-object +class Tag(BaseModel): + name: str + description: Optional[str] = None + externalDocs: Optional[ExternalDocumentation] = None + + model_config = MODEL_CONFIG_ALLOW + + +# https://swagger.io/specification/#operation-object +class Operation(OpenAPIExtensions): + tags: Optional[List[str]] = None + summary: Optional[str] = None + description: Optional[str] = None + externalDocs: Optional[ExternalDocumentation] = None + operationId: Optional[str] = None + parameters: Optional[List[Union[Parameter, Reference]]] = None + requestBody: Optional[Union[RequestBody, Reference]] = None + # Using Any for Specification Extensions + responses: Optional[Dict[int, Union[Response, Any]]] = None + callbacks: Optional[Dict[str, Union[Dict[str, "PathItem"], Reference]]] = None + deprecated: Optional[bool] = None + security: Optional[List[Dict[str, List[str]]]] = None + servers: Optional[List[Server]] = None + + model_config = MODEL_CONFIG_ALLOW + + +# https://swagger.io/specification/#path-item-object +class PathItem(BaseModel): + ref: Optional[str] = Field(default=None, alias="$ref") + summary: Optional[str] = None + description: Optional[str] = None + get: Optional[Operation] = None + put: Optional[Operation] = None + post: Optional[Operation] = None + delete: Optional[Operation] = None + options: Optional[Operation] = None + head: Optional[Operation] = None + patch: Optional[Operation] = None + trace: Optional[Operation] = None + servers: Optional[List[Server]] = None + parameters: Optional[List[Union[Parameter, Reference]]] = None + + model_config = MODEL_CONFIG_ALLOW + + +# https://swagger.io/specification/#security-scheme-object +class SecuritySchemeType(Enum): + apiKey = "apiKey" + http = "http" + oauth2 = "oauth2" + openIdConnect = "openIdConnect" + mutualTLS = "mutualTLS" + + +class SecurityBase(OpenAPIExtensions): + type_: SecuritySchemeType = Field(alias="type") + description: Optional[str] = None + + model_config = {"extra": "allow", "populate_by_name": True} + + +class APIKeyIn(Enum): + query = "query" + header = "header" + cookie = "cookie" + + +class APIKey(SecurityBase): + type_: SecuritySchemeType = Field(default=SecuritySchemeType.apiKey, alias="type") + in_: APIKeyIn = Field(alias="in") + name: str + + +class HTTPBase(SecurityBase): + type_: SecuritySchemeType = Field(default=SecuritySchemeType.http, alias="type") + scheme: str + + +class HTTPBearer(HTTPBase): # type: ignore[override] + scheme: Literal["bearer"] = "bearer" + bearerFormat: Optional[str] = None + + +class OAuthFlow(BaseModel): + refreshUrl: Optional[str] = None + scopes: Dict[str, str] = {} + + model_config = MODEL_CONFIG_ALLOW + + +class OAuthFlowImplicit(OAuthFlow): + authorizationUrl: str + + +class OAuthFlowPassword(OAuthFlow): + tokenUrl: str + + +class OAuthFlowClientCredentials(OAuthFlow): + tokenUrl: str + + +class OAuthFlowAuthorizationCode(OAuthFlow): + authorizationUrl: str + tokenUrl: str + + +class OAuthFlows(BaseModel): + implicit: Optional[OAuthFlowImplicit] = None + password: Optional[OAuthFlowPassword] = None + clientCredentials: Optional[OAuthFlowClientCredentials] = None + authorizationCode: Optional[OAuthFlowAuthorizationCode] = None + + model_config = MODEL_CONFIG_ALLOW + + +class OAuth2(SecurityBase): + type_: SecuritySchemeType = Field(default=SecuritySchemeType.oauth2, alias="type") + flows: OAuthFlows + + +class OpenIdConnect(SecurityBase): + type_: SecuritySchemeType = Field( + default=SecuritySchemeType.openIdConnect, + alias="type", + ) + openIdConnectUrl: str + + +class MutualTLS(SecurityBase): + type_: SecuritySchemeType = Field(default=SecuritySchemeType.mutualTLS, alias="type") + + +SecurityScheme = Union[APIKey, HTTPBase, OAuth2, OpenIdConnect, HTTPBearer, MutualTLS] + + +# https://swagger.io/specification/#components-object +class Components(BaseModel): + schemas: Optional[Dict[str, Union[Schema, Reference]]] = None + responses: Optional[Dict[str, Union[Response, Reference]]] = None + parameters: Optional[Dict[str, Union[Parameter, Reference]]] = None + examples: Optional[Dict[str, Union[Example, Reference]]] = None + requestBodies: Optional[Dict[str, Union[RequestBody, Reference]]] = None + headers: Optional[Dict[str, Union[Header, Reference]]] = None + securitySchemes: Optional[Dict[str, Union[SecurityScheme, Reference]]] = None + links: Optional[Dict[str, Union[Link, Reference]]] = None + # Using Any for Specification Extensions + callbacks: Optional[Dict[str, Union[Dict[str, PathItem], Reference, Any]]] = None + pathItems: Optional[Dict[str, Union[PathItem, Reference]]] = None + + model_config = MODEL_CONFIG_ALLOW + + +# https://swagger.io/specification/#openapi-object +class OpenAPI(OpenAPIExtensions): + openapi: str + info: Info + jsonSchemaDialect: Optional[str] = None + servers: Optional[List[Server]] = None + # Using Any for Specification Extensions + paths: Optional[Dict[str, Union[PathItem, Any]]] = None + webhooks: Optional[Dict[str, Union[PathItem, Reference]]] = None + components: Optional[Components] = None + security: Optional[List[Dict[str, List[str]]]] = None + tags: Optional[List[Tag]] = None + externalDocs: Optional[ExternalDocumentation] = None + + model_config = MODEL_CONFIG_ALLOW + + +model_rebuild(Schema) +model_rebuild(Operation) +model_rebuild(Encoding) diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/params.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/params.py new file mode 100644 index 0000000000000000000000000000000000000000..ffcef8b50962b9e603e61315401ec9546a7ca7d4 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/params.py @@ -0,0 +1,1086 @@ +from __future__ import annotations + +import inspect +from enum import Enum +from typing import TYPE_CHECKING, Any, Callable, Literal + +from pydantic import BaseConfig +from pydantic.fields import FieldInfo +from typing_extensions import Annotated, get_args, get_origin + +from aws_lambda_powertools.event_handler import Response +from aws_lambda_powertools.event_handler.openapi.compat import ( + ModelField, + Required, + Undefined, + UndefinedType, + copy_field_info, + field_annotation_is_scalar, + get_annotation_from_field_info, +) + +if TYPE_CHECKING: + from aws_lambda_powertools.event_handler.openapi.types import CacheKey + +""" +This turns the low-level function signature into typed, validated Pydantic models for consumption. +""" + + +class ParamTypes(Enum): + query = "query" + header = "header" + path = "path" + cookie = "cookie" + + +# MAINTENANCE: update when deprecating Pydantic v1, remove this alias +_Unset: Any = Undefined + + +class Dependant: + """ + A class used internally to represent a dependency between path operation decorators and the path operation function. + """ + + def __init__( + self, + *, + path_params: list[ModelField] | None = None, + query_params: list[ModelField] | None = None, + header_params: list[ModelField] | None = None, + cookie_params: list[ModelField] | None = None, + body_params: list[ModelField] | None = None, + return_param: ModelField | None = None, + response_extra_models: list[ModelField] | None = None, + name: str | None = None, + call: Callable[..., Any] | None = None, + request_param_name: str | None = None, + websocket_param_name: str | None = None, + http_connection_param_name: str | None = None, + response_param_name: str | None = None, + background_tasks_param_name: str | None = None, + path: str | None = None, + ) -> None: + self.path_params = path_params or [] + self.query_params = query_params or [] + self.header_params = header_params or [] + self.cookie_params = cookie_params or [] + self.body_params = body_params or [] + self.return_param = return_param or None + self.response_extra_models = response_extra_models or [] + self.request_param_name = request_param_name + self.websocket_param_name = websocket_param_name + self.http_connection_param_name = http_connection_param_name + self.response_param_name = response_param_name + self.background_tasks_param_name = background_tasks_param_name + self.name = name + self.call = call + # Store the path to be able to re-generate a dependable from it in overrides + self.path = path + # Save the cache key at creation to optimize performance + self.cache_key: CacheKey = self.call + + +class Param(FieldInfo): + """ + A class used internally to represent a parameter in a path operation. + """ + + in_: ParamTypes + + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Callable[[], Any] | None = _Unset, + annotation: Any | None = None, + alias: str | None = None, + alias_priority: int | None = _Unset, + # MAINTENANCE: update when deprecating Pydantic v1, import these types + # MAINTENANCE: validation_alias: str | AliasPath | AliasChoices | None + validation_alias: str | None = None, + serialization_alias: str | None = None, + title: str | None = None, + description: str | None = None, + gt: float | None = None, + ge: float | None = None, + lt: float | None = None, + le: float | None = None, + min_length: int | None = None, + max_length: int | None = None, + pattern: str | None = None, + discriminator: str | None = None, + strict: bool | None = _Unset, + multiple_of: float | None = _Unset, + allow_inf_nan: bool | None = _Unset, + max_digits: int | None = _Unset, + decimal_places: int | None = _Unset, + examples: list[Any] | None = None, + deprecated: bool | None = None, + include_in_schema: bool = True, + json_schema_extra: dict[str, Any] | None = None, + **extra: Any, + ): + """ + Constructs a new Param. + + Parameters + ---------- + default: Any + The default value of the parameter + default_factory: Callable[[], Any], optional + Callable that will be called when a default value is needed for this field + annotation: Any, optional + The type annotation of the parameter + alias: str, optional + The public name of the field + alias_priority: int, optional + Priority of the alias. This affects whether an alias generator is used + validation_alias: str | AliasPath | AliasChoices | None, optional + Alias to be used for validation only + serialization_alias: str | AliasPath | AliasChoices | None, optional + Alias to be used for serialization only + title: str, optional + The title of the parameter + description: str, optional + The description of the parameter + gt: float, optional + Only applies to numbers, required the field to be "greater than" + ge: float, optional + Only applies to numbers, required the field to be "greater than or equal" + lt: float, optional + Only applies to numbers, required the field to be "less than" + le: float, optional + Only applies to numbers, required the field to be "less than or equal" + min_length: int, optional + Only applies to strings, required the field to have a minimum length + max_length: int, optional + Only applies to strings, required the field to have a maximum length + pattern: str, optional + Only applies to strings, requires the field match against a regular expression pattern string + discriminator: str, optional + Parameter field name for discriminating the type in a tagged union + strict: bool, optional + Enables Pydantic's strict mode for the field + multiple_of: float, optional + Only applies to numbers, requires the field to be a multiple of the given value + allow_inf_nan: bool, optional + Only applies to numbers, requires the field to allow infinity and NaN values + max_digits: int, optional + Only applies to Decimals, requires the field to have a maxmium number of digits within the decimal. + decimal_places: int, optional + Only applies to Decimals, requires the field to have at most a number of decimal places + examples: list[Any], optional + A list of examples for the parameter + deprecated: bool, optional + If `True`, the parameter will be marked as deprecated + include_in_schema: bool, optional + If `False`, the parameter will be excluded from the generated OpenAPI schema + json_schema_extra: dict[str, Any], optional + Extra values to include in the generated OpenAPI schema + """ + self.deprecated = deprecated + self.include_in_schema = include_in_schema + + kwargs = dict( + default=default, + default_factory=default_factory, + alias=alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + discriminator=discriminator, + multiple_of=multiple_of, + allow_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + **extra, + ) + if examples is not None: + kwargs["examples"] = examples + + current_json_schema_extra = json_schema_extra or extra + + kwargs.update( + { + "annotation": annotation, + "alias_priority": alias_priority, + "validation_alias": validation_alias, + "serialization_alias": serialization_alias, + "strict": strict, + "json_schema_extra": current_json_schema_extra, + "pattern": pattern, + }, + ) + + use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset} + + super().__init__(**use_kwargs) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.default})" + + +class Path(Param): + """ + A class used internally to represent a path parameter in a path operation. + """ + + in_ = ParamTypes.path + + def __init__( + self, + default: Any = ..., + *, + default_factory: Callable[[], Any] | None = _Unset, + annotation: Any | None = None, + alias: str | None = None, + alias_priority: int | None = _Unset, + # MAINTENANCE: update when deprecating Pydantic v1, import these types + # MAINTENANCE: validation_alias: str | AliasPath | AliasChoices | None + validation_alias: str | None = None, + serialization_alias: str | None = None, + title: str | None = None, + description: str | None = None, + gt: float | None = None, + ge: float | None = None, + lt: float | None = None, + le: float | None = None, + min_length: int | None = None, + max_length: int | None = None, + pattern: str | None = None, + discriminator: str | None = None, + strict: bool | None = _Unset, + multiple_of: float | None = _Unset, + allow_inf_nan: bool | None = _Unset, + max_digits: int | None = _Unset, + decimal_places: int | None = _Unset, + examples: list[Any] | None = None, + deprecated: bool | None = None, + include_in_schema: bool = True, + json_schema_extra: dict[str, Any] | None = None, + **extra: Any, + ): + """ + Constructs a new Path param. + + Parameters + ---------- + default: Any + The default value of the parameter + default_factory: Callable[[], Any], optional + Callable that will be called when a default value is needed for this field + annotation: Any, optional + The type annotation of the parameter + alias: str, optional + The public name of the field + alias_priority: int, optional + Priority of the alias. This affects whether an alias generator is used + validation_alias: str | AliasPath | AliasChoices | None, optional + Alias to be used for validation only + serialization_alias: str | AliasPath | AliasChoices | None, optional + Alias to be used for serialization only + title: str, optional + The title of the parameter + description: str, optional + The description of the parameter + gt: float, optional + Only applies to numbers, required the field to be "greater than" + ge: float, optional + Only applies to numbers, required the field to be "greater than or equal" + lt: float, optional + Only applies to numbers, required the field to be "less than" + le: float, optional + Only applies to numbers, required the field to be "less than or equal" + min_length: int, optional + Only applies to strings, required the field to have a minimum length + max_length: int, optional + Only applies to strings, required the field to have a maximum length + pattern: str, optional + Only applies to strings, requires the field match against a regular expression pattern string + discriminator: str, optional + Parameter field name for discriminating the type in a tagged union + strict: bool, optional + Enables Pydantic's strict mode for the field + multiple_of: float, optional + Only applies to numbers, requires the field to be a multiple of the given value + allow_inf_nan: bool, optional + Only applies to numbers, requires the field to allow infinity and NaN values + max_digits: int, optional + Only applies to Decimals, requires the field to have a maxmium number of digits within the decimal. + decimal_places: int, optional + Only applies to Decimals, requires the field to have at most a number of decimal places + examples: list[Any], optional + A list of examples for the parameter + deprecated: bool, optional + If `True`, the parameter will be marked as deprecated + include_in_schema: bool, optional + If `False`, the parameter will be excluded from the generated OpenAPI schema + json_schema_extra: dict[str, Any], optional + Extra values to include in the generated OpenAPI schema + """ + if default is not ...: + raise AssertionError("Path parameters cannot have a default value") + + super().__init__( + default=default, + default_factory=default_factory, + annotation=annotation, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, + examples=examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +class Query(Param): + """ + A class used internally to represent a query parameter in a path operation. + """ + + in_ = ParamTypes.query + + def __init__( + self, + default: Any = _Unset, + *, + default_factory: Callable[[], Any] | None = _Unset, + annotation: Any | None = None, + alias: str | None = None, + alias_priority: int | None = _Unset, + validation_alias: str | None = None, + serialization_alias: str | None = None, + title: str | None = None, + description: str | None = None, + gt: float | None = None, + ge: float | None = None, + lt: float | None = None, + le: float | None = None, + min_length: int | None = None, + max_length: int | None = None, + pattern: str | None = None, + discriminator: str | None = None, + strict: bool | None = _Unset, + multiple_of: float | None = _Unset, + allow_inf_nan: bool | None = _Unset, + max_digits: int | None = _Unset, + decimal_places: int | None = _Unset, + examples: list[Any] | None = None, + deprecated: bool | None = None, + include_in_schema: bool = True, + json_schema_extra: dict[str, Any] | None = None, + **extra: Any, + ): + """ + Constructs a new Query param. + + Parameters + ---------- + default: Any + The default value of the parameter + default_factory: Callable[[], Any], optional + Callable that will be called when a default value is needed for this field + annotation: Any, optional + The type annotation of the parameter + alias: str, optional + The public name of the field + alias_priority: int, optional + Priority of the alias. This affects whether an alias generator is used + validation_alias: str | AliasPath | AliasChoices | None, optional + Alias to be used for validation only + serialization_alias: str | AliasPath | AliasChoices | None, optional + Alias to be used for serialization only + title: str, optional + The title of the parameter + description: str, optional + The description of the parameter + gt: float, optional + Only applies to numbers, required the field to be "greater than" + ge: float, optional + Only applies to numbers, required the field to be "greater than or equal" + lt: float, optional + Only applies to numbers, required the field to be "less than" + le: float, optional + Only applies to numbers, required the field to be "less than or equal" + min_length: int, optional + Only applies to strings, required the field to have a minimum length + max_length: int, optional + Only applies to strings, required the field to have a maximum length + pattern: str, optional + Only applies to strings, requires the field match against a regular expression pattern string + discriminator: str, optional + Parameter field name for discriminating the type in a tagged union + strict: bool, optional + Enables Pydantic's strict mode for the field + multiple_of: float, optional + Only applies to numbers, requires the field to be a multiple of the given value + allow_inf_nan: bool, optional + Only applies to numbers, requires the field to allow infinity and NaN values + max_digits: int, optional + Only applies to Decimals, requires the field to have a maxmium number of digits within the decimal. + decimal_places: int, optional + Only applies to Decimals, requires the field to have at most a number of decimal places + examples: list[Any], optional + A list of examples for the parameter + deprecated: bool, optional + If `True`, the parameter will be marked as deprecated + include_in_schema: bool, optional + If `False`, the parameter will be excluded from the generated OpenAPI schema + json_schema_extra: dict[str, Any], optional + Extra values to include in the generated OpenAPI schema + """ + super().__init__( + default=default, + default_factory=default_factory, + annotation=annotation, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, + examples=examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +class Header(Param): + """ + A class used internally to represent a header parameter in a path operation. + """ + + in_ = ParamTypes.header + + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Callable[[], Any] | None = _Unset, + annotation: Any | None = None, + alias: str | None = None, + alias_priority: int | None = _Unset, + # MAINTENANCE: update when deprecating Pydantic v1, import these types + # str | AliasPath | AliasChoices | None + validation_alias: str | None = None, + serialization_alias: str | None = None, + convert_underscores: bool = True, + title: str | None = None, + description: str | None = None, + gt: float | None = None, + ge: float | None = None, + lt: float | None = None, + le: float | None = None, + min_length: int | None = None, + max_length: int | None = None, + pattern: str | None = None, + discriminator: str | None = None, + strict: bool | None = _Unset, + multiple_of: float | None = _Unset, + allow_inf_nan: bool | None = _Unset, + max_digits: int | None = _Unset, + decimal_places: int | None = _Unset, + examples: list[Any] | None = None, + deprecated: bool | None = None, + include_in_schema: bool = True, + json_schema_extra: dict[str, Any] | None = None, + **extra: Any, + ): + """ + Constructs a new Query param. + + Parameters + ---------- + default: Any + The default value of the parameter + default_factory: Callable[[], Any], optional + Callable that will be called when a default value is needed for this field + annotation: Any, optional + The type annotation of the parameter + alias: str, optional + The public name of the field + alias_priority: int, optional + Priority of the alias. This affects whether an alias generator is used + validation_alias: str | AliasPath | AliasChoices | None, optional + Alias to be used for validation only + serialization_alias: str | AliasPath | AliasChoices | None, optional + Alias to be used for serialization only + convert_underscores: bool + If true convert "_" to "-" + See RFC: https://www.rfc-editor.org/rfc/rfc9110.html#name-field-name-registry + title: str, optional + The title of the parameter + description: str, optional + The description of the parameter + gt: float, optional + Only applies to numbers, required the field to be "greater than" + ge: float, optional + Only applies to numbers, required the field to be "greater than or equal" + lt: float, optional + Only applies to numbers, required the field to be "less than" + le: float, optional + Only applies to numbers, required the field to be "less than or equal" + min_length: int, optional + Only applies to strings, required the field to have a minimum length + max_length: int, optional + Only applies to strings, required the field to have a maximum length + pattern: str, optional + Only applies to strings, requires the field match against a regular expression pattern string + discriminator: str, optional + Parameter field name for discriminating the type in a tagged union + strict: bool, optional + Enables Pydantic's strict mode for the field + multiple_of: float, optional + Only applies to numbers, requires the field to be a multiple of the given value + allow_inf_nan: bool, optional + Only applies to numbers, requires the field to allow infinity and NaN values + max_digits: int, optional + Only applies to Decimals, requires the field to have a maxmium number of digits within the decimal. + decimal_places: int, optional + Only applies to Decimals, requires the field to have at most a number of decimal places + examples: list[Any], optional + A list of examples for the parameter + deprecated: bool, optional + If `True`, the parameter will be marked as deprecated + include_in_schema: bool, optional + If `False`, the parameter will be excluded from the generated OpenAPI schema + json_schema_extra: dict[str, Any], optional + Extra values to include in the generated OpenAPI schema + """ + self.convert_underscores = convert_underscores + self._alias = alias + + super().__init__( + default=default, + default_factory=default_factory, + annotation=annotation, + alias=self._alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, + examples=examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + @property + def alias(self): + return self._alias + + @alias.setter + def alias(self, value: str | None = None): + if value is not None: + # Headers are case-insensitive according to RFC 7540 (HTTP/2), so we lower the parameter name + # This ensures that customers can access headers with any casing, as per the RFC guidelines. + # Reference: https://www.rfc-editor.org/rfc/rfc7540#section-8.1.2 + self._alias = value.lower() + + +class Body(FieldInfo): + """ + A class used internally to represent a body parameter in a path operation. + """ + + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Callable[[], Any] | None = _Unset, + annotation: Any | None = None, + embed: bool = False, + media_type: str = "application/json", + alias: str | None = None, + alias_priority: int | None = _Unset, + # MAINTENANCE: update when deprecating Pydantic v1, import these types + # str | AliasPath | AliasChoices | None + validation_alias: str | None = None, + serialization_alias: str | None = None, + title: str | None = None, + description: str | None = None, + gt: float | None = None, + ge: float | None = None, + lt: float | None = None, + le: float | None = None, + min_length: int | None = None, + max_length: int | None = None, + pattern: str | None = None, + discriminator: str | None = None, + strict: bool | None = _Unset, + multiple_of: float | None = _Unset, + allow_inf_nan: bool | None = _Unset, + max_digits: int | None = _Unset, + decimal_places: int | None = _Unset, + examples: list[Any] | None = None, + deprecated: bool | None = None, + include_in_schema: bool = True, + json_schema_extra: dict[str, Any] | None = None, + **extra: Any, + ): + self.embed = embed + self.media_type = media_type + self.deprecated = deprecated + self.include_in_schema = include_in_schema + kwargs = dict( + default=default, + default_factory=default_factory, + alias=alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + discriminator=discriminator, + multiple_of=multiple_of, + allow_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + **extra, + ) + if examples is not None: + kwargs["examples"] = examples + current_json_schema_extra = json_schema_extra or extra + + kwargs.update( + { + "annotation": annotation, + "alias_priority": alias_priority, + "validation_alias": validation_alias, + "serialization_alias": serialization_alias, + "strict": strict, + "json_schema_extra": current_json_schema_extra, + "pattern": pattern, + }, + ) + + use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset} + + super().__init__(**use_kwargs) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.default})" + + +class _Form(Body): + """ + A class used internally to represent a form parameter in a path operation. + """ + + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Callable[[], Any] | None = _Unset, + annotation: Any | None = None, + media_type: str = "application/x-www-form-urlencoded", + alias: str | None = None, + alias_priority: int | None = _Unset, + # MAINTENANCE: update when deprecating Pydantic v1, import these types + # str | AliasPath | AliasChoices | None + validation_alias: str | None = None, + serialization_alias: str | None = None, + title: str | None = None, + description: str | None = None, + gt: float | None = None, + ge: float | None = None, + lt: float | None = None, + le: float | None = None, + min_length: int | None = None, + max_length: int | None = None, + pattern: str | None = None, + discriminator: str | None = None, + strict: bool | None = _Unset, + multiple_of: float | None = _Unset, + allow_inf_nan: bool | None = _Unset, + max_digits: int | None = _Unset, + decimal_places: int | None = _Unset, + examples: list[Any] | None = None, + deprecated: bool | None = None, + include_in_schema: bool = True, + json_schema_extra: dict[str, Any] | None = None, + **extra: Any, + ): + super().__init__( + default=default, + default_factory=default_factory, + annotation=annotation, + embed=True, + media_type=media_type, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, + examples=examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +class _File(_Form): + """ + A class used internally to represent a file parameter in a path operation. + """ + + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Callable[[], Any] | None = _Unset, + annotation: Any | None = None, + media_type: str = "multipart/form-data", + alias: str | None = None, + alias_priority: int | None = _Unset, + # MAINTENANCE: update when deprecating Pydantic v1, import these types + # str | AliasPath | AliasChoices | None + validation_alias: str | None = None, + serialization_alias: str | None = None, + title: str | None = None, + description: str | None = None, + gt: float | None = None, + ge: float | None = None, + lt: float | None = None, + le: float | None = None, + min_length: int | None = None, + max_length: int | None = None, + pattern: str | None = None, + discriminator: str | None = None, + strict: bool | None = _Unset, + multiple_of: float | None = _Unset, + allow_inf_nan: bool | None = _Unset, + max_digits: int | None = _Unset, + decimal_places: int | None = _Unset, + examples: list[Any] | None = None, + deprecated: bool | None = None, + include_in_schema: bool = True, + json_schema_extra: dict[str, Any] | None = None, + **extra: Any, + ): + super().__init__( + default=default, + default_factory=default_factory, + annotation=annotation, + media_type=media_type, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, + examples=examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +def get_flat_dependant( + dependant: Dependant, + visited: list[CacheKey] | None = None, +) -> Dependant: + """ + Flatten a recursive Dependant model structure. + + This function recursively concatenates the parameter fields of a Dependant model and its dependencies into a flat + Dependant structure. This is useful for scenarios like parameter validation where the nested structure is not + relevant. + + Parameters + ---------- + dependant: Dependant + The dependant model to flatten + skip_repeats: bool + If True, child Dependents already visited will be skipped to avoid duplicates + visited: list[CacheKey], optional + Keeps track of visited Dependents to avoid infinite recursion. Defaults to empty list. + + Returns + ------- + Dependant + The flattened Dependant model + """ + if visited is None: + visited = [] + visited.append(dependant.cache_key) + + return Dependant( + path_params=dependant.path_params.copy(), + query_params=dependant.query_params.copy(), + header_params=dependant.header_params.copy(), + cookie_params=dependant.cookie_params.copy(), + body_params=dependant.body_params.copy(), + path=dependant.path, + ) + + +def analyze_param( + *, + param_name: str, + annotation: Any, + value: Any, + is_path_param: bool, + is_response_param: bool, +) -> ModelField | None: + """ + Analyze a parameter annotation and value to determine the type and default value of the parameter. + + Parameters + ---------- + param_name: str + The name of the parameter + annotation + The annotation of the parameter + value + The value of the parameter + is_path_param + Whether the parameter is a path parameter + is_response_param + Whether the parameter is the return annotation + + Returns + ------- + ModelField | None + The type annotation and the Pydantic field representing the parameter + """ + field_info, type_annotation = get_field_info_and_type_annotation(annotation, value, is_path_param) + + # If the value is a FieldInfo, we use it as the FieldInfo for the parameter + if isinstance(value, FieldInfo): + if field_info is not None: + raise AssertionError("Cannot use a FieldInfo as a parameter annotation and pass a FieldInfo as a value") + field_info = value + + field_info.annotation = type_annotation # type: ignore[attr-defined,unused-ignore] + + # If we didn't determine the FieldInfo yet, we create a default one + if field_info is None: + default_value = value if value is not inspect.Signature.empty else Required + + # Check if the parameter is part of the path. Otherwise, defaults to query. + if is_path_param: + field_info = Path(annotation=type_annotation) + elif not field_annotation_is_scalar(annotation=type_annotation): + field_info = Body(annotation=type_annotation, default=default_value) + else: + field_info = Query(annotation=type_annotation, default=default_value) + + # When we have a response field, we need to set the default value to Required + if is_response_param: + field_info.default = Required + + field = _create_model_field(field_info, type_annotation, param_name, is_path_param) + return field + + +def get_field_info_and_type_annotation(annotation, value, is_path_param: bool) -> tuple[FieldInfo | None, Any]: + """ + Get the FieldInfo and type annotation from an annotation and value. + """ + field_info: FieldInfo | None = None + type_annotation: Any = Any + + if annotation is not inspect.Signature.empty: + # If the annotation is an Annotated type, we need to extract the type annotation and the FieldInfo + if get_origin(annotation) is Annotated: + field_info, type_annotation = get_field_info_annotated_type(annotation, value, is_path_param) + # If the annotation is a Response type, we recursively call this function with the inner type + elif get_origin(annotation) is Response: + field_info, type_annotation = get_field_info_response_type(annotation, value) + # If the annotation is not an Annotated type, we use it as the type annotation + else: + type_annotation = annotation + + return field_info, type_annotation + + +def get_field_info_response_type(annotation, value) -> tuple[FieldInfo | None, Any]: + # Example: get_args(Response[inner_type]) == (inner_type,) # noqa: ERA001 + (inner_type,) = get_args(annotation) + + # Recursively resolve the inner type + return get_field_info_and_type_annotation(inner_type, value, False) + + +def get_field_info_annotated_type(annotation, value, is_path_param: bool) -> tuple[FieldInfo | None, Any]: + """ + Get the FieldInfo and type annotation from an Annotated type. + """ + field_info: FieldInfo | None = None + annotated_args = get_args(annotation) + type_annotation = annotated_args[0] + powertools_annotations = [arg for arg in annotated_args[1:] if isinstance(arg, FieldInfo)] + + if len(powertools_annotations) > 1: + raise AssertionError("Only one FieldInfo can be used per parameter") + + powertools_annotation = next(iter(powertools_annotations), None) + + if isinstance(powertools_annotation, FieldInfo): + # Copy `field_info` because we mutate `field_info.default` later + field_info = copy_field_info( + field_info=powertools_annotation, + annotation=annotation, + ) + if field_info.default not in [Undefined, Required]: + raise AssertionError("FieldInfo needs to have a default value of Undefined or Required") + + if value is not inspect.Signature.empty: + if is_path_param: + raise AssertionError("Cannot use a FieldInfo as a path parameter and pass a value") + field_info.default = value + else: + field_info.default = Required + + return field_info, type_annotation + + +def create_response_field( + name: str, + type_: type[Any], + default: Any | None = Undefined, + required: bool | UndefinedType = Undefined, + model_config: type[BaseConfig] = BaseConfig, + field_info: FieldInfo | None = None, + alias: str | None = None, + mode: Literal["validation", "serialization"] = "validation", +) -> ModelField: + """ + Create a new response field. Raises if type_ is invalid. + """ + field_info = field_info or FieldInfo( + annotation=type_, + default=default, + alias=alias, + ) + + kwargs = {"name": name, "field_info": field_info, "mode": mode} + + return ModelField(**kwargs) # type: ignore[arg-type] + + +def _create_model_field( + field_info: FieldInfo | None, + type_annotation: Any, + param_name: str, + is_path_param: bool, +) -> ModelField | None: + """ + Create a new ModelField from a FieldInfo and type annotation. + """ + if field_info is None: + return None + + if is_path_param: + if not isinstance(field_info, Path): + raise AssertionError("Path parameters must be of type Path") + elif isinstance(field_info, Param) and getattr(field_info, "in_", None) is None: + field_info.in_ = ParamTypes.query + + # If the field_info is a Param, we use the `in_` attribute to determine the type annotation + use_annotation = get_annotation_from_field_info(type_annotation, field_info, param_name) + + # If the field doesn't have a defined alias, we use the param name + if not field_info.alias and getattr(field_info, "convert_underscores", None): + alias = param_name.replace("_", "-") + else: + alias = field_info.alias or param_name + field_info.alias = alias + + return create_response_field( + name=param_name, + type_=use_annotation, + default=field_info.default, + alias=alias, + required=field_info.default in (Required, Undefined), + field_info=field_info, + ) diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/pydantic_loader.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/pydantic_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..225f7e88096c3e60e91dc5f0d9a8995d239599cd --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/pydantic_loader.py @@ -0,0 +1,6 @@ +try: + from pydantic.version import VERSION as PYDANTIC_VERSION + + PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") +except ImportError: + PYDANTIC_V2 = False # pragma: no cover # false positive; dropping in v3 diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/swagger_ui/__init__.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/swagger_ui/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bc6eda8abb3da7e483810b96a775e58ad2f97b50 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/swagger_ui/__init__.py @@ -0,0 +1,13 @@ +from aws_lambda_powertools.event_handler.openapi.swagger_ui.html import ( + generate_swagger_html, +) +from aws_lambda_powertools.event_handler.openapi.swagger_ui.oauth2 import ( + OAuth2Config, + generate_oauth2_redirect_html, +) + +__all__ = [ + "generate_swagger_html", + "generate_oauth2_redirect_html", + "OAuth2Config", +] diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/swagger_ui/html.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/swagger_ui/html.py new file mode 100644 index 0000000000000000000000000000000000000000..70d98743bcf2bf1f628a6808a52d8f5d394c9f38 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/swagger_ui/html.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from aws_lambda_powertools.event_handler.openapi.swagger_ui.oauth2 import OAuth2Config + + +def generate_swagger_html( + spec: str, + swagger_js: str, + swagger_css: str, + swagger_base_url: str, + oauth2_config: OAuth2Config | None, + persist_authorization: bool = False, +) -> str: + """ + Generate Swagger UI HTML page + + Parameters + ---------- + spec: str + The OpenAPI spec + swagger_js: str + Swagger UI JavaScript source code or URL + swagger_css: str + Swagger UI CSS source code or URL + swagger_base_url: str + The base URL for Swagger UI + oauth2_config: OAuth2Config, optional + The OAuth2 configuration. + persist_authorization: bool, optional + Whether to persist authorization data on browser close/refresh. + """ + + # If Swagger base URL is present, generate HTML content with linked CSS and JavaScript files + # If no Swagger base URL is provided, include CSS and JavaScript directly in the HTML + if swagger_base_url: + swagger_css_content = f"<link rel='stylesheet' type='text/css' href='{swagger_css}'>" + swagger_js_content = f"<script src='{swagger_js}'></script>" + else: + swagger_css_content = f"<style>{swagger_css}</style>" + swagger_js_content = f"<script>{swagger_js}</script>" + + # Prepare oauth2 config + oauth2_content = ( + f"ui.initOAuth({oauth2_config.json(exclude_none=True, exclude_unset=True)});" if oauth2_config else "" + ) + + return f""" +<!DOCTYPE html> +<html> +<head> + <meta charset="UTF-8"> + <title>Swagger UI + + {swagger_css_content} + + + +
+ Loading... +
+ + +{swagger_js_content} + + + + """.strip() diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/swagger_ui/oauth2.py b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/swagger_ui/oauth2.py new file mode 100644 index 0000000000000000000000000000000000000000..4cafdfe401c79e476caeb999f0406e016b791458 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/swagger_ui/oauth2.py @@ -0,0 +1,154 @@ +# ruff: noqa: E501 FA100 +import warnings +from typing import Dict, Optional, Sequence + +from pydantic import BaseModel, Field, field_validator + +from aws_lambda_powertools.event_handler.openapi.models import ( + MODEL_CONFIG_ALLOW, +) +from aws_lambda_powertools.shared.functions import powertools_dev_is_set + + +# Based on https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/ +class OAuth2Config(BaseModel): + """ + OAuth2 configuration for Swagger UI + """ + + # The client ID for the OAuth2 application + clientId: Optional[str] = Field(alias="client_id", default=None) + + # The client secret for the OAuth2 application. This is sensitive information and requires the explicit presence + # of the POWERTOOLS_DEV environment variable. + clientSecret: Optional[str] = Field(alias="client_secret", default=None) + + # The realm in which the OAuth2 application is registered. Optional. + realm: Optional[str] = Field(default=None) + + # The name of the OAuth2 application + appName: str = Field(alias="app_name") + + # The scopes that the OAuth2 application requires. Defaults to an empty list. + scopes: Sequence[str] = Field(default=[]) + + # Additional query string parameters to be included in the OAuth2 request. Defaults to an empty dictionary. + additionalQueryStringParams: Dict[str, str] = Field(alias="additional_query_string_params", default={}) + + # Whether to use basic authentication with the access code grant type. Defaults to False. + useBasicAuthenticationWithAccessCodeGrant: bool = Field( + alias="use_basic_authentication_with_access_code_grant", + default=False, + ) + + # Whether to use PKCE with the authorization code grant type. Defaults to False. + usePkceWithAuthorizationCodeGrant: bool = Field(alias="use_pkce_with_authorization_code_grant", default=False) + + model_config = MODEL_CONFIG_ALLOW + + @field_validator("clientSecret") + def client_secret_only_on_dev(cls, v: Optional[str]) -> Optional[str]: + if not v: + return None + + if not powertools_dev_is_set(): + raise ValueError( + "cannot use client_secret without POWERTOOLS_DEV mode. See " + "https://docs.powertools.aws.dev/lambda/python/latest/#optimizing-for-non-production-environments", + ) + else: + warnings.warn( + "OAuth2Config is using client_secret and POWERTOOLS_DEV is set. This reveals sensitive information. " + "DO NOT USE THIS OUTSIDE LOCAL DEVELOPMENT", + stacklevel=2, + ) + return v + + +def generate_oauth2_redirect_html() -> str: + """ + Generates the HTML content for the OAuth2 redirect page. + + Source: https://github.com/swagger-api/swagger-ui/blob/master/dist/oauth2-redirect.html + """ + return """ + + + + Swagger UI: OAuth2 Redirect + + + + + + """.strip() diff --git a/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/swagger_ui/swagger-ui-bundle.min.js b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/swagger_ui/swagger-ui-bundle.min.js new file mode 100644 index 0000000000000000000000000000000000000000..bc1d328090c327ec7fd97e0d7e6c050ded3e6690 --- /dev/null +++ b/testbed/aws-powertools__powertools-lambda-python/aws_lambda_powertools/event_handler/openapi/swagger_ui/swagger-ui-bundle.min.js @@ -0,0 +1,12 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SwaggerUIBundle=t():e.SwaggerUIBundle=t()}(this,()=>{var s,i,n={69119:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BLANK_URL=t.relativeFirstCharacters=t.urlSchemeRegex=t.ctrlCharactersRegex=t.htmlCtrlEntityRegex=t.htmlEntitiesRegex=t.invalidProtocolRegex=void 0,t.invalidProtocolRegex=/^([^\w]*)(javascript|data|vbscript)/im,t.htmlEntitiesRegex=/&#(\w+)(^\w|;)?/g,t.htmlCtrlEntityRegex=/&(newline|tab);/gi,t.ctrlCharactersRegex=/[\u0000-\u001F\u007F-\u009F\u2000-\u200D\uFEFF]/gim,t.urlSchemeRegex=/^.+(:|:)/gim,t.relativeFirstCharacters=[".","/"],t.BLANK_URL="about:blank"},16750:(e,t,n)=>{"use strict";t.J=void 0;var r=n(69119);t.J=function(e){if(!e)return r.BLANK_URL;e=e.replace(r.ctrlCharactersRegex,"").replace(r.htmlEntitiesRegex,function(e,t){return String.fromCharCode(t)}).replace(r.htmlCtrlEntityRegex,"").replace(r.ctrlCharactersRegex,"").trim();if(!e)return r.BLANK_URL;if(-1{"use strict";t.byteLength=function(e){var e=u(e),t=e[0],e=e[1];return 3*(t+e)/4-e},t.toByteArray=function(e){for(var t,n=u(e),r=n[0],n=n[1],o=new c(3*(r+n)/4-n),s=0,i=0>16&255,o[s++]=t>>8&255,o[s++]=255&t;return 2===n&&(t=l[e.charCodeAt(a)]<<2|l[e.charCodeAt(a+1)]>>4,o[s++]=255&t),1===n&&(t=l[e.charCodeAt(a)]<<10|l[e.charCodeAt(a+1)]<<4|l[e.charCodeAt(a+2)]>>2,o[s++]=t>>8&255,o[s++]=255&t),o},t.fromByteArray=function(e){for(var t,n=e.length,r=n%3,o=[],s=0,i=n-r;s>18&63]+a[r>>12&63]+a[r>>6&63]+a[63&r]);return o.join("")}(e,s,i>2]+a[t<<4&63]+"==")):2==r&&(t=(e[n-2]<<8)+e[n-1],o.push(a[t>>10]+a[t>>4&63]+a[t<<2&63]+"=")),o.join("")};for(var a=[],l=[],c="undefined"!=typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=0;r<64;++r)a[r]=n[r],l[n.charCodeAt(r)]=r;function u(e){var t=e.length;if(0{"use strict";const g=e(67526),s=e(251),t="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null,r=(n.Buffer=u,n.SlowBuffer=function(e){return u.alloc(+(e=+e!=e?0:e))},n.INSPECT_MAX_BYTES=50,2147483647);function c(e){if(e>r)throw new RangeError('The value "'+e+'" is invalid for option "size"');e=new Uint8Array(e);return Object.setPrototypeOf(e,u.prototype),e}function u(e,t,n){if("number"!=typeof e)return o(e,t,n);if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return a(e)}function o(t,n,e){if("string"==typeof t){var r=t,o=n;if(!u.isEncoding(o="string"==typeof o&&""!==o?o:"utf8"))throw new TypeError("Unknown encoding: "+o);var s=0|f(r,o);let e=c(s);return r=e.write(r,o),e=r!==s?e.slice(0,r):e}if(ArrayBuffer.isView(t))return T(o=t,Uint8Array)?h((s=new Uint8Array(o)).buffer,s.byteOffset,s.byteLength):p(o);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(T(t,ArrayBuffer)||t&&T(t.buffer,ArrayBuffer))return h(t,n,e);if("undefined"!=typeof SharedArrayBuffer&&(T(t,SharedArrayBuffer)||t&&T(t.buffer,SharedArrayBuffer)))return h(t,n,e);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');r=t.valueOf&&t.valueOf();if(null!=r&&r!==t)return u.from(r,n,e);var i,a,l=u.isBuffer(i=t)?(0!==(a=c(l=0|d(i.length))).length&&i.copy(a,0,0,l),a):void 0!==i.length?"number"!=typeof i.length||R(i.length)?c(0):p(i):"Buffer"===i.type&&Array.isArray(i.data)?p(i.data):void 0;if(l)return l;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return u.from(t[Symbol.toPrimitive]("string"),n,e);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function i(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function a(e){return i(e),c(e<0?0:0|d(e))}function p(t){const n=t.length<0?0:0|d(t.length),r=c(n);for(let e=0;e=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return 0|e}function f(e,t){if(u.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||T(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,r=2>>1;case"base64":return $(e).length;default:if(o)return r?-1:N(e).length;t=(""+t).toLowerCase(),o=!0}}function F(e,n,r){let t=!1;if((n=void 0===n||n<0?0:n)>this.length)return"";if((r=void 0===r||r>this.length?this.length:r)<=0)return"";if((r>>>=0)<=(n>>>=0))return"";for(e=e||"utf8";;)switch(e){case"hex":{var o=this;var s=n;var i=r;var a=o.length;(!s||s<0)&&(s=0),(!i||i<0||a=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=u.from(t,r)),u.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?(o?Uint8Array.prototype.indexOf:Uint8Array.prototype.lastIndexOf).call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(n,r,t,e,o){let s,i=1,a=n.length,l=r.length;if(void 0!==e&&("ucs2"===(e=String(e).toLowerCase())||"ucs-2"===e||"utf16le"===e||"utf-16le"===e)){if(n.length<2||r.length<2)return-1;i=2,a/=2,l/=2,t/=2}function c(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}if(o){let e=-1;for(s=t;sa&&(t=a-l),s=t;0<=s;s--){let t=!0;for(let e=0;e>>10&1023|55296),o=56320|1023&o),n.push(o),l+=s}{var r=n,o=r.length;if(o<=b)return String.fromCharCode.apply(String,r);let e="",t=0;for(;tr.length?(e=u.isBuffer(e)?e:u.from(e)).copy(r,o):Uint8Array.prototype.set.call(r,e,o);else{if(!u.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(r,o)}o+=e.length}return r},u.byteLength=f,u.prototype._isBuffer=!0,u.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;et&&(e+=" ... "),""},t&&(u.prototype[t]=u.prototype.inspect),u.prototype.compare=function(e,t,n,r,o){if(T(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),(t=void 0===t?0:t)<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(o<=r&&n<=t)return 0;if(o<=r)return-1;if(n<=t)return 1;if(this===e)return 0;let s=(o>>>=0)-(r>>>=0),i=(n>>>=0)-(t>>>=0);var a=Math.min(s,i),l=this.slice(r,o),c=e.slice(t,n);for(let e=0;e>>=0,isFinite(r)?(r>>>=0,void 0===e&&(e="utf8")):(e=r,r=void 0)}var o,s,i,a,l,c,u=this.length-n;if((void 0===r||uthis.length)throw new RangeError("Attempt to write outside buffer bounds");e=e||"utf8";let p=!1;for(;;)switch(e){case"hex":{var h=this;var d=t;var f=n;var m=r;f=Number(f)||0;var g=h.length-f,g=((!m||(m=Number(m))>g)&&(m=g),d.length);let e;for(g/2>8,s.push(r%256),s.push(o);return s}(t,(o=this).length-s),o,s,i);default:if(p)throw new TypeError("Unknown encoding: "+e);e=(""+e).toLowerCase(),p=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const b=4096;function w(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(ne.length)throw new RangeError("Index out of range")}function S(e,t,n,r,o){L(t,r,o,e,n,7);r=Number(t&BigInt(4294967295)),e[n++]=r,e[n++]=r>>=8,e[n++]=r>>=8,e[n++]=r>>=8,o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,e[n++]=o>>=8,e[n++]=o>>=8,e[n++]=o>>=8,n}function x(e,t,n,r,o){L(t,r,o,e,n,7);r=Number(t&BigInt(4294967295)),e[n+7]=r,e[n+6]=r>>=8,e[n+5]=r>>=8,e[n+4]=r>>=8,o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,e[n+2]=o>>=8,e[n+1]=o>>=8,e[n]=o>>=8,n+8}function _(e,t,n,r){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function k(e,t,n,r,o){return t=+t,n>>>=0,o||_(e,0,n,4),s.write(e,t,n,r,23,4),n+4}function A(e,t,n,r,o){return t=+t,n>>>=0,o||_(e,0,n,8),s.write(e,t,n,r,52,8),n+8}u.prototype.slice=function(e,t){var n=this.length,n=((e=~~e)<0?(e+=n)<0&&(e=0):n>>=0,t>>>=0,n||w(e,t,this.length);let r=this[e],o=1,s=0;for(;++s>>=0,t>>>=0,n||w(e,t,this.length);let r=this[e+--t],o=1;for(;0>>=0,t||w(e,1,this.length),this[e]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||w(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||w(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||w(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||w(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readBigUInt64LE=M(function(e){j(e>>>=0,"offset");var t=this[e],n=this[e+7],t=(void 0!==t&&void 0!==n||P(e,this.length-8),t+256*this[++e]+65536*this[++e]+this[++e]*2**24),e=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(t)+(BigInt(e)<>>=0,"offset");var t=this[e],n=this[e+7],t=(void 0!==t&&void 0!==n||P(e,this.length-8),t*2**24+65536*this[++e]+256*this[++e]+this[++e]),e=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(t)<>>=0,t>>>=0,n||w(e,t,this.length);let r=this[e],o=1,s=0;for(;++s=o&&(r-=Math.pow(2,8*t)),r},u.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||w(e,t,this.length);let r=t,o=1,s=this[e+--r];for(;0=o&&(s-=Math.pow(2,8*t)),s},u.prototype.readInt8=function(e,t){return e>>>=0,t||w(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||w(e,2,this.length);t=this[e]|this[e+1]<<8;return 32768&t?4294901760|t:t},u.prototype.readInt16BE=function(e,t){e>>>=0,t||w(e,2,this.length);t=this[e+1]|this[e]<<8;return 32768&t?4294901760|t:t},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||w(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||w(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readBigInt64LE=M(function(e){j(e>>>=0,"offset");var t=this[e],n=this[e+7],n=(void 0!==t&&void 0!==n||P(e,this.length-8),this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24));return(BigInt(n)<>>=0,"offset");var t=this[e],n=this[e+7],t=(void 0!==t&&void 0!==n||P(e,this.length-8),(t<<24)+65536*this[++e]+256*this[++e]+this[++e]);return(BigInt(t)<>>=0,t||w(e,4,this.length),s.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||w(e,4,this.length),s.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||w(e,8,this.length),s.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||w(e,8,this.length),s.read(this,e,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||E(this,e,t,n,Math.pow(2,8*n)-1,0);let o=1,s=0;for(this[t]=255&e;++s>>=0,n>>>=0,r||E(this,e,t,n,Math.pow(2,8*n)-1,0);let o=n-1,s=1;for(this[t+o]=255&e;0<=--o&&(s*=256);)this[t+o]=e/s&255;return t+n},u.prototype.writeUint8=u.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigUInt64LE=M(function(e,t=0){return S(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeBigUInt64BE=M(function(e,t=0){return x(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);E(this,e,t,n,r-1,-r)}let o=0,s=1,i=0;for(this[t]=255&e;++o>0)-i&255;return t+n},u.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);E(this,e,t,n,r-1,-r)}let o=n-1,s=1,i=0;for(this[t+o]=255&e;0<=--o&&(s*=256);)e<0&&0===i&&0!==this[t+o+1]&&(i=1),this[t+o]=(e/s>>0)-i&255;return t+n},u.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,1,127,-128),this[t]=255&(e=e<0?255+e+1:e),t+1},u.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},u.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,4,2147483647,-2147483648),this[t]=(e=e<0?4294967295+e+1:e)>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigInt64LE=M(function(e,t=0){return S(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),u.prototype.writeBigInt64BE=M(function(e,t=0){return x(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),u.prototype.writeFloatLE=function(e,t,n){return k(this,e,t,!0,n)},u.prototype.writeFloatBE=function(e,t,n){return k(this,e,t,!1,n)},u.prototype.writeDoubleLE=function(e,t,n){return A(this,e,t,!0,n)},u.prototype.writeDoubleBE=function(e,t,n){return A(this,e,t,!1,n)},u.prototype.copy=function(e,t,n,r){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n=n||0,r||0===r||(r=this.length),t>=e.length&&(t=e.length),(r=0=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length);var o=(r=e.length-t>>=0,n=void 0===n?this.length:n>>>0,"number"==typeof(e=e||0))for(o=t;o=4+r;n-=3)t="_"+e.slice(n-3,n)+t;return""+e.slice(0,n)+t}function L(e,t,n,r,o,s){if(n= 0${r} and < 2${r} ** `+8*(s+1)+r:`>= -(2${r} ** ${8*(s+1)-1}${r}) and < 2 ** `+(8*(s+1)-1)+r:`>= ${t}${r} and <= `+n+r;throw new O.ERR_OUT_OF_RANGE("value",t,e)}n=r,t=s,j(e=o,"offset"),void 0!==n[e]&&void 0!==n[e+t]||P(e,n.length-(t+1))}function j(e,t){if("number"!=typeof e)throw new O.ERR_INVALID_ARG_TYPE(t,"number",e)}function P(e,t,n){if(Math.floor(e)!==e)throw j(e,n),new O.ERR_OUT_OF_RANGE(n||"offset","an integer",e);if(t<0)throw new O.ERR_BUFFER_OUT_OF_BOUNDS;throw new O.ERR_OUT_OF_RANGE(n||"offset",`>= ${n?1:0} and <= `+t,e)}C("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?e+" is outside of buffer bounds":"Attempt to access memory outside buffer bounds"},RangeError),C("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type `+typeof t},TypeError),C("ERR_OUT_OF_RANGE",function(e,t,n){let r=`The value of "${e}" is out of range.`,o=n;return Number.isInteger(n)&&Math.abs(n)>2**32?o=B(String(n)):"bigint"==typeof n&&(o=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(o=B(o)),o+="n"),r+=` It must be ${t}. Received `+o},RangeError);const q=/[^+/0-9A-Za-z-_]/g;function N(t,n){let r;n=n||1/0;var o=t.length;let s=null;const i=[];for(let e=0;e>6|192,63&r|128)}else if(r<65536){if((n-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((n-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function $(e){return g.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(q,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function I(e,t,n,r){let o;for(o=0;o=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function T(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function R(e){return e!=e}const z=function(){const n="0123456789abcdef",r=new Array(256);for(let t=0;t<16;++t){var o=16*t;for(let e=0;e<16;++e)r[o+e]=n[t]+n[e]}return r}();function M(e){return"undefined"==typeof BigInt?U:e}function U(){throw new Error("BigInt not supported")}},38075:(e,t,n)=>{"use strict";var r=n(70453),o=n(10487),s=o(r("String.prototype.indexOf"));e.exports=function(e,t){t=r(e,!!t);return"function"==typeof t&&-1{"use strict";var r=n(66743),o=n(70453),s=n(96897),i=o("%TypeError%"),a=o("%Function.prototype.apply%"),l=o("%Function.prototype.call%"),c=o("%Reflect.apply%",!0)||r.call(l,a),n=o("%Object.defineProperty%",!0),u=o("%Math.max%");if(n)try{n({},"a",{value:1})}catch(e){n=null}e.exports=function(e){if("function"!=typeof e)throw new i("a function is required");var t=c(r,l,arguments);return s(t,1+u(0,e.length-(arguments.length-1)),!0)};function p(){return c(r,a,arguments)}n?n(e.exports,"apply",{value:p}):e.exports.apply=p},17965:(e,t,n)=>{"use strict";var p=n(16426),h={"text/plain":"Text","text/html":"Url",default:"Text"};e.exports=function(n,r){var t,e,o,s,i,a,l,c=!1,u=(r=r||{}).debug||!1;try{if(e=p(),o=document.createRange(),s=document.getSelection(),(i=document.createElement("span")).textContent=n,i.ariaHidden="true",i.style.all="unset",i.style.position="fixed",i.style.top=0,i.style.clip="rect(0, 0, 0, 0)",i.style.whiteSpace="pre",i.style.webkitUserSelect="text",i.style.MozUserSelect="text",i.style.msUserSelect="text",i.style.userSelect="text",i.addEventListener("copy",function(e){var t;e.stopPropagation(),r.format&&(e.preventDefault(),void 0===e.clipboardData?(u&&console.warn("unable to use e.clipboardData"),u&&console.warn("trying IE specific stuff"),window.clipboardData.clearData(),t=h[r.format]||h.default,window.clipboardData.setData(t,n)):(e.clipboardData.clearData(),e.clipboardData.setData(r.format,n))),r.onCopy&&(e.preventDefault(),r.onCopy(e.clipboardData))}),document.body.appendChild(i),o.selectNodeContents(i),s.addRange(o),!document.execCommand("copy"))throw new Error("copy command was unsuccessful");c=!0}catch(e){u&&console.error("unable to copy using execCommand: ",e),u&&console.warn("trying IE specific stuff");try{window.clipboardData.setData(r.format||"text",n),r.onCopy&&r.onCopy(window.clipboardData),c=!0}catch(e){u&&console.error("unable to copy using clipboardData: ",e),u&&console.error("falling back to prompt"),a="message"in r?r.message:"Copy to clipboard: #{key}, Enter",l=(/mac os x/i.test(navigator.userAgent)?"⌘":"Ctrl")+"+C",t=a.replace(/#{\s*key\s*}/g,l),window.prompt(t,n)}}finally{s&&("function"==typeof s.removeRange?s.removeRange(o):s.removeAllRanges()),i&&document.body.removeChild(i),e()}return c}},2205:function(e,t,n){n=void 0!==n.g?n.g:this;e.exports=function(e){if(e.CSS&&e.CSS.escape)return e.CSS.escape;function t(e){if(0==arguments.length)throw new TypeError("`CSS.escape` requires an argument.");for(var t,n=String(e),r=n.length,o=-1,s="",i=n.charCodeAt(0);++o{"use strict";var r=n(48287).Buffer;function s(e){return e instanceof r||e instanceof Date||e instanceof RegExp}function i(e){var t;if(e instanceof r)return t=r.alloc?r.alloc(e.length):new r(e.length),e.copy(t),t;if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e);throw new Error("Unexpected situation")}function a(e,t){return"__proto__"===t?void 0:e[t]}var l=e.exports=function(){if(arguments.length<1||"object"!=typeof arguments[0])return!1;if(arguments.length<2)return arguments[0];var n,r,o=arguments[0];return Array.prototype.slice.call(arguments,1).forEach(function(t){"object"!=typeof t||null===t||Array.isArray(t)||Object.keys(t).forEach(function(e){return r=a(o,e),(n=a(t,e))===o?void 0:"object"!=typeof n||null===n?void(o[e]=n):Array.isArray(n)?void(o[e]=function n(e){var r=[];return e.forEach(function(e,t){"object"==typeof e&&null!==e?Array.isArray(e)?r[t]=n(e):s(e)?r[t]=i(e):r[t]=l({},e):r[t]=e}),r}(n)):s(n)?void(o[e]=i(n)):"object"!=typeof r||null===r||Array.isArray(r)?void(o[e]=l({},n)):void(o[e]=l(r,n))})}),o}},14744:e=>{"use strict";function o(e){return!(!(t=e)||"object"!=typeof t||(t=e,"[object RegExp]"===(e=Object.prototype.toString.call(t))||"[object Date]"===e||t.$$typeof===n));var t}var n="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function a(e,t){return!1!==t.clone&&t.isMergeableObject(e)?c(Array.isArray(e)?[]:{},e,t):e}function s(e,t,n){return e.concat(t).map(function(e){return a(e,n)})}function t(e){return Object.keys(e).concat((t=e,Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(t).filter(function(e){return Object.propertyIsEnumerable.call(t,e)}):[]));var t}function l(e,t){try{return t in e}catch(e){return!1}}function i(r,o,s){var i={};return s.isMergeableObject(r)&&t(r).forEach(function(e){i[e]=a(r[e],s)}),t(o).forEach(function(e){var t,n;(!l(t=r,n=e)||Object.hasOwnProperty.call(t,n)&&Object.propertyIsEnumerable.call(t,n))&&(l(r,e)&&s.isMergeableObject(o[e])?i[e]=function(e,t){if(!t.customMerge)return c;t=t.customMerge(e);return"function"==typeof t?t:c}(e,s)(r[e],o[e],s):i[e]=a(o[e],s))}),i}function c(e,t,n){(n=n||{}).arrayMerge=n.arrayMerge||s,n.isMergeableObject=n.isMergeableObject||o,n.cloneUnlessOtherwiseSpecified=a;var r=Array.isArray(t);return r===Array.isArray(e)?r?n.arrayMerge(e,t,n):i(e,t,n):a(t,n)}c.all=function(e,n){if(Array.isArray(e))return e.reduce(function(e,t){return c(e,t,n)},{});throw new Error("first argument should be an array")},e.exports=c},30041:(e,t,n)=>{"use strict";var r=n(30592)(),o=n(70453),l=r&&o("%Object.defineProperty%",!0);if(l)try{l({},"a",{value:1})}catch(e){l=!1}var c=o("%SyntaxError%"),u=o("%TypeError%"),p=n(75795);e.exports=function(e,t,n){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new u("`obj` must be an object or a function`");if("string"!=typeof t&&"symbol"!=typeof t)throw new u("`property` must be a string or a symbol`");if(3/gm),p=e(/\${[\w\W]*}/gm),h=e(/^data-[\-\w.\u00B7-\uFFFF]/),d=e(/^aria-[\-\w]+$/),ht=e(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),f=e(/^(?:\w+script|data):/i),m=e(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),dt=e(/^html$/i);var ft=Object.freeze({__proto__:null,MUSTACHE_EXPR:t,ERB_EXPR:n,TMPLIT_EXPR:p,DATA_ATTR:h,ARIA_ATTR:d,IS_ALLOWED_URI:ht,IS_SCRIPT_OR_DATA:f,ATTR_WHITESPACE:m,DOCTYPE_NAME:dt});return function D(e){e=0D(e);if(c.version="3.0.9",c.removed=[],!e||!e.document||9!==e.document.nodeType)return c.isSupported=!1,c;let s=e.document;const l=s,F=l.currentScript,{DocumentFragment:B,HTMLTemplateElement:L,Node:u,Element:q,NodeFilter:t,NamedNodeMap:$=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:z,DOMParser:U,trustedTypes:p}=e,n=q.prototype,V=nt(n,"cloneNode"),K=nt(n,"nextSibling"),W=nt(n,"childNodes"),o=nt(n,"parentNode");if("function"==typeof L){const ze=s.createElement("template");ze.content&&ze.content.ownerDocument&&(s=ze.content.ownerDocument)}let h,d="";const{implementation:i,createNodeIterator:J,createDocumentFragment:H,getElementsByTagName:G}=s,Y=l.importNode;let r={};c.isSupported="function"==typeof ze&&"function"==typeof o&&i&&void 0!==i.createHTMLDocument;const{MUSTACHE_EXPR:f,ERB_EXPR:m,TMPLIT_EXPR:X,DATA_ATTR:Q,ARIA_ATTR:Z,IS_SCRIPT_OR_DATA:ee,ATTR_WHITESPACE:te}=ft;let ne=ft.IS_ALLOWED_URI,g=null;const re=et({},[...rt,...ot,...st,...it,...at]);let y=null;const oe=et({},[...lt,...ct,...ut,...pt]);let a=Object.seal(Ve(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),v=null,se=null,ie=!0,ae=!0,le=!1,ce=!0,b=!1,w=!1,ue=!1,pe=!1,E=!1,S=!1,x=!1,he=!0,de=!1;const fe="user-content-";let me=!0,_=!1,k={},A=null;const ge=et({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let ye=null;const ve=et({},["audio","video","img","source","image","track"]);let be=null;const we=et({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),O="http://www.w3.org/1998/Math/MathML",C="http://www.w3.org/2000/svg",j="http://www.w3.org/1999/xhtml";let P=j,Ee,Se=null;const xe=et({},[O,C,j],Ge);let N=null;const _e=["application/xhtml+xml","text/html"];let I=null,T=null;function ke(e){return e instanceof RegExp||e instanceof Function}function Ae(){let e=0e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+t+" could not be created."),null}}(p,F):h)&&"string"==typeof d&&(d=h.createHTML(""));Ue&&Ue(e),T=e}}function R(t){Je(c.removed,{element:t});try{t.parentNode.removeChild(t)}catch(e){t.remove()}}function Oe(e){let t=null,n=null;if(pe)e=""+e;else{const t=mt(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===N&&P===j&&(e=''+e+"");var r=h?h.createHTML(e):e;if(P===j)try{t=(new U).parseFromString(r,N)}catch(e){}if(!t||!t.documentElement){t=i.createDocument(P,"template",null);try{t.documentElement.innerHTML=Ee?d:r}catch(e){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(s.createTextNode(n),o.childNodes[0]||null),P===j?G.call(t,w?"html":"body")[0]:w?t.documentElement:o}function Ce(e){return J.call(e.ownerDocument||e,e,t.SHOW_ELEMENT|t.SHOW_COMMENT|t.SHOW_TEXT,null)}function je(e){return"function"==typeof u&&e instanceof u}function Pe(t){let n=null;if(M("beforeSanitizeElements",t,null),(e=t)instanceof z&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof $)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes))return R(t),1;var e;const r=I(t.nodeName);if(M("uponSanitizeElement",t,{tagName:r,allowedTags:g}),t.hasChildNodes()&&!je(t.firstElementChild)&&Qe(/<[/\w]/g,t.innerHTML)&&Qe(/<[/\w]/g,t.textContent))return R(t),1;if(g[r]&&!v[r])return t instanceof q&&!function(e){let t=o(e);t&&t.tagName||(t={namespaceURI:P,tagName:"template"});var n=He(e.tagName),r=He(t.tagName);return Se[e.namespaceURI]&&(e.namespaceURI===C?t.namespaceURI===j?"svg"===n:t.namespaceURI===O?"svg"===n&&("annotation-xml"===r||Me[r]):Boolean(Be[n]):e.namespaceURI===O?t.namespaceURI===j?"math"===n:t.namespaceURI===C?"math"===n&&De[r]:Boolean(Le[n]):e.namespaceURI===j?(t.namespaceURI!==C||De[r])&&(t.namespaceURI!==O||Me[r])&&!Le[n]&&(Fe[n]||!Be[n]):"application/xhtml+xml"===N&&Se[e.namespaceURI])}(t)||("noscript"===r||"noembed"===r||"noframes"===r)&&Qe(/<\/no(script|embed|frames)/i,t.innerHTML)?(R(t),!0):(b&&3===t.nodeType&&(n=t.textContent,Ke([f,m,X],e=>{n=Ye(n,e," ")}),t.textContent!==n&&(Je(c.removed,{element:t.cloneNode()}),t.textContent=n)),M("afterSanitizeElements",t,null),!1);if(!v[r]&&Ne(r)){if(a.tagNameCheck instanceof RegExp&&Qe(a.tagNameCheck,r))return;if(a.tagNameCheck instanceof Function&&a.tagNameCheck(r))return}if(me&&!A[r]){const n=o(t)||t.parentNode,r=W(t)||t.childNodes;if(r&&n)for(let e=r.length-1;0<=e;--e)n.insertBefore(V(r[e],!0),K(t))}return R(t),1}function Ne(e){return"annotation-xml"!==e&&0/i,t))qe(o,n);else if(b&&Ke([f,m,X],e=>{t=Ye(t,e," ")}),i=I(n.nodeName),$e(i,a,t)){if(!de||"id"!==a&&"name"!==a||(qe(o,n),t=fe+t),h&&"object"==typeof p&&"function"==typeof p.getAttributeType&&!s)switch(p.getAttributeType(i,a)){case"TrustedHTML":t=h.createHTML(t);break;case"TrustedScriptURL":t=h.createScriptURL(t)}try{s?n.setAttributeNS(s,o,t):n.setAttribute(o,t),We(c.removed)}catch(n){}}}M("afterSanitizeAttributes",n,null)}}function Te(e){var t;const n=Ce(e);for(M("beforeSanitizeShadowDOM",e,null);t=n.nextNode();)M("uponSanitizeShadowNode",t,null),Pe(t)||(t.content instanceof B&&Te(t.content),Ie(t));M("afterSanitizeShadowDOM",e,null)}const Re=s.createElement("form"),Me=et({},["mi","mo","mn","ms","mtext"]),De=et({},["foreignobject","desc","title","annotation-xml"]),Fe=et({},["title","style","font","a","script"]),Be=et({},[...ot,...st,...vt]),Le=et({},[...it,...bt]),qe=function(e,t){try{Je(c.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){Je(c.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e&&!y[e])if(E||S)try{R(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},M=function(e,t,n){r[e]&&Ke(r[e],e=>{e.call(c,t,n,T)})},$e=function(e,t,n){if(he&&("id"===t||"name"===t)&&(n in s||n in Re))return!1;if((!ae||se[t]||!Qe(Q,t))&&(!ie||!Qe(Z,t)))if(!y[t]||se[t]){if(!(Ne(e)&&(a.tagNameCheck instanceof RegExp&&Qe(a.tagNameCheck,e)||a.tagNameCheck instanceof Function&&a.tagNameCheck(e))&&(a.attributeNameCheck instanceof RegExp&&Qe(a.attributeNameCheck,t)||a.attributeNameCheck instanceof Function&&a.attributeNameCheck(t))||"is"===t&&a.allowCustomizedBuiltInElements&&(a.tagNameCheck instanceof RegExp&&Qe(a.tagNameCheck,n)||a.tagNameCheck instanceof Function&&a.tagNameCheck(n))))return!1}else if(!be[t]&&!Qe(ne,Ye(n,te,""))&&("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==gt(n,"data:")||!ye[e])&&(!le||Qe(ee,Ye(n,te,"")))&&n)return!1;return!0};return c.sanitize=function(e){let t=1\n"+a),b&&Ke([f,m,X],e=>{a=Ye(a,e," ")}),h&&x?h.createHTML(a):a},c.setConfig=function(){Ae(0{"use strict";class s{constructor(e,t){this.low=e,this.high=t,this.length=1+t-e}overlaps(e){return!(this.highe.high)}touches(e){return!(this.high+1e.high)}add(e){return new s(Math.min(this.low,e.low),Math.max(this.high,e.high))}subtract(e){return e.low<=this.low&&e.high>=this.high?[]:e.low>this.low&&e.highe+t.length,0)}add(e,t){var n=e=>{for(var t=0;t{for(var t=0;t{for(var t=0;t{for(var n=t.low;n<=t.high;)e.push(n),n++;return e},[])}subranges(){return this.ranges.map(e=>({low:e.low,high:e.high,length:1+e.high-e.low}))}}},37007:e=>{"use strict";var t="object"==typeof Reflect?Reflect:null,l=t&&"function"==typeof t.apply?t.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},n=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)},r=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}e.exports=o,e.exports.once=function(a,l){return new Promise(function(e,t){function n(e){a.removeListener(l,r),t(e)}function r(){"function"==typeof a.removeListener&&a.removeListener("error",n),e([].slice.call(arguments))}var o,s,i;f(a,l,r,{once:!0}),"error"!==l&&(s=n,i={once:!0},"function"==typeof(o=a).on&&f(o,"error",s,i))})},(o.EventEmitter=o).prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var s=10;function c(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function i(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function a(e,t,n,r){var o,s;return c(n),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener||n),o=e._events),s=o[t]),void 0===s?(s=o[t]=n,++e._eventsCount):("function"==typeof s?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),0<(o=i(e))&&s.length>o&&!s.warned&&(s.warned=!0,(r=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit")).name="MaxListenersExceededWarning",r.emitter=e,r.type=t,r.count=s.length,n=r,console&&console.warn&&console.warn(n))),e}function u(e,t,n){e={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},t=function(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}.bind(e);return t.listener=n,e.wrapFn=t}function p(e,t,n){e=e._events;if(void 0===e)return[];e=e[t];{if(void 0===e)return[];if("function"==typeof e)return n?[e.listener||e]:[e];if(n){for(var r=e,o=new Array(r.length),s=0;s{"use strict";var r=n(26311),n=o(Error);function o(t){return e.displayName=t.displayName||t.name,e;function e(e){return e=e&&r.apply(null,arguments),new t(e)}}(e.exports=n).eval=o(EvalError),n.range=o(RangeError),n.reference=o(ReferenceError),n.syntax=o(SyntaxError),n.type=o(TypeError),n.uri=o(URIError),n.create=o},26311:e=>{function n(t){function e(){return i[s++]}for(var n,r,o,s=1,i=[].slice.call(arguments),a=0,l=t.length,c="",u=!1,p=!1;a{"use strict";function l(e,t){for(var n=[],r=0;r{"use strict";n=n(89353);e.exports=Function.prototype.bind||n},70453:(e,t,n)=>{"use strict";var r,h=SyntaxError,o=Function,d=TypeError,s=function(e){try{return o('"use strict"; return ('+e+").constructor;")()}catch(e){}},f=Object.getOwnPropertyDescriptor;if(f)try{f({},"")}catch(e){f=null}function i(){throw new d}var a=f?function(){try{return i}catch(e){try{return f(arguments,"callee").get}catch(e){return i}}}():i,l=n(64039)(),c=n(80024)(),u=Object.getPrototypeOf||(c?function(e){return e.__proto__}:null),m={},c="undefined"!=typeof Uint8Array&&u?u(Uint8Array):r,g={"%AggregateError%":"undefined"==typeof AggregateError?r:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?r:ArrayBuffer,"%ArrayIteratorPrototype%":l&&u?u([][Symbol.iterator]()):r,"%AsyncFromSyncIteratorPrototype%":r,"%AsyncFunction%":m,"%AsyncGenerator%":m,"%AsyncGeneratorFunction%":m,"%AsyncIteratorPrototype%":m,"%Atomics%":"undefined"==typeof Atomics?r:Atomics,"%BigInt%":"undefined"==typeof BigInt?r:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?r:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?r:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?r:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?r:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?r:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?r:FinalizationRegistry,"%Function%":o,"%GeneratorFunction%":m,"%Int8Array%":"undefined"==typeof Int8Array?r:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?r:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?r:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":l&&u?u(u([][Symbol.iterator]())):r,"%JSON%":"object"==typeof JSON?JSON:r,"%Map%":"undefined"==typeof Map?r:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&l&&u?u((new Map)[Symbol.iterator]()):r,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?r:Promise,"%Proxy%":"undefined"==typeof Proxy?r:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?r:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?r:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&l&&u?u((new Set)[Symbol.iterator]()):r,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?r:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":l&&u?u(""[Symbol.iterator]()):r,"%Symbol%":l?Symbol:r,"%SyntaxError%":h,"%ThrowTypeError%":a,"%TypedArray%":c,"%TypeError%":d,"%Uint8Array%":"undefined"==typeof Uint8Array?r:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?r:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?r:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?r:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?r:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?r:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?r:WeakSet};if(u)try{null.error}catch(e){l=u(u(e));g["%Error.prototype%"]=l}function y(e){var t,n;return"%AsyncFunction%"===e?t=s("async function () {}"):"%GeneratorFunction%"===e?t=s("function* () {}"):"%AsyncGeneratorFunction%"===e?t=s("async function* () {}"):"%AsyncGenerator%"===e?(n=y("%AsyncGeneratorFunction%"))&&(t=n.prototype):"%AsyncIteratorPrototype%"===e&&(n=y("%AsyncGenerator%"))&&u&&(t=u(n.prototype)),g[e]=t}var v={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},a=n(66743),b=n(9957),w=a.call(Function.call,Array.prototype.concat),E=a.call(Function.apply,Array.prototype.splice),S=a.call(Function.call,String.prototype.replace),x=a.call(Function.call,String.prototype.slice),_=a.call(Function.call,RegExp.prototype.exec),k=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,A=/\\(\\)?/g;e.exports=function(e,t){if("string"!=typeof e||0===e.length)throw new d("intrinsic name must be a non-empty string");if(1=n.length?(l=!!(p=f(s,c)))&&"get"in p&&!("originalValue"in p.get)?p.get:s[c]:(l=b(s,c),s[c]),l&&!i&&(g[u]=s)}}return s}},75795:(e,t,n)=>{"use strict";n=n(70453)("%Object.getOwnPropertyDescriptor%",!0);if(n)try{n([],"length")}catch(e){n=null}e.exports=n},30592:(e,t,n)=>{"use strict";function r(){if(o)try{return o({},"a",{value:1}),!0}catch(e){return!1}return!1}var o=n(70453)("%Object.defineProperty%",!0);r.hasArrayLengthDefineBug=function(){if(!r())return null;try{return 1!==o([],"length",{value:1}).length}catch(e){return!0}},e.exports=r},80024:e=>{"use strict";var t={foo:{}},n=Object;e.exports=function(){return{__proto__:t}.foo===t.foo&&!({__proto__:null}instanceof n)}},64039:(e,t,n)=>{"use strict";var r="undefined"!=typeof Symbol&&Symbol,o=n(41333);e.exports=function(){return"function"==typeof r&&"function"==typeof Symbol&&"symbol"==typeof r("foo")&&"symbol"==typeof Symbol("bar")&&o()}},41333:e=>{"use strict";e.exports=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),n=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(n))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;n=Object.getOwnPropertySymbols(e);if(1!==n.length||n[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){n=Object.getOwnPropertyDescriptor(e,t);if(42!==n.value||!0!==n.enumerable)return!1}return!0}},9957:(e,t,n)=>{"use strict";var r=Function.prototype.call,o=Object.prototype.hasOwnProperty,n=n(66743);e.exports=n.call(r,o)},45981:e=>{function n(t){return t instanceof Map?t.clear=t.delete=t.set=function(){throw new Error("map is read-only")}:t instanceof Set&&(t.add=t.clear=t.delete=function(){throw new Error("set is read-only")}),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(function(e){e=t[e];"object"!=typeof e||Object.isFrozen(e)||n(e)}),t}var g=n;g.default=n;class P{constructor(e){void 0===e.data&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function u(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function l(e,...t){const n=Object.create(null);for(const t in e)n[t]=e[t];return t.forEach(function(e){for(const t in e)n[t]=e[t]}),n}const r=e=>!!e.kind;class t{constructor(e,t){this.buffer="",this.classPrefix=t.classPrefix,e.walk(this)}addText(e){this.buffer+=u(e)}openNode(t){if(r(t)){let e=t.kind;t.sublanguage||(e=""+this.classPrefix+e),this.span(e)}}closeNode(e){r(e)&&(this.buffer+="")}value(){return this.buffer}span(e){this.buffer+=``}}class o{constructor(){this.rootNode={children:[]},this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){this.top.children.push(e)}openNode(e){e={kind:e,children:[]};this.add(e),this.stack.push(e)}closeNode(){if(1this._walk(t,e)),t.closeNode(e)),t}static _collapse(e){"string"!=typeof e&&e.children&&(e.children.every(e=>"string"==typeof e)?e.children=[e.children.join("")]:e.children.forEach(e=>{o._collapse(e)}))}}class y extends o{constructor(e){super(),this.options=e}addKeyword(e,t){""!==e&&(this.openNode(t),this.addText(e),this.closeNode())}addText(e){""!==e&&this.add(e)}addSublanguage(e,t){const n=e.root;n.kind=t,n.sublanguage=!0,this.add(n)}toHTML(){return new t(this,this.options).value()}finalize(){return!0}}function c(e){return e?"string"==typeof e?e:e.source:null}function s(e,t,n={}){const r=l({className:"comment",begin:e,end:t,contains:[]},n);return r.contains.push(w),r.contains.push({className:"doctag",begin:"(?:TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):",relevance:0}),r}const p=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./,i="[a-zA-Z]\\w*",a="[a-zA-Z_]\\w*",h="\\b\\d+(\\.\\d+)?",d="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",f="\\b(0b[01]+)",m={begin:"\\\\[\\s\\S]",relevance:0},v={className:"string",begin:"'",end:"'",illegal:"\\n",contains:[m]},b={className:"string",begin:'"',end:'"',illegal:"\\n",contains:[m]},w={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},E=s("//","$"),S=s("/\\*","\\*/"),x=s("#","$"),C={className:"number",begin:h,relevance:0},j={className:"number",begin:d,relevance:0},B={className:"number",begin:f,relevance:0},L={className:"number",begin:h+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},q={begin:/(?=\/[^/\n]*\/)/,contains:[{className:"regexp",begin:/\//,end:/\/[gimuy]*/,illegal:/\n/,contains:[m,{begin:/\[/,end:/\]/,relevance:0,contains:[m]}]}]},$={className:"title",begin:i,relevance:0},z={className:"title",begin:a,relevance:0},U={begin:"\\.\\s*"+a,relevance:0};var N=Object.freeze({__proto__:null,MATCH_NOTHING_RE:/\b\B/,IDENT_RE:i,UNDERSCORE_IDENT_RE:a,NUMBER_RE:h,C_NUMBER_RE:d,BINARY_NUMBER_RE:f,RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(e={})=>{var t=/^#![ ]*\//;return e.binary&&(e.begin=[t,/.*\b/,e.binary,/\b.*/].map(e=>c(e)).join("")),l({className:"meta",begin:t,end:/$/,relevance:0,"on:begin":(e,t)=>{0!==e.index&&t.ignoreMatch()}},e)},BACKSLASH_ESCAPE:m,APOS_STRING_MODE:v,QUOTE_STRING_MODE:b,PHRASAL_WORDS_MODE:w,COMMENT:s,C_LINE_COMMENT_MODE:E,C_BLOCK_COMMENT_MODE:S,HASH_COMMENT_MODE:x,NUMBER_MODE:C,C_NUMBER_MODE:j,BINARY_NUMBER_MODE:B,CSS_NUMBER_MODE:L,REGEXP_MODE:q,TITLE_MODE:$,UNDERSCORE_TITLE_MODE:z,METHOD_GUARD:U,END_SAME_AS_BEGIN:function(e){return Object.assign(e,{"on:begin":(e,t)=>{t.data._beginMatch=e[1]},"on:end":(e,t)=>{t.data._beginMatch!==e[1]&&t.ignoreMatch()}})}});function V(e,t){"."===e.input[e.index-1]&&t.ignoreMatch()}const K=["of","and","for","in","not","or","if","then","parent","list","value"],W="keyword";function _(t,r,e=W){const o={};return"string"==typeof t?n(e,t.split(" ")):Array.isArray(t)?n(e,t):Object.keys(t).forEach(function(e){Object.assign(o,_(t[e],r,e))}),o;function n(n,e){(e=r?e.map(e=>e.toLowerCase()):e).forEach(function(e){var t,e=e.split("|");o[e[0]]=[n,(t=e[0],(e=e[1])?Number(e):function(e){return K.includes(e.toLowerCase())}(t)?0:1)]})}}function J(s,{}){function i(e,t){return new RegExp(c(e),"m"+(s.case_insensitive?"i":"")+(t?"g":""))}class t{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(e,t){t.position=this.position++,this.matchIndexes[this.matchAt]=t,this.regexes.push([t,e]),this.matchAt+=new RegExp(e.toString()+"|").exec("").length-1+1}compile(){0===this.regexes.length&&(this.exec=()=>null);var e=this.regexes.map(e=>e[1]);this.matcherRe=i(function(e,t="|"){let o=0;return e.map(e=>{var t=o+=1;let n=c(e),r="";for(;0`(${e})`).join(t)}(e),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex;const t=this.matcherRe.exec(e);if(!t)return null;var e=t.findIndex((e,t)=>0n.addRule(e,t)),n.compile(),this.multiRegexes[e]=n}resumingScanAtSamePosition(){return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(e,t){this.rules.push([e,t]),"begin"===t.type&&this.count++}exec(e){const t=this.getMatcher(this.regexIndex);t.lastIndex=this.lastIndex;let n=t.exec(e);if(this.resumingScanAtSamePosition()&&(!n||n.index!==this.lastIndex)){const t=this.getMatcher(0);t.lastIndex=this.lastIndex+1,n=t.exec(e)}return n&&(this.regexIndex+=n.position+1,this.regexIndex===this.count&&this.considerAll()),n}}if(s.compilerExtensions||(s.compilerExtensions=[]),s.contains&&s.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return s.classNameAliases=l(s.classNameAliases||{}),function t(n,r){const o=n;if(n.isCompiled)return o;[function(e,t){if(e.match){if(e.begin||e.end)throw new Error("begin & end are not supported with match");e.begin=e.match,delete e.match}}].forEach(e=>e(n,r)),s.compilerExtensions.forEach(e=>e(n,r)),n.__beforeBegin=null,[function(e,t){t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",e.__beforeBegin=V,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,void 0===e.relevance&&(e.relevance=0))},function(e,t){Array.isArray(e.illegal)&&(e.illegal=([...e]=[...e.illegal],"("+e.map(e=>c(e)).join("|")+")"))},function(e,t){void 0===e.relevance&&(e.relevance=1)}].forEach(e=>e(n,r)),n.isCompiled=!0;let e=null;if("object"==typeof n.keywords&&(e=n.keywords.$pattern,delete n.keywords.$pattern),n.keywords&&(n.keywords=_(n.keywords,s.case_insensitive)),n.lexemes&&e)throw new Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) ");return e=e||n.lexemes||/\w+/,o.keywordPatternRe=i(e,!0),r&&(n.begin||(n.begin=/\B|\b/),o.beginRe=i(n.begin),n.endSameAsBegin&&(n.end=n.begin),n.end||n.endsWithParent||(n.end=/\B|\b/),n.end&&(o.endRe=i(n.end)),o.terminatorEnd=c(n.end)||"",n.endsWithParent&&r.terminatorEnd&&(o.terminatorEnd+=(n.end?"|":"")+r.terminatorEnd)),n.illegal&&(o.illegalRe=i(n.illegal)),n.contains||(n.contains=[]),n.contains=[].concat(...n.contains.map(function(e){return(t="self"===e?n:e).variants&&!t.cachedVariants&&(t.cachedVariants=t.variants.map(function(e){return l(t,{variants:null},e)})),t.cachedVariants||(function e(t){return!!t&&(t.endsWithParent||e(t.starts))}(t)?l(t,{starts:t.starts?l(t.starts):null}):Object.isFrozen(t)?l(t):t);var t})),n.contains.forEach(function(e){t(e,o)}),n.starts&&t(n.starts,r),o.matcher=function(e){const t=new a;return e.contains.forEach(e=>t.addRule(e.begin,{rule:e,type:"begin"})),e.terminatorEnd&&t.addRule(e.terminatorEnd,{type:"end"}),e.illegal&&t.addRule(e.illegal,{type:"illegal"}),t}(o),o}(s)}function H(t){const n={props:["language","code","autodetect"],data:function(){return{detectedLanguage:"",unknownLanguage:!1}},computed:{className(){return this.unknownLanguage?"":"hljs "+this.detectedLanguage},highlighted(){if(!this.autoDetect&&!t.getLanguage(this.language))return console.warn(`The language "${this.language}" you specified could not be found.`),this.unknownLanguage=!0,u(this.code);let e={};return this.autoDetect?(e=t.highlightAuto(this.code),this.detectedLanguage=e.language):(e=t.highlight(this.language,this.code,this.ignoreIllegals),this.detectedLanguage=this.language),e.value},autoDetect(){return!this.language||(e=this.autodetect,Boolean(e||""===e));var e},ignoreIllegals:()=>!0},render(e){return e("pre",{},[e("code",{class:this.className,domProps:{innerHTML:this.highlighted}})])}};return{Component:n,VuePlugin:{install(e){e.component("highlightjs",n)}}}}const G={"after:highlightElement":({el:e,result:t,text:n})=>{e=A(e);if(e.length){const r=document.createElement("div");r.innerHTML=t.value,t.value=function(t,e,n){let r=0,o="";const s=[];function i(){return t.length&&e.length?t[0].offset!==e[0].offset?t[0].offset"}function l(e){o+=""}function c(e){("start"===e.event?a:l)(e.node)}for(;t.length||e.length;){let e=i();if(o+=u(n.substring(r,e[0].offset)),r=e[0].offset,e===t){for(s.reverse().forEach(l);c(e.splice(0,1)[0]),(e=i())===t&&e.length&&e[0].offset===r;);s.reverse().forEach(a)}else"start"===e[0].event?s.push(e[0].node):s.pop(),c(e.splice(0,1)[0])}return o+u(n.substr(r))}(e,A(r),n)}}};function k(e){return e.nodeName.toLowerCase()}function A(e){const o=[];return function t(n,r){for(let e=n.firstChild;e;e=e.nextSibling)3===e.nodeType?r+=e.nodeValue.length:1===e.nodeType&&(o.push({event:"start",offset:r,node:e}),r=t(e,r),k(e).match(/br|hr|img|input/)||o.push({event:"stop",offset:r,node:e}));return r}(e,0),o}const O={},I=e=>{console.error(e)},T=(e,...t)=>{console.log("WARN: "+e,...t)},R=(e,t)=>{O[e+"/"+t]||(console.log(`Deprecated as of ${e}. `+t),O[e+"/"+t]=!0)},M=u,D=l,F=Symbol("nomatch");var Y=function(r){const S=Object.create(null),s=Object.create(null),x=[];let _=!0;const t=/(^(<[^>]+>|\t|)+|\n)/gm,k="Could not find the language '{}', did you forget to load/include a language module?",l={disableAutodetect:!0,name:"Plain text",contains:[]};let A={noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:null,__emitter:y};function i(e){return A.noHighlightRe.test(e)}function a(e,t,n,r){let o="",s="";"object"==typeof t?(o=e,n=t.ignoreIllegals,s=t.language,r=void 0):(R("10.7.0","highlight(lang, code, ...args) has been deprecated."),R("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),s=e,o=t);e={code:o,language:s};m("before:highlight",e);const i=e.result||O(e.language,e.code,n,r);return i.code=e.code,m("after:highlight",i),i}function O(r,o,s,e){function i(){(null!=d.subLanguage?function(){if(""!==g){let e=null;if("string"==typeof d.subLanguage){if(!S[d.subLanguage])return m.addText(g);e=O(d.subLanguage,g,!0,f[d.subLanguage]),f[d.subLanguage]=e.top}else e=C(g,d.subLanguage.length?d.subLanguage:null);0")+'"');throw r.mode=d,r}if("end"===t.type){const r=c(t);if(r!==F)return r}if("illegal"===t.type&&""===n)return 1;if(1e53*t.index)throw new Error("potential infinite loop, way more iterations than matches");return g+=n,n.length}const p=j(r);if(!p)throw I(k.replace("{}",r)),new Error('Unknown language: "'+r+'"');var n=J(p,{plugins:x});let h="",d=e||n;const f={},m=new A.__emitter(A);{const E=[];for(let e=d;e!==p;e=e.parent)e.className&&E.unshift(e.className);E.forEach(e=>m.openNode(e))}let g="",y=0,v=0,b=0,w=!1;try{for(d.matcher.considerAll();;){b++,w?w=!1:d.matcher.considerAll(),d.matcher.lastIndex=v;const r=d.matcher.exec(o);if(!r)break;const S=t(o.substring(v,r.index),r);v=r.index+S}return t(o.substr(v)),m.closeAllNodes(),m.finalize(),h=m.toHTML(),{relevance:Math.floor(y),value:h,language:r,illegal:!1,emitter:m,top:d}}catch(e){if(e.message&&e.message.includes("Illegal"))return{illegal:!0,illegalBy:{msg:e.message,context:o.slice(v-100,v+100),mode:e.mode},sofar:h,relevance:0,value:M(o),emitter:m};if(_)return{illegal:!1,relevance:0,value:M(o),emitter:m,language:r,top:d,errorRaised:e};throw e}}function C(t,e){e=e||A.languages||Object.keys(S);const n=function(e){const t={relevance:0,emitter:new A.__emitter(A),value:M(e),illegal:!1,top:l};return t.emitter.addText(e),t}(t),r=e.filter(j).filter(f).map(e=>O(e,t,!1)),o=(r.unshift(n),r.sort((e,t)=>{if(e.relevance!==t.relevance)return t.relevance-e.relevance;if(e.language&&t.language){if(j(e.language).supersetOf===t.language)return 1;if(j(t.language).supersetOf===e.language)return-1}return 0})),[s,i]=o,a=s;return a.second_best=i,a}const e={"before:highlightElement":({el:e})=>{A.useBR&&(e.innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n"))},"after:highlightElement":({result:e})=>{A.useBR&&(e.value=e.value.replace(/\n/g,"
"))}},n=/^(<[^>]+>|\t)+/gm,o={"after:highlightElement":({result:e})=>{A.tabReplace&&(e.value=e.value.replace(n,e=>e.replace(/\t/g,A.tabReplace)))}};function c(e){var t,n,r,o=function(e){let t=e.className+" ";t+=e.parentNode?e.parentNode.className:"";var n=A.languageDetectRe.exec(t);if(n){const t=j(n[1]);return t||(T(k.replace("{}",n[1])),T("Falling back to no-highlight mode for this block.",e)),t?n[1]:"no-highlight"}return t.split(/\s+/).find(e=>i(e)||j(e))}(e);i(o)||(m("before:highlightElement",{el:e,language:o}),n=e.textContent,m("after:highlightElement",{el:e,result:t=o?a(n,{language:o,ignoreIllegals:!0}):C(n),text:n}),e.innerHTML=t.value,n=e,o=o,r=t.language,o=o?s[o]:r,n.classList.add("hljs"),o&&n.classList.add(o),e.result={language:t.language,re:t.relevance,relavance:t.relevance},t.second_best&&(e.second_best={language:t.second_best.language,re:t.second_best.relevance,relavance:t.second_best.relevance}))}const u=()=>{u.called||(u.called=!0,R("10.6.0","initHighlighting() is deprecated. Use highlightAll() instead."),document.querySelectorAll("pre code").forEach(c))};let p=!1;function h(){"loading"===document.readyState?p=!0:document.querySelectorAll("pre code").forEach(c)}function j(e){return e=(e||"").toLowerCase(),S[e]||S[s[e]]}function d(e,{languageName:t}){(e="string"==typeof e?[e]:e).forEach(e=>{s[e.toLowerCase()]=t})}function f(e){e=j(e);return e&&!e.disableAutodetect}function m(e,t){const n=e;x.forEach(function(e){e[n]&&e[n](t)})}"undefined"!=typeof window&&window.addEventListener&&window.addEventListener("DOMContentLoaded",function(){p&&h()},!1),Object.assign(r,{highlight:a,highlightAuto:C,highlightAll:h,fixMarkup:function(e){return R("10.2.0","fixMarkup will be removed entirely in v11.0"),R("10.2.0","Please see https://github.com/highlightjs/highlight.js/issues/2534"),e=e,A.tabReplace||A.useBR?e.replace(t,e=>"\n"===e?A.useBR?"
":e:A.tabReplace?e.replace(/\t/g,A.tabReplace):e):e},highlightElement:c,highlightBlock:function(e){return R("10.7.0","highlightBlock will be removed entirely in v12.0"),R("10.7.0","Please use highlightElement now."),c(e)},configure:function(e){e.useBR&&(R("10.3.0","'useBR' will be removed entirely in v11.0"),R("10.3.0","Please see https://github.com/highlightjs/highlight.js/issues/2559")),A=D(A,e)},initHighlighting:u,initHighlightingOnLoad:function(){R("10.6.0","initHighlightingOnLoad() is deprecated. Use highlightAll() instead."),p=!0},registerLanguage:function(t,e){let n=null;try{n=e(r)}catch(e){if(I("Language definition for '{}' could not be registered.".replace("{}",t)),!_)throw e;I(e),n=l}n.name||(n.name=t),(S[t]=n).rawDefinition=e.bind(null,r),n.aliases&&d(n.aliases,{languageName:t})},unregisterLanguage:function(e){delete S[e];for(const t of Object.keys(s))s[t]===e&&delete s[t]},listLanguages:function(){return Object.keys(S)},getLanguage:j,registerAliases:d,requireLanguage:function(e){R("10.4.0","requireLanguage will be removed entirely in v11."),R("10.4.0","Please see https://github.com/highlightjs/highlight.js/pull/2844");var t=j(e);if(t)return t;throw new Error("The '{}' language is required, but not loaded.".replace("{}",e))},autoDetection:f,inherit:D,addPlugin:function(e){var t;(t=e)["before:highlightBlock"]&&!t["before:highlightElement"]&&(t["before:highlightElement"]=e=>{t["before:highlightBlock"](Object.assign({block:e.el},e))}),t["after:highlightBlock"]&&!t["after:highlightElement"]&&(t["after:highlightElement"]=e=>{t["after:highlightBlock"](Object.assign({block:e.el},e))}),x.push(e)},vuePlugin:H(r).VuePlugin}),r.debugMode=function(){_=!1},r.safeMode=function(){_=!0},r.versionString="10.7.3";for(const r in N)"object"==typeof N[r]&&g(N[r]);return Object.assign(r,N),r.addPlugin(e),r.addPlugin(G),r.addPlugin(o),r}({});e.exports=Y},35344:e=>{e.exports=function(e){var t={},n={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[t]}]};Object.assign(t,{className:"variable",variants:[{begin:[/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])"].map(e=>{return e?"string"==typeof e?e:e.source:null}).join("")},n]});const r={className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},o={begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},s={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,t,r]};r.contains.push(s);var n={begin:/\$\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,t]},i=e.SHEBANG({binary:`(${["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"].join("|")})`,relevance:10}),a={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z._-]+\b/,keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp"},contains:[i,e.SHEBANG(),a,n,e.HASH_COMMENT_MODE,o,s,{className:"",begin:/\\"/},{className:"string",begin:/'/,end:/'/},t]}}},73402:e=>{e.exports=function(e){var t="HTTP/(2|1\\.[01])",n={className:"attribute",begin:["^",/[A-Za-z][A-Za-z0-9-]*/,"(?=\\:\\s)"].map(e=>{return e?"string"==typeof e?e:e.source:null}).join(""),starts:{contains:[{className:"punctuation",begin:/: /,relevance:0,starts:{end:"$",relevance:0}}]}},r=[n,{begin:"\\n\\n",starts:{subLanguage:[],endsWithParent:!0}}];return{name:"HTTP",aliases:["https"],illegal:/\S/,contains:[{begin:"^(?="+t+" \\d{3})",end:/$/,contains:[{className:"meta",begin:t},{className:"number",begin:"\\b\\d{3}\\b"}],starts:{end:/\b\B/,illegal:/\S/,contains:r}},{begin:"(?=^[A-Z]+ (.*?) "+t+"$)",end:/$/,contains:[{className:"string",begin:" ",end:" ",excludeBegin:!0,excludeEnd:!0},{className:"meta",begin:t},{className:"keyword",begin:"[A-Z]+"}],starts:{end:/\b\B/,illegal:/\S/,contains:r}},e.inherit(n,{relevance:0})]}}},95089:e=>{const b="[A-Za-z$_][0-9A-Za-z$_]*",w=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends"],E=["true","false","null","undefined","NaN","Infinity"],S=[].concat(["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],["arguments","this","super","console","window","document","localStorage","module","global"],["Intl","DataView","Number","Math","Date","String","RegExp","Object","Function","Boolean","Error","Symbol","Set","Map","WeakSet","WeakMap","Proxy","Reflect","JSON","Promise","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Float32Array","Array","Uint8Array","Uint8ClampedArray","ArrayBuffer","BigInt64Array","BigUint64Array","BigInt"],["EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"]);function x(e){return _("(?=",e,")")}function _(...e){return e.map(e=>{return e?"string"==typeof e?e:e.source:null}).join("")}e.exports=function(e){const t=b,n=/<[A-Za-z0-9\\._:-]+/,r=/\/[A-Za-z0-9\\._:-]+>|\/>/,o=(e,t)=>{var n=e[0].length+e.index,r=e.input[n];"<"!==r?">"===r&&([r,e]=[e,{after:n}["after"]],n="",returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:y}]}]},{begin:/,/,relevance:0},{className:"",begin:/\s/,end:/\s*/,skip:!0},{variants:[{begin:"<>",end:""},{begin:n,"on:begin":o,end:r}],subLanguage:"xml",contains:[{begin:n,end:r,skip:!0,contains:["self"]}]}],relevance:0},{className:"function",beginKeywords:"function",end:/[{;]/,excludeEnd:!0,keywords:s,contains:["self",e.inherit(e.TITLE_MODE,{begin:t}),v],illegal:/%/},{beginKeywords:"while if switch catch for"},{className:"function",begin:e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,contains:[v,e.inherit(e.TITLE_MODE,{begin:t})]},{variants:[{begin:"\\."+t},{begin:"\\$"+t}],relevance:0},{className:"class",beginKeywords:"class",end:/[{;=]/,excludeEnd:!0,illegal:/[:"[\]]/,contains:[{beginKeywords:"extends"},e.UNDERSCORE_TITLE_MODE]},{begin:/\b(?=constructor)/,end:/[{;]/,excludeEnd:!0,contains:[e.inherit(e.TITLE_MODE,{begin:t}),"self",v]},{begin:"(get|set)\\s+(?="+t+"\\()",end:/\{/,keywords:"get set",contains:[e.inherit(e.TITLE_MODE,{begin:t}),{begin:/\(\)/},v]},{begin:/\$[(.]/}]}}},65772:e=>{e.exports=function(e){const t={literal:"true false null"},n=[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],r=[e.QUOTE_STRING_MODE,e.C_NUMBER_MODE],o={end:",",endsWithParent:!0,excludeEnd:!0,contains:r,keywords:t},s={begin:/\{/,end:/\}/,contains:[{className:"attr",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE],illegal:"\\n"},e.inherit(o,{begin:/:/})].concat(n),illegal:"\\S"},i={begin:"\\[",end:"\\]",contains:[e.inherit(o)],illegal:"\\S"};return r.push(s,i),n.forEach(function(e){r.push(e)}),{name:"JSON",contains:r,keywords:t,illegal:"\\S"}}},26571:e=>{e.exports=function(e){const t={$pattern:/-?[A-z\.\-]+\b/,keyword:"if else foreach return do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch hidden static parameter",built_in:"ac asnp cat cd CFS chdir clc clear clhy cli clp cls clv cnsn compare copy cp cpi cpp curl cvpa dbp del diff dir dnsn ebp echo|0 epal epcsv epsn erase etsn exsn fc fhx fl ft fw gal gbp gc gcb gci gcm gcs gdr gerr ghy gi gin gjb gl gm gmo gp gps gpv group gsn gsnp gsv gtz gu gv gwmi h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi iwr kill lp ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv oh popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo rni rnp rp rsn rsnp rujb rv rvpa rwmi sajb sal saps sasv sbp sc scb select set shcm si sl sleep sls sort sp spjb spps spsv start stz sujb sv swmi tee trcm type wget where wjb write"},n={begin:"`[\\s\\S]",relevance:0},r={className:"variable",variants:[{begin:/\$\B/},{className:"keyword",begin:/\$this/},{begin:/\$[\w\d][\w\d_:]*/}]},o={className:"string",variants:[{begin:/"/,end:/"/},{begin:/@"/,end:/^"@/}],contains:[n,r,{className:"variable",begin:/\$[A-z]/,end:/[^A-z]/}]},s={className:"string",variants:[{begin:/'/,end:/'/},{begin:/@'/,end:/^'@/}]},i=e.inherit(e.COMMENT(null,null),{variants:[{begin:/#/,end:/$/},{begin:/<#/,end:/#>/}],contains:[{className:"doctag",variants:[{begin:/\.(synopsis|description|example|inputs|outputs|notes|link|component|role|functionality)/},{begin:/\.(parameter|forwardhelptargetname|forwardhelpcategory|remotehelprunspace|externalhelp)\s+\S+/}]}]}),a={className:"built_in",variants:[{begin:"(".concat("Add|Clear|Close|Copy|Enter|Exit|Find|Format|Get|Hide|Join|Lock|Move|New|Open|Optimize|Pop|Push|Redo|Remove|Rename|Reset|Resize|Search|Select|Set|Show|Skip|Split|Step|Switch|Undo|Unlock|Watch|Backup|Checkpoint|Compare|Compress|Convert|ConvertFrom|ConvertTo|Dismount|Edit|Expand|Export|Group|Import|Initialize|Limit|Merge|Mount|Out|Publish|Restore|Save|Sync|Unpublish|Update|Approve|Assert|Build|Complete|Confirm|Deny|Deploy|Disable|Enable|Install|Invoke|Register|Request|Restart|Resume|Start|Stop|Submit|Suspend|Uninstall|Unregister|Wait|Debug|Measure|Ping|Repair|Resolve|Test|Trace|Connect|Disconnect|Read|Receive|Send|Write|Block|Grant|Protect|Revoke|Unblock|Unprotect|Use|ForEach|Sort|Tee|Where",")+(-)[\\w\\d]+")}]},l={className:"class",beginKeywords:"class enum",end:/\s*[{]/,excludeEnd:!0,relevance:0,contains:[e.TITLE_MODE]},c={className:"function",begin:/function\s+/,end:/\s*\{|$/,excludeEnd:!0,returnBegin:!0,relevance:0,contains:[{begin:"function",relevance:0,className:"keyword"},{className:"title",begin:/\w[\w\d]*((-)[\w\d]+)*/,relevance:0},{begin:/\(/,end:/\)/,className:"params",relevance:0,contains:[r]}]},u={begin:/using\s/,end:/$/,returnBegin:!0,contains:[o,s,{className:"keyword",begin:/(using|assembly|command|module|namespace|type)/}]},p={variants:[{className:"operator",begin:"(".concat("-and|-as|-band|-bnot|-bor|-bxor|-casesensitive|-ccontains|-ceq|-cge|-cgt|-cle|-clike|-clt|-cmatch|-cne|-cnotcontains|-cnotlike|-cnotmatch|-contains|-creplace|-csplit|-eq|-exact|-f|-file|-ge|-gt|-icontains|-ieq|-ige|-igt|-ile|-ilike|-ilt|-imatch|-in|-ine|-inotcontains|-inotlike|-inotmatch|-ireplace|-is|-isnot|-isplit|-join|-le|-like|-lt|-match|-ne|-not|-notcontains|-notin|-notlike|-notmatch|-or|-regex|-replace|-shl|-shr|-split|-wildcard|-xor",")\\b")},{className:"literal",begin:/(-)[\w\d]+/,relevance:0}]},h={className:"function",begin:/\[.*\]\s*[\w]+[ ]??\(/,end:/$/,returnBegin:!0,relevance:0,contains:[{className:"keyword",begin:"(".concat(t.keyword.toString().replace(/\s/g,"|"),")\\b"),endsParent:!0,relevance:0},e.inherit(e.TITLE_MODE,{endsParent:!0})]},d=[h,i,n,e.NUMBER_MODE,o,s,a,r,{className:"literal",begin:/\$(null|true|false)\b/},{className:"selector-tag",begin:/@\B/,relevance:0}],f={begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0,relevance:0,contains:[].concat("self",d,{begin:"("+["string","char","byte","int","long","bool","decimal","single","double","DateTime","xml","array","hashtable","void"].join("|")+")",className:"built_in",relevance:0},{className:"type",begin:/[\.\w\d]+/,relevance:0})};return h.contains.unshift(f),{name:"PowerShell",aliases:["ps","ps1"],case_insensitive:!0,keywords:t,contains:d.concat(l,c,u,p,f)}}},17285:e=>{function l(e){return e?"string"==typeof e?e:e.source:null}function c(e){return u("(?=",e,")")}function u(...e){return e.map(e=>l(e)).join("")}e.exports=function(e){var t=u(/[A-Z_]/,u("(",/[A-Z0-9_.-]*:/,")?"),/[A-Z0-9_.-]*/),n={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},r={begin:/\s/,contains:[{className:"meta-keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},o=e.inherit(r,{begin:/\(/,end:/\)/}),s=e.inherit(e.APOS_STRING_MODE,{className:"meta-string"}),i=e.inherit(e.QUOTE_STRING_MODE,{className:"meta-string"}),a={endsWithParent:!0,illegal:/`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,contains:[{className:"meta",begin://,relevance:10,contains:[r,i,s,o,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin://,contains:[r,o,i,s]}]}]},e.COMMENT(//,{relevance:10}),{begin://,relevance:10},n,{className:"meta",begin:/<\?xml/,end:/\?>/,relevance:10},{className:"tag",begin:/)/,end:/>/,keywords:{name:"style"},contains:[a],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/)/,end:/>/,keywords:{name:"script"},contains:[a],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:u(//,/>/,/\s/].map(e=>l(e)).join("|")+")"))),end:/\/?>/,contains:[{className:"name",begin:t,relevance:0,starts:a}]},{className:"tag",begin:u(/<\//,c(u(t,/>/))),contains:[{className:"name",begin:t,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}},17533:e=>{e.exports=function(e){var t="true false yes no null",n="[\\w#;/?:@&=+$,.~*'()[\\]]+",r={className:"string",relevance:0,variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},o=e.inherit(r,{variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),s={end:",",endsWithParent:!0,excludeEnd:!0,keywords:t,relevance:0},n=[{className:"attr",variants:[{begin:"\\w[\\w :\\/.-]*:(?=[ \t]|$)"},{begin:'"\\w[\\w :\\/.-]*":(?=[ \t]|$)'},{begin:"'\\w[\\w :\\/.-]*':(?=[ \t]|$)"}]},{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+n},{className:"type",begin:"!<"+n+">"},{className:"type",begin:"!"+n},{className:"type",begin:"!!"+n},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:t,keywords:{literal:t}},{className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},{begin:/\{/,end:/\}/,contains:[s],illegal:"\\n",relevance:0},{begin:"\\[",end:"\\]",contains:[s],illegal:"\\n",relevance:0},r],t=[...n];return t.pop(),t.push(o),s.contains=t,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:n}}},251:(e,t)=>{t.read=function(e,t,n,r,o){var s,i,a=8*o-r-1,l=(1<>1,u=-7,p=n?o-1:0,h=n?-1:1,o=e[t+p];for(p+=h,s=o&(1<<-u)-1,o>>=-u,u+=a;0>=-u,u+=r;0>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=r?0:s-1,d=r?1:-1,s=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,i=c):(i=Math.floor(Math.log(t)/Math.LN2),t*(r=Math.pow(2,-i))<1&&(i--,r*=2),2<=(t+=1<=i+u?p/r:p*Math.pow(2,1-u))*r&&(i++,r/=2),c<=i+u?(a=0,i=c):1<=i+u?(a=(t*r-1)*Math.pow(2,o),i+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,o),i=0));8<=o;e[n+h]=255&a,h+=d,a/=256,o-=8);for(i=i<>>0;if(""+n!==t||4294967295==n)return NaN;t=n}return t<0?H(e)+t:t}function Y(){return!0}function X(e,t,n){return(0===e||void 0!==n&&e<=-n)&&(void 0===t||void 0!==n&&n<=t)}function Q(e,t){return ee(e,t,0)}function Z(e,t){return ee(e,t,t)}function ee(e,t,n){return void 0===e?n:e<0?Math.max(0,t+e):void 0===t?e:Math.min(t,e)}var te=0,h=1,ne=2,re="function"==typeof Symbol&&Symbol.iterator,oe="@@iterator",se=re||oe;function d(e){this.next=e}function f(e,t,n,r){e=0===e?t:1===e?n:[t,n];return r?r.value=e:r={value:e,done:!1},r}function m(){return{value:void 0,done:!0}}function ie(e){return ce(e)}function ae(e){return e&&"function"==typeof e.next}function le(e){var t=ce(e);return t&&t.call(e)}function ce(e){e=e&&(re&&e[re]||e[oe]);if("function"==typeof e)return e}function ue(e){return e&&"number"==typeof e.length}function n(e){{if(null==e)return Se();if(u(e))return e.toSeq();var t=ke(e)||"object"==typeof e&&new ve(e);if(t)return t;throw new TypeError("Expected Array or iterable object of values, or keyed object: "+e)}}function pe(e){return null==e?Se().toKeyedSeq():u(e)?c(e)?e.toSeq():e.fromEntrySeq():xe(e)}function g(e){return null==e?Se():u(e)?c(e)?e.entrySeq():e.toIndexedSeq():_e(e)}function he(e){return(null==e?Se():u(e)?c(e)?e.entrySeq():e:_e(e)).toSetSeq()}d.prototype.toString=function(){return"[Iterator]"},d.KEYS=te,d.VALUES=h,d.ENTRIES=ne,d.prototype.inspect=d.prototype.toSource=function(){return this.toString()},d.prototype[se]=function(){return this},e(n,l),n.of=function(){return n(arguments)},n.prototype.toSeq=function(){return this},n.prototype.toString=function(){return this.__toString("Seq {","}")},n.prototype.cacheResult=function(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this},n.prototype.__iterate=function(e,t){return Ae(this,e,t,!0)},n.prototype.__iterator=function(e,t){return Oe(this,e,t,!0)},e(pe,n),pe.prototype.toKeyedSeq=function(){return this},e(g,n),g.of=function(){return g(arguments)},g.prototype.toIndexedSeq=function(){return this},g.prototype.toString=function(){return this.__toString("Seq [","]")},g.prototype.__iterate=function(e,t){return Ae(this,e,t,!1)},g.prototype.__iterator=function(e,t){return Oe(this,e,t,!1)},e(he,n),he.of=function(){return he(arguments)},he.prototype.toSetSeq=function(){return this},n.isSeq=Ee,n.Keyed=pe,n.Set=he,n.Indexed=g;var de,fe,me,ge="@@__IMMUTABLE_SEQ__@@";function ye(e){this._array=e,this.size=e.length}function ve(e){var t=Object.keys(e);this._object=e,this._keys=t,this.size=t.length}function be(e){this._iterable=e,this.size=e.length||e.size}function we(e){this._iterator=e,this._iteratorCache=[]}function Ee(e){return!(!e||!e[ge])}function Se(){return de=de||new ye([])}function xe(e){var t=Array.isArray(e)?new ye(e).fromEntrySeq():ae(e)?new we(e).fromEntrySeq():ie(e)?new be(e).fromEntrySeq():"object"==typeof e?new ve(e):void 0;if(t)return t;throw new TypeError("Expected Array or iterable object of [k, v] entries, or keyed object: "+e)}function _e(e){var t=ke(e);if(t)return t;throw new TypeError("Expected Array or iterable object of values: "+e)}function ke(e){return ue(e)?new ye(e):ae(e)?new we(e):ie(e)?new be(e):void 0}function Ae(e,t,n,r){var o=e._cache;if(o){for(var s=o.length-1,i=0;i<=s;i++){var a=o[n?s-i:i];if(!1===t(a[1],r?a[0]:i,e))return i+1}return i}return e.__iterateUncached(t,n)}function Oe(e,t,n,r){var o,s,i=e._cache;return i?(o=i.length-1,s=0,new d(function(){var e=i[n?o-s:s];return s++>o?m():f(t,r?e[0]:s-1,e[1])})):e.__iteratorUncached(t,n)}function Ce(e,t){return t?function n(r,o,e,t){return Array.isArray(o)?r.call(t,e,g(o).map(function(e,t){return n(r,e,t,o)})):Pe(o)?r.call(t,e,pe(o).map(function(e,t){return n(r,e,t,o)})):o}(t,e,"",{"":e}):je(e)}function je(e){return Array.isArray(e)?g(e).map(je).toList():Pe(e)?pe(e).map(je).toMap():e}function Pe(e){return e&&(e.constructor===Object||void 0===e.constructor)}function v(e,t){if(e===t||e!=e&&t!=t)return!0;if(!e||!t)return!1;if("function"==typeof e.valueOf&&"function"==typeof t.valueOf){if((e=e.valueOf())===(t=t.valueOf())||e!=e&&t!=t)return!0;if(!e||!t)return!1}return!("function"!=typeof e.equals||"function"!=typeof t.equals||!e.equals(t))}function Ne(n,e){if(n===e)return!0;if(!u(e)||void 0!==n.size&&void 0!==e.size&&n.size!==e.size||void 0!==n.__hash&&void 0!==e.__hash&&n.__hash!==e.__hash||c(n)!==c(e)||p(n)!==p(e)||B(n)!==B(e))return!1;if(0===n.size&&0===e.size)return!0;var r,o=!F(n);if(B(n))return r=n.entries(),e.every(function(e,t){var n=r.next().value;return n&&v(n[1],e)&&(o||v(n[0],t))})&&r.next().done;var s=!1,i=(void 0===n.size&&(void 0===e.size?"function"==typeof n.cacheResult&&n.cacheResult():(s=!0,t=n,n=e,e=t)),!0),t=e.__iterate(function(e,t){if(o?!n.has(e):s?!v(e,n.get(t,x)):!v(n.get(t,x),e))return i=!1});return i&&n.size===t}function s(e,t){if(!(this instanceof s))return new s(e,t);if(this._value=e,this.size=void 0===t?1/0:Math.max(0,t),0===this.size){if(fe)return fe;fe=this}}function Ie(e,t){if(!e)throw new Error(t)}function i(e,t,n){if(!(this instanceof i))return new i(e,t,n);if(Ie(0!==n,"Cannot step a Range by 0"),e=e||0,void 0===t&&(t=1/0),n=void 0===n?1:Math.abs(n),ts?m():f(t,e,r[e])})},ve.prototype[z]=!0,e(be,g),be.prototype.__iterateUncached=function(e,t){if(t)return this.cacheResult().__iterate(e,t);var n,r=le(this._iterable),o=0;if(ae(r))for(;!(n=r.next()).done&&!1!==e(n.value,o++,this););return o},be.prototype.__iteratorUncached=function(t,e){if(e)return this.cacheResult().__iterator(t,e);var n=le(this._iterable);if(!ae(n))return new d(m);var r=0;return new d(function(){var e=n.next();return e.done?e:f(t,r++,e.value)})},e(we,g),we.prototype.__iterateUncached=function(e,t){if(t)return this.cacheResult().__iterate(e,t);for(var n=this._iterator,r=this._iteratorCache,o=0;o=r.length){var e=n.next();if(e.done)return e;r[o]=e.value}return f(t,o,r[o++])})},e(s,g),s.prototype.toString=function(){return 0===this.size?"Repeat []":"Repeat [ "+this._value+" "+this.size+" times ]"},s.prototype.get=function(e,t){return this.has(e)?this._value:t},s.prototype.includes=function(e){return v(this._value,e)},s.prototype.slice=function(e,t){var n=this.size;return X(e,t,n)?this:new s(this._value,Z(t,n)-Q(e,n))},s.prototype.reverse=function(){return this},s.prototype.indexOf=function(e){return v(this._value,e)?0:-1},s.prototype.lastIndexOf=function(e){return v(this._value,e)?this.size:-1},s.prototype.__iterate=function(e,t){for(var n=0;n>>16)*r+n*(t>>>16)<<16>>>0)|0};function Be(e){return e>>>1&1073741824|3221225471&e}function _(e){if(!1===e||null==e)return 0;if("function"==typeof e.valueOf&&(!1===(e=e.valueOf())||null==e))return 0;if(!0===e)return 1;var t,n,r=typeof e;if("number"==r){if(e!=e||e===1/0)return 0;var o=0|e;for(o!==e&&(o^=4294967295*e);4294967295We?(void 0===(t=Ge[s=e])&&(t=Le(s),He===Je&&(He=0,Ge={}),He++,Ge[s]=t),t):Le(e);if("function"==typeof e.hashCode)return e.hashCode();if("object"==r){var s=e;if(Ue&&void 0!==(n=ze.get(s)))return n;if(void 0!==(n=s[Ke]))return n;if(!$e){if(void 0!==(n=s.propertyIsEnumerable&&s.propertyIsEnumerable[Ke]))return n;if(void 0!==(n=function(e){if(e&&0=n.length)throw new Error("Missing value for key: "+n[t]);e.set(n[t],n[t+1])}})},k.prototype.toString=function(){return this.__toString("Map {","}")},k.prototype.get=function(e,t){return this._root?this._root.get(0,void 0,e,t):t},k.prototype.set=function(e,t){return ct(this,e,t)},k.prototype.setIn=function(e,t){return this.updateIn(e,x,function(){return t})},k.prototype.remove=function(e){return ct(this,e,x)},k.prototype.deleteIn=function(e){return this.updateIn(e,function(){return x})},k.prototype.update=function(e,t,n){return 1===arguments.length?e(this):this.updateIn([e],t,n)},k.prototype.updateIn=function(e,t,n){n||(n=t,t=void 0);e=function e(t,n,r,o){var s=t===x,i=n.next();if(i.done)return(l=o(a=s?r:t))===a?t:l;Ie(s||t&&t.set,"invalid keyPath");var a=i.value,l=s?x:t.get(a,x),i=e(l,n,r,o);return i===l?t:i===x?t.remove(a):(s?lt():t).set(a,i)}(this,cn(e),t,n);return e===x?void 0:e},k.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):lt()},k.prototype.merge=function(){return dt(this,void 0,arguments)},k.prototype.mergeWith=function(e){return dt(this,e,r.call(arguments,1))},k.prototype.mergeIn=function(e){var t=r.call(arguments,1);return this.updateIn(e,lt(),function(e){return"function"==typeof e.merge?e.merge.apply(e,t):t[t.length-1]})},k.prototype.mergeDeep=function(){return dt(this,ft,arguments)},k.prototype.mergeDeepWith=function(e){return dt(this,mt(e),r.call(arguments,1))},k.prototype.mergeDeepIn=function(e){var t=r.call(arguments,1);return this.updateIn(e,lt(),function(e){return"function"==typeof e.mergeDeep?e.mergeDeep.apply(e,t):t[t.length-1]})},k.prototype.sort=function(e){return j(Qt(this,e))},k.prototype.sortBy=function(e,t){return j(Qt(this,t,e))},k.prototype.withMutations=function(e){var t=this.asMutable();return e(t),t.wasAltered()?t.__ensureOwner(this.__ownerID):this},k.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new W)},k.prototype.asImmutable=function(){return this.__ensureOwner()},k.prototype.wasAltered=function(){return this.__altered},k.prototype.__iterator=function(e,t){return new ot(this,e,t)},k.prototype.__iterate=function(t,e){var n=this,r=0;return this._root&&this._root.iterate(function(e){return r++,t(e[1],e[0],n)},e),r},k.prototype.__ensureOwner=function(e){return e===this.__ownerID?this:e?at(this.size,this._root,e,this.__hash):(this.__ownerID=e,this.__altered=!1,this)},k.isMap=Ye;var Xe,Qe="@@__IMMUTABLE_MAP__@@",A=k.prototype;function Ze(e,t){this.ownerID=e,this.entries=t}function et(e,t,n){this.ownerID=e,this.bitmap=t,this.nodes=n}function tt(e,t,n){this.ownerID=e,this.count=t,this.nodes=n}function nt(e,t,n){this.ownerID=e,this.keyHash=t,this.entries=n}function rt(e,t,n){this.ownerID=e,this.keyHash=t,this.entry=n}function ot(e,t,n){this._type=t,this._reverse=n,this._stack=e._root&&it(e._root)}function st(e,t){return f(e,t[0],t[1])}function it(e,t){return{node:e,index:0,__prev:t}}function at(e,t,n,r){var o=Object.create(A);return o.size=e,o._root=t,o.__ownerID=n,o.__hash=r,o.__altered=!1,o}function lt(){return Xe=Xe||at(0)}function ct(e,t,n){if(e._root){var r=K(U),o=K(V),s=ut(e._root,e.__ownerID,0,void 0,t,n,r,o);if(!o.value)return e;o=e.size+(r.value?n===x?-1:1:0)}else{if(n===x)return e;o=1,s=new Ze(e.__ownerID,[[t,n]])}return e.__ownerID?(e.size=o,e._root=s,e.__hash=void 0,e.__altered=!0,e):s?at(o,s):lt()}function ut(e,t,n,r,o,s,i,a){return e?e.update(t,n,r,o,s,i,a):s===x?e:(y(a),y(i),new rt(t,r,[o,s]))}function pt(e){return e.constructor===rt||e.constructor===nt}function ht(e,t,n,r,o){if(e.keyHash===r)return new nt(t,r,[e.entry,o]);var s=(0===n?e.keyHash:e.keyHash>>>n)&S,i=(0===n?r:r>>>n)&S;return new et(t,1<>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,127&(e+=e>>8)+(e>>16)}function vt(e,t,n,r){r=r?e:J(e);return r[t]=n,r}A[Qe]=!0,A[t]=A.remove,A.removeIn=A.deleteIn,Ze.prototype.get=function(e,t,n,r){for(var o=this.entries,s=0,i=o.length;s=bt){for(var h=e,d=l,i=r,s=o,f=new rt(h=h||new W,_(i),[i,s]),m=0;m>>e)&S),s=this.bitmap;return 0==(s&o)?r:this.nodes[yt(s&o-1)].get(e+w,t,n,r)},et.prototype.update=function(e,t,n,r,o,s,i){void 0===n&&(n=_(r));var a=(0===t?n:n>>>t)&S,l=1<=wt){for(var n=e,f=h,m=c,r=a,o=t,g=0,y=new Array(E),v=0;0!==m;v++,m>>>=1)y[v]=1&m?f[g++]:void 0;return y[r]=o,new tt(n,g+1,y)}if(u&&!t&&2===h.length&&pt(h[1^p]))return h[1^p];if(u&&t&&1===h.length&&pt(t))return t;s=e&&e===this.ownerID,i=u?t?c:c^l:c|l,d=u?t?vt(h,p,t,s):function(e,t,n){var r=e.length-1;if(n&&t===r)return e.pop(),e;for(var o=new Array(r),s=0,i=0;i>>e)&S];return o?o.get(e+w,t,n,r):r},tt.prototype.update=function(e,t,n,r,o,s,i){void 0===n&&(n=_(r));var a=(0===t?n:n>>>t)&S,l=o===x,c=this.nodes,u=c[a];if(l&&!u)return this;l=ut(u,e,t+w,n,r,o,s,i);if(l===u)return this;t=this.count;if(u){if(!l&&--t=n.size||r<0)return n.withMutations(function(e){r<0?Rt(e,r).set(0,o):Rt(e,0,r+1).set(r,o)});r+=n._origin;var e=n._tail,t=n._root,s=K(V);return r>=Dt(n._capacity)?e=Nt(e,n.__ownerID,0,r,o,s):t=Nt(t,n.__ownerID,n._level,r,o,s),s.value?n.__ownerID?(n._root=t,n._tail=e,n.__hash=void 0,n.__altered=!0,n):jt(n._origin,n._capacity,n._level,t,e):n},O.prototype.remove=function(e){return this.has(e)?0===e?this.shift():e===this.size-1?this.pop():this.splice(e,1):this},O.prototype.insert=function(e,t){return this.splice(e,0,t)},O.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=this._origin=this._capacity=0,this._level=w,this._root=this._tail=null,this.__hash=void 0,this.__altered=!0,this):Pt()},O.prototype.push=function(){var n=arguments,r=this.size;return this.withMutations(function(e){Rt(e,0,r+n.length);for(var t=0;t>>t&S;if(r>=this.array.length)return new _t([],e);var o,s=0==r;if(0>>t&S;if(o>=this.array.length)return this;if(0>r,E<(l=1+(g-o>>r))&&(l=E),function(){for(;;){if(s){var e=s();if(e!==Ot)return e;s=null}if(a===l)return Ot;e=f?--l:a++;s=b(i&&i[e],r-w,o+(e<>>n&S,c=e&&l=Dt(e._capacity))return e._tail;if(t<1<>>r&S],r-=w;return n}}function Rt(e,t,n){void 0!==t&&(t|=0),void 0!==n&&(n|=0);var r=e.__ownerID||new W,o=e._origin,s=e._capacity,i=o+t,t=void 0===n?s:n<0?s+n:o+n;if(i===o&&t===s)return e;if(t<=i)return e.clear();for(var a=e._level,l=e._root,c=0;i+c<0;)l=new _t(l&&l.array.length?[void 0,l]:[],r),c+=1<<(a+=w);c&&(i+=c,o+=c,t+=c,s+=c);for(var u=Dt(s),p=Dt(t);1<>>f&S,d=d.array[m]=It(d.array[m],r);d.array[u>>>w&S]=n}if(t>>a&S;if(g!=p>>>a&S)break;g&&(c+=(1<o&&(o=a.size),u(i)||(a=a.map(function(e){return Ce(e)})),r.push(a)}return gt(e=o>e.size?e.setSize(o):e,t,r)}function Dt(e){return e>>w<=E&&i.size>=2*s.size?(r=(o=i.filter(function(e,t){return void 0!==e&&a!==t})).toKeyedSeq().map(function(e){return e[0]}).flip().toMap(),e.__ownerID&&(r.__ownerID=o.__ownerID=e.__ownerID)):(r=s.remove(t),o=a===i.size-1?i.pop():i.set(a,void 0))}else if(l){if(n===i.get(a)[1])return e;r=s,o=i.set(a,[t,n])}else r=s.set(t,i.size),o=i.set(i.size,[t,n]);return e.__ownerID?(e.size=r.size,e._map=r,e._list=o,e.__hash=void 0,e):Bt(r,o)}function $t(e,t){this._iter=e,this._useKeys=t,this.size=e.size}function zt(e){this._iter=e,this.size=e.size}function Ut(e){this._iter=e,this.size=e.size}function Vt(e){this._iter=e,this.size=e.size}function Kt(o){var e=sn(o);return e._iter=o,e.size=o.size,e.flip=function(){return o},e.reverse=function(){var e=o.reverse.apply(this);return e.flip=function(){return o.reverse()},e},e.has=function(e){return o.includes(e)},e.includes=function(e){return o.has(e)},e.cacheResult=an,e.__iterateUncached=function(n,e){var r=this;return o.__iterate(function(e,t){return!1!==n(t,e,r)},e)},e.__iteratorUncached=function(e,t){var n;return e===ne?(n=o.__iterator(e,t),new d(function(){var e,t=n.next();return t.done||(e=t.value[0],t.value[0]=t.value[1],t.value[1]=e),t})):o.__iterator(e===h?te:h,t)},e}function Wt(s,i,a){var e=sn(s);return e.size=s.size,e.has=function(e){return s.has(e)},e.get=function(e,t){var n=s.get(e,x);return n===x?t:i.call(a,n,e,s)},e.__iterateUncached=function(r,e){var o=this;return s.__iterate(function(e,t,n){return!1!==r(i.call(a,e,t,n),t,o)},e)},e.__iteratorUncached=function(r,e){var o=s.__iterator(ne,e);return new d(function(){var e=o.next();if(e.done)return e;var t=e.value,n=t[0];return f(r,n,i.call(a,t[1],n,s),e)})},e}function Jt(o,n){var e=sn(o);return e._iter=o,e.size=o.size,e.reverse=function(){return o},o.flip&&(e.flip=function(){var e=Kt(o);return e.reverse=function(){return o.flip()},e}),e.get=function(e,t){return o.get(n?e:-1-e,t)},e.has=function(e){return o.has(n?e:-1-e)},e.includes=function(e){return o.includes(e)},e.cacheResult=an,e.__iterate=function(n,e){var r=this;return o.__iterate(function(e,t){return n(e,t,r)},!e)},e.__iterator=function(e,t){return o.__iterator(e,!t)},e}function Ht(i,a,l,c){var e=sn(i);return c&&(e.has=function(e){var t=i.get(e,x);return t!==x&&!!a.call(l,t,e,i)},e.get=function(e,t){var n=i.get(e,x);return n!==x&&a.call(l,n,e,i)?n:t}),e.__iterateUncached=function(r,e){var o=this,s=0;return i.__iterate(function(e,t,n){if(a.call(l,e,t,n))return s++,r(e,c?t:s-1,o)},e),s},e.__iteratorUncached=function(r,e){var o=i.__iterator(ne,e),s=0;return new d(function(){for(;;){var e=o.next();if(e.done)return e;var t=e.value,n=t[0],t=t[1];if(a.call(l,t,n,i))return f(r,c?n:s++,t,e)}})},e}function Gt(a,e,t,l){var n=a.size;if(void 0!==e&&(e|=0),void 0!==t&&(t===1/0?t=n:t|=0),X(e,t,n))return a;var c=Q(e,n),n=Z(t,n);if(c!=c||n!=n)return Gt(a.toSeq().cacheResult(),e,t,l);var u,e=n-c,t=(e==e&&(u=e<0?0:e),sn(a));return t.size=0===u?u:a.size&&u||void 0,!l&&Ee(a)&&0<=u&&(t.get=function(e,t){return 0<=(e=G(this,e))&&eu)return m();var e=n.next();return l||t===h?e:f(t,o-1,t===te?void 0:e.value[1],e)})},t}function Yt(t,c,u,p){var e=sn(t);return e.__iterateUncached=function(r,e){var o=this;if(e)return this.cacheResult().__iterate(r,e);var s=!0,i=0;return t.__iterate(function(e,t,n){if(!s||!(s=c.call(u,e,t,n)))return i++,r(e,p?t:i-1,o)}),i},e.__iteratorUncached=function(o,e){var s=this;if(e)return this.cacheResult().__iterator(o,e);var i=t.__iterator(ne,e),a=!0,l=0;return new d(function(){var e;do{if((e=i.next()).done)return p||o===h?e:f(o,l++,o===te?void 0:e.value[1],e);var t=e.value,n=t[0],r=t[1]}while(a=a&&c.call(u,r,n,s));return o===ne?e:f(o,n,r,e)})},e}function Xt(e,l,c){var t=sn(e);return t.__iterateUncached=function(s,t){var i=0,a=!1;return function n(e,r){var o=this;e.__iterate(function(e,t){return(!l||r>>-15,461845907),t=Fe(t<<13|t>>>-13,5),t=Fe((t=(t+3864292196|0)^e)^t>>>16,2246822507),t=Be((t=Fe(t^t>>>13,3266489909))^t>>>16)}(e.__iterate(n?t?function(e,t){r=31*r+Ln(_(e),_(t))|0}:function(e,t){r=r+Ln(_(e),_(t))|0}:t?function(e){r=31*r+_(e)|0}:function(e){r=r+_(e)|0}),r)}(this))}});var t=l.prototype,Nn=(t[L]=!0,t[se]=t.values,t.__toJS=t.toArray,t.__toStringMapper=Dn,t.inspect=t.toSource=function(){return this.toString()},t.chain=t.flatMap,t.contains=t.includes,Pn(a,{flip:function(){return P(this,Kt(this))},mapEntries:function(n,r){var o=this,s=0;return P(this,this.toSeq().map(function(e,t){return n.call(r,[t,e],s++,o)}).fromEntrySeq())},mapKeys:function(n,r){var o=this;return P(this,this.toSeq().flip().map(function(e,t){return n.call(r,e,t,o)}).flip())}}),a.prototype);function In(e,t){return t}function Tn(e,t){return[t,e]}function Rn(e){return function(){return!e.apply(this,arguments)}}function Mn(e){return function(){return-e.apply(this,arguments)}}function Dn(e){return"string"==typeof e?JSON.stringify(e):String(e)}function Fn(){return J(arguments)}function Bn(e,t){return e>2)|0}return Nn[q]=!0,Nn[se]=t.entries,Nn.__toJS=t.toObject,Nn.__toStringMapper=function(e,t){return JSON.stringify(t)+": "+Dn(e)},Pn(D,{toKeyedSeq:function(){return new $t(this,!1)},filter:function(e,t){return P(this,Ht(this,e,t,!1))},findIndex:function(e,t){e=this.findEntry(e,t);return e?e[0]:-1},indexOf:function(e){e=this.keyOf(e);return void 0===e?-1:e},lastIndexOf:function(e){e=this.lastKeyOf(e);return void 0===e?-1:e},reverse:function(){return P(this,Jt(this,!1))},slice:function(e,t){return P(this,Gt(this,e,t,!1))},splice:function(e,t){var n=arguments.length;if(t=Math.max(0|t,0),0===n||2===n&&!t)return this;e=Q(e,e<0?this.count():this.size);var r=this.slice(0,e);return P(this,1===n?r:r.concat(J(arguments,2),this.slice(e+t)))},findLastIndex:function(e,t){e=this.findLastEntry(e,t);return e?e[0]:-1},first:function(){return this.get(0)},flatten:function(e){return P(this,Xt(this,e,!1))},get:function(n,e){return(n=G(this,n))<0||this.size===1/0||void 0!==this.size&&n>this.size?e:this.find(function(e,t){return t===n},void 0,e)},has:function(e){return 0<=(e=G(this,e))&&(void 0!==this.size?this.size===1/0||e{"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){var n;t&&(e.super_=t,(n=function(){}).prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e)}},5419:e=>{e.exports=function(e,t,n,r){var o,s,r=new Blob(void 0!==r?[r,e]:[e],{type:n||"application/octet-stream"});void 0!==window.navigator.msSaveBlob?window.navigator.msSaveBlob(r,t):(o=(window.URL&&window.URL.createObjectURL?window.URL:window.webkitURL).createObjectURL(r),(s=document.createElement("a")).style.display="none",s.href=o,s.setAttribute("download",t),void 0===s.download&&s.setAttribute("target","_blank"),document.body.appendChild(s),s.click(),setTimeout(function(){document.body.removeChild(s),window.URL.revokeObjectURL(o)},200))}},20181:(e,t,n)=>{function v(){return c.Date.now()}var r=/^\s+|\s+$/g,o=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,i=/^0o[0-7]+$/i,a=parseInt,n="object"==typeof n.g&&n.g&&n.g.Object===Object&&n.g,l="object"==typeof self&&self&&self.Object===Object&&self,c=n||l||Function("return this")(),u=Object.prototype.toString,b=Math.max,w=Math.min;function E(e){var t=typeof e;return e&&("object"==t||"function"==t)}function S(e){if("number"==typeof e)return e;if("symbol"==typeof(n=e)||(t=n)&&"object"==typeof t&&"[object Symbol]"==u.call(n))return NaN;var t;if("string"!=typeof(e=E(e)?E(t="function"==typeof e.valueOf?e.valueOf():e)?t+"":t:e))return 0===e?e:+e;e=e.replace(r,"");var n=s.test(e);return n||i.test(e)?a(e.slice(2),n?2:8):o.test(e)?NaN:+e}e.exports=function(r,n,e){var o,s,i,a,l,c,u=0,p=!1,h=!1,t=!0;if("function"!=typeof r)throw new TypeError("Expected a function");function d(e){var t=o,n=s;return o=s=void 0,u=e,a=r.apply(n,t)}function f(e){var t=e-c;return void 0===c||n<=t||t<0||h&&i<=e-u}function m(){var e,t=v();if(f(t))return g(t);l=setTimeout(m,(e=n-((t=t)-c),h?w(e,i-(t-u)):e))}function g(e){return l=void 0,t&&o?d(e):(o=s=void 0,a)}function y(){var e=v(),t=f(e);if(o=arguments,s=this,c=e,t){if(void 0===l)return u=e=c,l=setTimeout(m,n),p?d(e):a;if(h)return l=setTimeout(m,n),d(c)}return void 0===l&&(l=setTimeout(m,n)),a}return n=S(n)||0,E(e)&&(p=!!e.leading,i=(h="maxWait"in e)?b(S(e.maxWait)||0,n):i,t="trailing"in e?!!e.trailing:t),y.cancel=function(){void 0!==l&&clearTimeout(l),o=c=s=l=void(u=0)},y.flush=function(){return void 0===l?a:g(v())},y}},55580:(e,t,n)=>{n=n(56110)(n(9325),"DataView");e.exports=n},21549:(e,t,n)=>{var r=n(22032),o=n(63862),s=n(66721),i=n(12749),n=n(35749);function a(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t{var r=n(39344),n=n(94033);function o(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=4294967295,this.__views__=[]}o.prototype=r(n.prototype),e.exports=o.prototype.constructor=o},80079:(e,t,n)=>{var r=n(63702),o=n(70080),s=n(24739),i=n(48655),n=n(31175);function a(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t{var r=n(39344),n=n(94033);function o(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=void 0}o.prototype=r(n.prototype),e.exports=o.prototype.constructor=o},68223:(e,t,n)=>{n=n(56110)(n(9325),"Map");e.exports=n},53661:(e,t,n)=>{var r=n(63040),o=n(17670),s=n(90289),i=n(4509),n=n(72949);function a(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t{n=n(56110)(n(9325),"Promise");e.exports=n},76545:(e,t,n)=>{n=n(56110)(n(9325),"Set");e.exports=n},38859:(e,t,n)=>{var r=n(53661),o=n(31380),n=n(51459);function s(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new r;++t{var r=n(80079),o=n(51420),s=n(90938),i=n(63605),a=n(29817),n=n(80945);function l(e){e=this.__data__=new r(e);this.size=e.size}l.prototype.clear=o,l.prototype.delete=s,l.prototype.get=i,l.prototype.has=a,l.prototype.set=n,e.exports=l},51873:(e,t,n)=>{n=n(9325).Symbol;e.exports=n},37828:(e,t,n)=>{n=n(9325).Uint8Array;e.exports=n},28303:(e,t,n)=>{n=n(56110)(n(9325),"WeakMap");e.exports=n},91033:e=>{e.exports=function(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}},83729:e=>{e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length;++n{e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length,o=0,s=[];++n{var r=n(96131);e.exports=function(e,t){return!(null==e||!e.length)&&-1{var u=n(78096),p=n(72428),h=n(56449),d=n(3656),f=n(30361),m=n(37167),g=Object.prototype.hasOwnProperty;e.exports=function(e,t){var n,r=h(e),o=!r&&p(e),s=!r&&!o&&d(e),i=!r&&!o&&!s&&m(e),a=r||o||s||i,l=a?u(e.length,String):[],c=l.length;for(n in e)!t&&!g.call(e,n)||a&&("length"==n||s&&("offset"==n||"parent"==n)||i&&("buffer"==n||"byteLength"==n||"byteOffset"==n)||f(n,c))||l.push(n);return l}},34932:e=>{e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length,o=Array(r);++n{e.exports=function(e,t){for(var n=-1,r=t.length,o=e.length;++n{e.exports=function(e,t,n,r){var o=-1,s=null==e?0:e.length;for(r&&s&&(n=e[++o]);++o{e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length;++n{e.exports=function(e){return e.split("")}},1733:e=>{var t=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;e.exports=function(e){return e.match(t)||[]}},87805:(e,t,n)=>{var r=n(43360),o=n(75288);e.exports=function(e,t,n){(void 0===n||o(e[t],n))&&(void 0!==n||t in e)||r(e,t,n)}},16547:(e,t,n)=>{var o=n(43360),s=n(75288),i=Object.prototype.hasOwnProperty;e.exports=function(e,t,n){var r=e[t];i.call(e,t)&&s(r,n)&&(void 0!==n||t in e)||o(e,t,n)}},26025:(e,t,n)=>{var r=n(75288);e.exports=function(e,t){for(var n=e.length;n--;)if(r(e[n][0],t))return n;return-1}},74733:(e,t,n)=>{var r=n(21791),o=n(95950);e.exports=function(e,t){return e&&r(t,o(t),e)}},43838:(e,t,n)=>{var r=n(21791),o=n(37241);e.exports=function(e,t){return e&&r(t,o(t),e)}},43360:(e,t,n)=>{var r=n(93243);e.exports=function(e,t,n){"__proto__"==t&&r?r(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n}},9999:(e,t,n)=>{var f=n(37217),m=n(83729),g=n(16547),y=n(74733),v=n(43838),b=n(93290),w=n(23007),E=n(92271),S=n(48948),x=n(50002),_=n(83349),k=n(5861),A=n(76189),O=n(77199),C=n(35529),j=n(56449),P=n(3656),N=n(87730),I=n(23805),T=n(38440),R=n(95950),M=n(37241),D="[object Arguments]",F="[object Function]",B="[object Object]",L={};L[D]=L["[object Array]"]=L["[object ArrayBuffer]"]=L["[object DataView]"]=L["[object Boolean]"]=L["[object Date]"]=L["[object Float32Array]"]=L["[object Float64Array]"]=L["[object Int8Array]"]=L["[object Int16Array]"]=L["[object Int32Array]"]=L["[object Map]"]=L["[object Number]"]=L[B]=L["[object RegExp]"]=L["[object Set]"]=L["[object String]"]=L["[object Symbol]"]=L["[object Uint8Array]"]=L["[object Uint8ClampedArray]"]=L["[object Uint16Array]"]=L["[object Uint32Array]"]=!0,L["[object Error]"]=L[F]=L["[object WeakMap]"]=!1,e.exports=function n(r,o,s,e,t,i){var a,l=1&o,c=2&o,u=4&o;if(void 0!==(a=s?t?s(r,e,t,i):s(r):a))return a;if(!I(r))return r;e=j(r);if(e){if(a=A(r),!l)return w(r,a)}else{var p=k(r),h=p==F||"[object GeneratorFunction]"==p;if(P(r))return b(r,l);if(p==B||p==D||h&&!t){if(a=c||h?{}:C(r),!l)return c?S(r,v(a,r)):E(r,y(a,r))}else{if(!L[p])return t?r:{};a=O(r,p,l)}}h=(i=i||new f).get(r);if(h)return h;i.set(r,a),T(r)?r.forEach(function(e){a.add(n(e,o,s,e,r,i))}):N(r)&&r.forEach(function(e,t){a.set(t,n(e,o,s,t,r,i))});var d=e?void 0:(u?c?_:x:c?M:R)(r);return m(d||r,function(e,t){d&&(e=r[t=e]),g(a,t,n(e,o,s,t,r,i))}),a}},39344:(e,t,n)=>{var r=n(23805),o=Object.create;function s(){}e.exports=function(e){if(!r(e))return{};if(o)return o(e);s.prototype=e;e=new s;return s.prototype=void 0,e}},80909:(e,t,n)=>{var r=n(30641),n=n(38329)(r);e.exports=n},2523:e=>{e.exports=function(e,t,n,r){for(var o=e.length,s=n+(r?1:-1);r?s--:++s{var c=n(14528),u=n(45891);e.exports=function e(t,n,r,o,s){var i=-1,a=t.length;for(r=r||u,s=s||[];++i{n=n(83221)();e.exports=n},30641:(e,t,n)=>{var r=n(86649),o=n(95950);e.exports=function(e,t){return e&&r(e,t,o)}},47422:(e,t,n)=>{var o=n(31769),s=n(77797);e.exports=function(e,t){for(var n=0,r=(t=o(t,e)).length;null!=e&&n{var r=n(14528),o=n(56449);e.exports=function(e,t,n){t=t(e);return o(e)?t:r(t,n(e))}},72552:(e,t,n)=>{var r=n(51873),o=n(659),s=n(59350),i=r?r.toStringTag:void 0;e.exports=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":(i&&i in Object(e)?o:s)(e)}},28077:e=>{e.exports=function(e,t){return null!=e&&t in Object(e)}},96131:(e,t,n)=>{var r=n(2523),o=n(85463),s=n(76959);e.exports=function(e,t,n){return t==t?s(e,t,n):r(e,o,n)}},27534:(e,t,n)=>{var r=n(72552),o=n(40346);e.exports=function(e){return o(e)&&"[object Arguments]"==r(e)}},60270:(e,t,n)=>{var i=n(87068),a=n(40346);e.exports=function e(t,n,r,o,s){return t===n||(null==t||null==n||!a(t)&&!a(n)?t!=t&&n!=n:i(t,n,r,o,e,s))}},87068:(e,t,n)=>{var p=n(37217),h=n(25911),d=n(21986),f=n(50689),m=n(5861),g=n(56449),y=n(3656),v=n(37167),b="[object Arguments]",w="[object Array]",E="[object Object]",S=Object.prototype.hasOwnProperty;e.exports=function(e,t,n,r,o,s){var i=g(e),a=g(t),l=i?w:m(e),a=a?w:m(t),c=(l=l==b?E:l)==E,u=(a=a==b?E:a)==E,a=l==a;if(a&&y(e)){if(!y(t))return!1;c=!(i=!0)}if(a&&!c)return s=s||new p,i||v(e)?h(e,t,n,r,o,s):d(e,t,l,n,r,o,s);if(!(1&n)){i=c&&S.call(e,"__wrapped__"),l=u&&S.call(t,"__wrapped__");if(i||l)return o(i?e.value():e,l?t.value():t,n,r,s=s||new p)}return!!a&&(s=s||new p,f(e,t,n,r,o,s))}},29172:(e,t,n)=>{var r=n(5861),o=n(40346);e.exports=function(e){return o(e)&&"[object Map]"==r(e)}},41799:(e,t,n)=>{var d=n(37217),f=n(60270);e.exports=function(e,t,n,r){var o=n.length,s=o,i=!r;if(null==e)return!s;for(e=Object(e);o--;){var a=n[o];if(i&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return!1}for(;++o{e.exports=function(e){return e!=e}},45083:(e,t,n)=>{var r=n(1882),o=n(87296),s=n(23805),i=n(47473),a=/^\[object .+?Constructor\]$/,n=Function.prototype,l=Object.prototype,n=n.toString,l=l.hasOwnProperty,c=RegExp("^"+n.call(l).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=function(e){return!(!s(e)||o(e))&&(r(e)?c:a).test(i(e))}},16038:(e,t,n)=>{var r=n(5861),o=n(40346);e.exports=function(e){return o(e)&&"[object Set]"==r(e)}},4901:(e,t,n)=>{var r=n(72552),o=n(30294),s=n(40346),i={};i["[object Float32Array]"]=i["[object Float64Array]"]=i["[object Int8Array]"]=i["[object Int16Array]"]=i["[object Int32Array]"]=i["[object Uint8Array]"]=i["[object Uint8ClampedArray]"]=i["[object Uint16Array]"]=i["[object Uint32Array]"]=!0,i["[object Arguments]"]=i["[object Array]"]=i["[object ArrayBuffer]"]=i["[object Boolean]"]=i["[object DataView]"]=i["[object Date]"]=i["[object Error]"]=i["[object Function]"]=i["[object Map]"]=i["[object Number]"]=i["[object Object]"]=i["[object RegExp]"]=i["[object Set]"]=i["[object String]"]=i["[object WeakMap]"]=!1,e.exports=function(e){return s(e)&&o(e.length)&&!!i[r(e)]}},15389:(e,t,n)=>{var r=n(93663),o=n(87978),s=n(83488),i=n(56449),a=n(50583);e.exports=function(e){return"function"==typeof e?e:null==e?s:"object"==typeof e?i(e)?o(e[0],e[1]):r(e):a(e)}},88984:(e,t,n)=>{var r=n(55527),o=n(3650),s=Object.prototype.hasOwnProperty;e.exports=function(e){if(!r(e))return o(e);var t,n=[];for(t in Object(e))s.call(e,t)&&"constructor"!=t&&n.push(t);return n}},72903:(e,t,n)=>{var o=n(23805),s=n(55527),i=n(90181),a=Object.prototype.hasOwnProperty;e.exports=function(e){if(!o(e))return i(e);var t,n=s(e),r=[];for(t in e)("constructor"!=t||!n&&a.call(e,t))&&r.push(t);return r}},94033:e=>{e.exports=function(){}},93663:(e,t,n)=>{var r=n(41799),o=n(10776),s=n(67197);e.exports=function(t){var n=o(t);return 1==n.length&&n[0][2]?s(n[0][0],n[0][1]):function(e){return e===t||r(e,t,n)}}},87978:(e,t,n)=>{var o=n(60270),s=n(58156),i=n(80631),a=n(28586),l=n(30756),c=n(67197),u=n(77797);e.exports=function(n,r){return a(n)&&l(r)?c(u(n),r):function(e){var t=s(e,n);return void 0===t&&t===r?i(e,n):o(r,t,3)}}},85250:(e,t,n)=>{var c=n(37217),u=n(87805),p=n(86649),h=n(42824),d=n(23805),f=n(37241),m=n(14974);e.exports=function r(o,s,i,a,l){o!==s&&p(s,function(e,t){var n;l=l||new c,d(e)?h(o,s,t,i,r,a,l):(n=a?a(m(o,t),e,t+"",o,s,l):void 0,u(o,t,n=void 0===n?e:n))},f)}},42824:(e,t,n)=>{var d=n(87805),f=n(93290),m=n(71961),g=n(23007),y=n(35529),v=n(72428),b=n(56449),w=n(83693),E=n(3656),S=n(1882),x=n(23805),_=n(11331),k=n(37167),A=n(14974),O=n(69884);e.exports=function(e,t,n,r,o,s,i){var a,l,c,u=A(e,n),p=A(t,n),h=i.get(p);h?d(e,n,h):((t=void 0===(h=s?s(u,p,n+"",e,t,i):void 0))&&(l=!(a=b(p))&&E(p),c=!a&&!l&&k(p),h=p,a||l||c?h=b(u)?u:w(u)?g(u):l?f(p,!(t=!1)):c?m(p,!(t=!1)):[]:_(p)||v(p)?v(h=u)?h=O(u):x(u)&&!S(u)||(h=y(p)):t=!1),t&&(i.set(p,h),o(h,p,r,s,i),i.delete(p)),d(e,n,h))}},47237:e=>{e.exports=function(t){return function(e){return null==e?void 0:e[t]}}},17255:(e,t,n)=>{var r=n(47422);e.exports=function(t){return function(e){return r(e,t)}}},54552:e=>{e.exports=function(t){return function(e){return null==t?void 0:t[e]}}},85558:e=>{e.exports=function(e,r,o,s,t){return t(e,function(e,t,n){o=s?(s=!1,e):r(o,e,t,n)}),o}},69302:(e,t,n)=>{var r=n(83488),o=n(56757),s=n(32865);e.exports=function(e,t){return s(o(e,t,r),e+"")}},73170:(e,t,n)=>{var p=n(16547),h=n(31769),d=n(30361),f=n(23805),m=n(77797);e.exports=function(e,t,n,r){if(!f(e))return e;for(var o=-1,s=(t=h(t,e)).length,i=s-1,a=e;null!=a&&++o{var r=n(83488),o=n(48152);e.exports=o?function(e,t){return o.set(e,t),e}:r},19570:(e,t,n)=>{var r=n(37334),o=n(93243),n=n(83488);e.exports=o?function(e,t){return o(e,"toString",{configurable:!0,enumerable:!1,value:r(t),writable:!0})}:n},25160:e=>{e.exports=function(e,t,n){var r=-1,o=e.length;(n=o>>0,t>>>=0;for(var s=Array(o);++r{var s=n(80909);e.exports=function(e,r){var o;return s(e,function(e,t,n){return!(o=r(e,t,n))}),!!o}},78096:e=>{e.exports=function(e,t){for(var n=-1,r=Array(e);++n{var r=n(51873),o=n(34932),s=n(56449),i=n(44394),n=r?r.prototype:void 0,a=n?n.toString:void 0;e.exports=function e(t){if("string"==typeof t)return t;if(s(t))return o(t,e)+"";if(i(t))return a?a.call(t):"";var n=t+"";return"0"==n&&1/t==-1/0?"-0":n}},54128:(e,t,n)=>{var r=n(31800),o=/^\s+/;e.exports=function(e){return e&&e.slice(0,r(e)+1).replace(o,"")}},27301:e=>{e.exports=function(t){return function(e){return t(e)}}},19931:(e,t,n)=>{var r=n(31769),o=n(68090),s=n(68969),i=n(77797);e.exports=function(e,t){return t=r(t,e),null==(e=s(e,t))||delete e[i(o(t))]}},51234:e=>{e.exports=function(e,t,n){for(var r=-1,o=e.length,s=t.length,i={};++r{e.exports=function(e,t){return e.has(t)}},31769:(e,t,n)=>{var r=n(56449),o=n(28586),s=n(61802),i=n(13222);e.exports=function(e,t){return r(e)?e:o(e,t)?[e]:s(i(e))}},28754:(e,t,n)=>{var o=n(25160);e.exports=function(e,t,n){var r=e.length;return n=void 0===n?r:n,!t&&r<=n?e:o(e,t,n)}},49653:(e,t,n)=>{var r=n(37828);e.exports=function(e){var t=new e.constructor(e.byteLength);return new r(t).set(new r(e)),t}},93290:(e,t,n)=>{e=n.nmd(e);var n=n(9325),t=t&&!t.nodeType&&t,r=t&&e&&!e.nodeType&&e,r=r&&r.exports===t?n.Buffer:void 0,o=r?r.allocUnsafe:void 0;e.exports=function(e,t){if(t)return e.slice();t=e.length,t=o?o(t):new e.constructor(t);return e.copy(t),t}},76169:(e,t,n)=>{var r=n(49653);e.exports=function(e,t){t=t?r(e.buffer):e.buffer;return new e.constructor(t,e.byteOffset,e.byteLength)}},73201:e=>{var n=/\w*$/;e.exports=function(e){var t=new e.constructor(e.source,n.exec(e));return t.lastIndex=e.lastIndex,t}},93736:(e,t,n)=>{var n=n(51873),n=n?n.prototype:void 0,r=n?n.valueOf:void 0;e.exports=function(e){return r?Object(r.call(e)):{}}},71961:(e,t,n)=>{var r=n(49653);e.exports=function(e,t){t=t?r(e.buffer):e.buffer;return new e.constructor(t,e.byteOffset,e.length)}},91596:e=>{var h=Math.max;e.exports=function(e,t,n,r){for(var o=-1,s=e.length,i=n.length,a=-1,l=t.length,c=h(s-i,0),u=Array(l+c),p=!r;++a{var f=Math.max;e.exports=function(e,t,n,r){for(var o=-1,s=e.length,i=-1,a=n.length,l=-1,c=t.length,u=f(s-a,0),p=Array(u+c),h=!r;++o{e.exports=function(e,t){var n=-1,r=e.length;for(t=t||Array(r);++n{var c=n(16547),u=n(43360);e.exports=function(e,t,n,r){var o=!n;n=n||{};for(var s=-1,i=t.length;++s{var r=n(21791),o=n(4664);e.exports=function(e,t){return r(e,o(e),t)}},48948:(e,t,n)=>{var r=n(21791),o=n(86375);e.exports=function(e,t){return r(e,o(e),t)}},55481:(e,t,n)=>{n=n(9325)["__core-js_shared__"];e.exports=n},58523:e=>{e.exports=function(e,t){for(var n=e.length,r=0;n--;)e[n]===t&&++r;return r}},20999:(e,t,n)=>{var r=n(69302),l=n(36800);e.exports=function(a){return r(function(e,t){var n=-1,r=t.length,o=1{var a=n(64894);e.exports=function(s,i){return function(e,t){if(null==e)return e;if(!a(e))return s(e,t);for(var n=e.length,r=i?n:-1,o=Object(e);(i?r--:++r{e.exports=function(l){return function(e,t,n){for(var r=-1,o=Object(e),s=n(e),i=s.length;i--;){var a=s[l?i:++r];if(!1===t(o[a],a,o))break}return e}}},11842:(e,t,n)=>{var s=n(82819),i=n(9325);e.exports=function(t,e,n){var r=1&e,o=s(t);return function e(){return(this&&this!==i&&this instanceof e?o:t).apply(r?n:this,arguments)}}},12507:(e,t,n)=>{var o=n(28754),s=n(49698),i=n(63912),a=n(13222);e.exports=function(r){return function(e){e=a(e);var t=s(e)?i(e):void 0,n=t?t[0]:e.charAt(0),t=t?o(t,1).join(""):e.slice(1);return n[r]()+t}}},45539:(e,t,n)=>{var r=n(40882),o=n(50828),s=n(66645),i=RegExp("['’]","g");e.exports=function(t){return function(e){return r(s(o(e).replace(i,"")),t,"")}}},82819:(e,t,n)=>{var o=n(39344),s=n(23805);e.exports=function(r){return function(){var e=arguments;switch(e.length){case 0:return new r;case 1:return new r(e[0]);case 2:return new r(e[0],e[1]);case 3:return new r(e[0],e[1],e[2]);case 4:return new r(e[0],e[1],e[2],e[3]);case 5:return new r(e[0],e[1],e[2],e[3],e[4]);case 6:return new r(e[0],e[1],e[2],e[3],e[4],e[5]);case 7:return new r(e[0],e[1],e[2],e[3],e[4],e[5],e[6])}var t=o(r.prototype),n=r.apply(t,e);return s(n)?n:t}}},77078:(e,t,n)=>{var c=n(91033),r=n(82819),u=n(37471),p=n(18073),h=n(11287),d=n(36306),f=n(9325);e.exports=function(s,i,a){var l=r(s);return function e(){for(var t=arguments.length,n=Array(t),r=t,o=h(e);r--;)n[r]=arguments[r];o=t<3&&n[0]!==o&&n[t-1]!==o?[]:d(n,o);return(t-=o.length){var i=n(15389),a=n(64894),l=n(95950);e.exports=function(s){return function(e,t,n){var r,o=Object(e),t=(a(e)||(r=i(t,3),e=l(e),t=function(e){return r(o[e],e,o)}),s(e,t,n));return-1{var x=n(91596),_=n(53320),k=n(58523),A=n(82819),O=n(18073),C=n(11287),j=n(68294),P=n(36306),N=n(9325);e.exports=function i(a,l,c,u,p,h,d,f,m,g){var y=128&l,v=1&l,b=2&l,w=24&l,E=512&l,S=b?void 0:A(a);return function e(){for(var t=arguments.length,n=Array(t),r=t;r--;)n[r]=arguments[r];if(w&&(o=C(e),s=k(n,o)),u&&(n=x(n,u,p,w)),h&&(n=_(n,h,d,w)),t-=s,w&&t{var h=n(91033),r=n(82819),d=n(9325);e.exports=function(a,e,l,c){var u=1&e,p=r(a);return function e(){for(var t=-1,n=arguments.length,r=-1,o=c.length,s=Array(o+n),i=this&&this!==d&&this instanceof e?p:a;++r{var p=n(85087),h=n(54641),d=n(70981);e.exports=function(e,t,n,r,o,s,i,a,l,c){var u=8&t,o=(4&(t=(t|(u?32:64))&~(u?64:32))||(t&=-4),[e,t,o,u?s:void 0,u?i:void 0,u?void 0:s,u?void 0:i,a,l,c]),s=n.apply(void 0,o);return p(e)&&h(s,o),s.placeholder=r,d(s,e,t)}},66977:(e,t,n)=>{var d=n(68882),f=n(11842),m=n(77078),g=n(37471),y=n(24168),v=n(37381),b=n(3209),w=n(54641),E=n(70981),S=n(61489),x=Math.max;e.exports=function(e,t,n,r,o,s,i,a){var l=2&t;if(!l&&"function"!=typeof e)throw new TypeError("Expected a function");var c,u=r?r.length:0,p=(u||(t&=-97,r=o=void 0),i=void 0===i?i:x(S(i),0),a=void 0===a?a:S(a),u-=o?o.length:0,64&t&&(h=r,c=o,r=o=void 0),l?void 0:v(e)),h=[e,t,n,r,o,h,c,s,i,a];return p&&b(h,p),e=h[0],t=h[1],n=h[2],r=h[3],o=h[4],!(a=h[9]=void 0===h[9]?l?0:e.length:x(h[9]-u,0))&&24&t&&(t&=-25),c=t&&1!=t?8==t||16==t?m(e,t,a):32!=t&&33!=t||o.length?g.apply(void 0,h):y(e,t,n,r):f(e,t,n),E((p?d:w)(c,h),e,t)}},53138:(e,t,n)=>{var r=n(11331);e.exports=function(e){return r(e)?void 0:e}},24647:(e,t,n)=>{n=n(54552)({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"});e.exports=n},93243:(e,t,n)=>{var r=n(56110),n=function(){try{var e=r(Object,"defineProperty");return e({},"",{}),e}catch(e){}}();e.exports=n},25911:(e,t,n)=>{var g=n(38859),y=n(14248),v=n(19219);e.exports=function(e,t,n,r,o,s){var i=1&n,a=e.length,l=t.length;if(a!=l&&!(i&&a{var r=n(51873),c=n(37828),u=n(75288),p=n(25911),h=n(20317),d=n(84247),n=r?r.prototype:void 0,f=n?n.valueOf:void 0;e.exports=function(e,t,n,r,o,s,i){switch(n){case"[object DataView]":if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case"[object ArrayBuffer]":return!(e.byteLength!=t.byteLength||!s(new c(e),new c(t)));case"[object Boolean]":case"[object Date]":case"[object Number]":return u(+e,+t);case"[object Error]":return e.name==t.name&&e.message==t.message;case"[object RegExp]":case"[object String]":return e==t+"";case"[object Map]":var a=h;case"[object Set]":a=a||d;if(e.size!=t.size&&!(1&r))return!1;var l=i.get(e);if(l)return l==t;r|=2,i.set(e,t);l=p(a(e),a(t),r,o,s,i);return i.delete(e),l;case"[object Symbol]":if(f)return f.call(e)==f.call(t)}return!1}},50689:(e,t,n)=>{var v=n(50002),b=Object.prototype.hasOwnProperty;e.exports=function(e,t,n,r,o,s){var i=1&n,a=v(e),l=a.length;if(l!=v(t).length&&!i)return!1;for(var c=l;c--;){var u=a[c];if(!(i?u in t:b.call(t,u)))return!1}var p=s.get(e),h=s.get(t);if(p&&h)return p==t&&h==e;var d=!0;s.set(e,t),s.set(t,e);for(var f=i;++c{var r=n(35970),o=n(56757),s=n(32865);e.exports=function(e){return s(o(e,void 0,r),e+"")}},34840:(e,t,n)=>{n="object"==typeof n.g&&n.g&&n.g.Object===Object&&n.g;e.exports=n},50002:(e,t,n)=>{var r=n(82199),o=n(4664),s=n(95950);e.exports=function(e){return r(e,s,o)}},83349:(e,t,n)=>{var r=n(82199),o=n(86375),s=n(37241);e.exports=function(e){return r(e,s,o)}},37381:(e,t,n)=>{var r=n(48152),n=n(63950);e.exports=r?function(e){return r.get(e)}:n},62284:(e,t,n)=>{var i=n(84629),a=Object.prototype.hasOwnProperty;e.exports=function(e){for(var t=e.name+"",n=i[t],r=a.call(i,t)?n.length:0;r--;){var o=n[r],s=o.func;if(null==s||s==e)return o.name}return t}},11287:e=>{e.exports=function(e){return e.placeholder}},12651:(e,t,n)=>{var r=n(74218);e.exports=function(e,t){e=e.__data__;return r(t)?e["string"==typeof t?"string":"hash"]:e.map}},10776:(e,t,n)=>{var s=n(30756),i=n(95950);e.exports=function(e){for(var t=i(e),n=t.length;n--;){var r=t[n],o=e[r];t[n]=[r,o,s(o)]}return t}},56110:(e,t,n)=>{var r=n(45083),o=n(10392);e.exports=function(e,t){e=o(e,t);return r(e)?e:void 0}},28879:(e,t,n)=>{n=n(74335)(Object.getPrototypeOf,Object);e.exports=n},659:(e,t,n)=>{var n=n(51873),r=Object.prototype,s=r.hasOwnProperty,i=r.toString,a=n?n.toStringTag:void 0;e.exports=function(e){var t=s.call(e,a),n=e[a];try{var r=!(e[a]=void 0)}catch(e){}var o=i.call(e);return r&&(t?e[a]=n:delete e[a]),o}},4664:(e,t,n)=>{var r=n(79770),n=n(63345),o=Object.prototype.propertyIsEnumerable,s=Object.getOwnPropertySymbols;e.exports=s?function(t){return null==t?[]:(t=Object(t),r(s(t),function(e){return o.call(t,e)}))}:n},86375:(e,t,n)=>{var r=n(14528),o=n(28879),s=n(4664),n=n(63345),n=Object.getOwnPropertySymbols?function(e){for(var t=[];e;)r(t,s(e)),e=o(e);return t}:n;e.exports=n},5861:(e,t,n)=>{var r=n(55580),o=n(68223),s=n(32804),i=n(76545),a=n(28303),l=n(72552),c=n(47473),u="[object Map]",p="[object Promise]",h="[object Set]",d="[object WeakMap]",f="[object DataView]",m=c(r),g=c(o),y=c(s),v=c(i),b=c(a),n=l;(r&&n(new r(new ArrayBuffer(1)))!=f||o&&n(new o)!=u||s&&n(s.resolve())!=p||i&&n(new i)!=h||a&&n(new a)!=d)&&(n=function(e){var t=l(e),e="[object Object]"==t?e.constructor:void 0,e=e?c(e):"";if(e)switch(e){case m:return f;case g:return u;case y:return p;case v:return h;case b:return d}return t}),e.exports=n},10392:e=>{e.exports=function(e,t){return null==e?void 0:e[t]}},75251:e=>{var t=/\{\n\/\* \[wrapped with (.+)\] \*/,n=/,? & /;e.exports=function(e){e=e.match(t);return e?e[1].split(n):[]}},49326:(e,t,n)=>{var a=n(31769),l=n(72428),c=n(56449),u=n(30361),p=n(30294),h=n(77797);e.exports=function(e,t,n){for(var r=-1,o=(t=a(t,e)).length,s=!1;++r{var t=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");e.exports=function(e){return t.test(e)}},45434:e=>{var t=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;e.exports=function(e){return t.test(e)}},22032:(e,t,n)=>{var r=n(81042);e.exports=function(){this.__data__=r?r(null):{},this.size=0}},63862:e=>{e.exports=function(e){e=this.has(e)&&delete this.__data__[e];return this.size-=e?1:0,e}},66721:(e,t,n)=>{var r=n(81042),o=Object.prototype.hasOwnProperty;e.exports=function(e){var t,n=this.__data__;return r?"__lodash_hash_undefined__"===(t=n[e])?void 0:t:o.call(n,e)?n[e]:void 0}},12749:(e,t,n)=>{var r=n(81042),o=Object.prototype.hasOwnProperty;e.exports=function(e){var t=this.__data__;return r?void 0!==t[e]:o.call(t,e)}},35749:(e,t,n)=>{var r=n(81042);e.exports=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=r&&void 0===t?"__lodash_hash_undefined__":t,this}},76189:e=>{var r=Object.prototype.hasOwnProperty;e.exports=function(e){var t=e.length,n=new e.constructor(t);return t&&"string"==typeof e[0]&&r.call(e,"index")&&(n.index=e.index,n.input=e.input),n}},77199:(e,t,n)=>{var o=n(49653),s=n(76169),i=n(73201),a=n(93736),l=n(71961);e.exports=function(e,t,n){var r=e.constructor;switch(t){case"[object ArrayBuffer]":return o(e);case"[object Boolean]":case"[object Date]":return new r(+e);case"[object DataView]":return s(e,n);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return l(e,n);case"[object Map]":case"[object Set]":return new r;case"[object Number]":case"[object String]":return new r(e);case"[object RegExp]":return i(e);case"[object Symbol]":return a(e)}}},35529:(e,t,n)=>{var r=n(39344),o=n(28879),s=n(55527);e.exports=function(e){return"function"!=typeof e.constructor||s(e)?{}:r(o(e))}},62060:e=>{var o=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;e.exports=function(e,t){var n=t.length;if(!n)return e;var r=n-1;return t[r]=(1{var r=n(51873),o=n(72428),s=n(56449),i=r?r.isConcatSpreadable:void 0;e.exports=function(e){return s(e)||o(e)||!!(i&&e&&e[i])}},30361:e=>{var r=/^(?:0|[1-9]\d*)$/;e.exports=function(e,t){var n=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==n||"symbol"!=n&&r.test(e))&&-1{var o=n(75288),s=n(64894),i=n(30361),a=n(23805);e.exports=function(e,t,n){if(!a(n))return!1;var r=typeof t;return!!("number"==r?s(n)&&i(t,n.length):"string"==r&&t in n)&&o(n[t],e)}},28586:(e,t,n)=>{var r=n(56449),o=n(44394),s=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,i=/^\w*$/;e.exports=function(e,t){if(r(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!o(e))||i.test(e)||!s.test(e)||null!=t&&e in Object(t)}},74218:e=>{e.exports=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}},85087:(e,t,n)=>{var r=n(30980),o=n(37381),s=n(62284),i=n(53758);e.exports=function(e){var t=s(e),n=i[t];if("function"!=typeof n||!(t in r.prototype))return!1;if(e===n)return!0;t=o(n);return!!t&&e===t[0]}},87296:(e,t,n)=>{var n=n(55481),r=(n=/[^.]+$/.exec(n&&n.keys&&n.keys.IE_PROTO||""))?"Symbol(src)_1."+n:"";e.exports=function(e){return!!r&&r in e}},55527:e=>{var n=Object.prototype;e.exports=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||n)}},30756:(e,t,n)=>{var r=n(23805);e.exports=function(e){return e==e&&!r(e)}},63702:e=>{e.exports=function(){this.__data__=[],this.size=0}},70080:(e,t,n)=>{var r=n(26025),o=Array.prototype.splice;e.exports=function(e){var t=this.__data__,e=r(t,e);return!(e<0||(e==t.length-1?t.pop():o.call(t,e,1),--this.size,0))}},24739:(e,t,n)=>{var r=n(26025);e.exports=function(e){var t=this.__data__,e=r(t,e);return e<0?void 0:t[e][1]}},48655:(e,t,n)=>{var r=n(26025);e.exports=function(e){return-1{var o=n(26025);e.exports=function(e,t){var n=this.__data__,r=o(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}},63040:(e,t,n)=>{var r=n(21549),o=n(80079),s=n(68223);e.exports=function(){this.size=0,this.__data__={hash:new r,map:new(s||o),string:new r}}},17670:(e,t,n)=>{var r=n(12651);e.exports=function(e){e=r(this,e).delete(e);return this.size-=e?1:0,e}},90289:(e,t,n)=>{var r=n(12651);e.exports=function(e){return r(this,e).get(e)}},4509:(e,t,n)=>{var r=n(12651);e.exports=function(e){return r(this,e).has(e)}},72949:(e,t,n)=>{var o=n(12651);e.exports=function(e,t){var n=o(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}},20317:e=>{e.exports=function(e){var n=-1,r=Array(e.size);return e.forEach(function(e,t){r[++n]=[t,e]}),r}},67197:e=>{e.exports=function(t,n){return function(e){return null!=e&&e[t]===n&&(void 0!==n||t in Object(e))}}},62224:(e,t,n)=>{var r=n(50104);e.exports=function(e){var e=r(e,function(e){return 500===t.size&&t.clear(),e}),t=e.cache;return e}},3209:(e,t,n)=>{var a=n(91596),l=n(53320),c=n(36306),u="__lodash_placeholder__",p=Math.min;e.exports=function(e,t){var n=e[1],r=t[1],o=n|r,s=128==r&&8==n||128==r&&256==n&&e[7].length<=t[8]||384==r&&t[7].length<=t[8]&&8==n;if(!(o<131)&&!s)return e;1&r&&(e[2]=t[2],o|=1&n?0:4);var i,s=t[3];return s&&(i=e[3],e[3]=i?a(i,s,t[4]):s,e[4]=i?c(e[3],u):t[4]),(s=t[5])&&(i=e[5],e[5]=i?l(i,s,t[6]):s,e[6]=i?c(e[5],u):t[6]),(s=t[7])&&(e[7]=s),128&r&&(e[8]=null==e[8]?t[8]:p(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=o,e}},48152:(e,t,n)=>{n=n(28303),n=n&&new n;e.exports=n},81042:(e,t,n)=>{n=n(56110)(Object,"create");e.exports=n},3650:(e,t,n)=>{n=n(74335)(Object.keys,Object);e.exports=n},90181:e=>{e.exports=function(e){var t=[];if(null!=e)for(var n in Object(e))t.push(n);return t}},86009:(e,t,n)=>{e=n.nmd(e);var n=n(34840),t=t&&!t.nodeType&&t,r=t&&e&&!e.nodeType&&e,o=r&&r.exports===t&&n.process,t=function(){try{return r&&r.require&&r.require("util").types||o&&o.binding&&o.binding("util")}catch(e){}}();e.exports=t},59350:e=>{var t=Object.prototype.toString;e.exports=function(e){return t.call(e)}},74335:e=>{e.exports=function(t,n){return function(e){return t(n(e))}}},56757:(e,t,n)=>{var l=n(91033),c=Math.max;e.exports=function(s,i,a){return i=c(void 0===i?s.length-1:i,0),function(){for(var e=arguments,t=-1,n=c(e.length-i,0),r=Array(n);++t{var r=n(47422),o=n(25160);e.exports=function(e,t){return t.length<2?e:r(e,o(t,0,-1))}},84629:e=>{e.exports={}},68294:(e,t,n)=>{var i=n(23007),a=n(30361),l=Math.min;e.exports=function(e,t){for(var n=e.length,r=l(t.length,n),o=i(e);r--;){var s=t[r];e[r]=a(s,n)?o[s]:void 0}return e}},36306:e=>{var a="__lodash_placeholder__";e.exports=function(e,t){for(var n=-1,r=e.length,o=0,s=[];++n{var n=n(34840),r="object"==typeof self&&self&&self.Object===Object&&self,n=n||r||Function("return this")();e.exports=n},14974:e=>{e.exports=function(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]}},31380:e=>{e.exports=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this}},51459:e=>{e.exports=function(e){return this.__data__.has(e)}},54641:(e,t,n)=>{var r=n(68882),n=n(51811)(r);e.exports=n},84247:e=>{e.exports=function(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}},32865:(e,t,n)=>{var r=n(19570),n=n(51811)(r);e.exports=n},70981:(e,t,n)=>{var r=n(75251),o=n(62060),s=n(32865),i=n(75948);e.exports=function(e,t,n){t+="";return s(e,o(t,i(r(t),n)))}},51811:e=>{var s=Date.now;e.exports=function(n){var r=0,o=0;return function(){var e=s(),t=16-(e-o);if(o=e,0{var r=n(80079);e.exports=function(){this.__data__=new r,this.size=0}},90938:e=>{e.exports=function(e){var t=this.__data__,e=t.delete(e);return this.size=t.size,e}},63605:e=>{e.exports=function(e){return this.__data__.get(e)}},29817:e=>{e.exports=function(e){return this.__data__.has(e)}},80945:(e,t,n)=>{var o=n(80079),s=n(68223),i=n(53661);e.exports=function(e,t){var n=this.__data__;if(n instanceof o){var r=n.__data__;if(!s||r.length<199)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new i(r)}return n.set(e,t),this.size=n.size,this}},76959:e=>{e.exports=function(e,t,n){for(var r=n-1,o=e.length;++r{var r=n(61074),o=n(49698),s=n(42054);e.exports=function(e){return(o(e)?s:r)(e)}},61802:(e,t,n)=>{var n=n(62224),r=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,s=/\\(\\)?/g,n=n(function(e){var o=[];return 46===e.charCodeAt(0)&&o.push(""),e.replace(r,function(e,t,n,r){o.push(n?r.replace(s,"$1"):t||e)}),o});e.exports=n},77797:(e,t,n)=>{var r=n(44394);e.exports=function(e){if("string"==typeof e||r(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}},47473:e=>{var t=Function.prototype.toString;e.exports=function(e){if(null!=e){try{return t.call(e)}catch(e){}try{return e+""}catch(e){}}return""}},31800:e=>{var n=/\s/;e.exports=function(e){for(var t=e.length;t--&&n.test(e.charAt(t)););return t}},42054:e=>{var t="\\ud800-\\udfff",n="["+t+"]",r="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",o="\\ud83c[\\udffb-\\udfff]",t="[^"+t+"]",s="(?:\\ud83c[\\udde6-\\uddff]){2}",i="[\\ud800-\\udbff][\\udc00-\\udfff]",a="(?:"+r+"|"+o+")?",l="[\\ufe0e\\ufe0f]?",l=l+a+"(?:\\u200d(?:"+[t,s,i].join("|")+")"+l+a+")*",a="(?:"+[t+r+"?",r,s,i,n].join("|")+")",c=RegExp(o+"(?="+o+")|"+a+l,"g");e.exports=function(e){return e.match(c)||[]}},22225:e=>{var t="\\ud800-\\udfff",n="\\u2700-\\u27bf",r="a-z\\xdf-\\xf6\\xf8-\\xff",o="A-Z\\xc0-\\xd6\\xd8-\\xde",s="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",i="["+s+"]",a="["+n+"]",l="["+r+"]",s="[^"+t+s+"\\d+"+n+r+o+"]",n="(?:\\ud83c[\\udde6-\\uddff]){2}",r="[\\ud800-\\udbff][\\udc00-\\udfff]",o="["+o+"]",c="(?:"+l+"|"+s+")",s="(?:"+o+"|"+s+")",u="(?:['’](?:d|ll|m|re|s|t|ve))?",p="(?:['’](?:D|LL|M|RE|S|T|VE))?",h="(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?",d="[\\ufe0e\\ufe0f]?",t=d+h+"(?:\\u200d(?:"+["[^"+t+"]",n,r].join("|")+")"+d+h+")*",d="(?:"+[a,n,r].join("|")+")"+t,f=RegExp([o+"?"+l+"+"+u+"(?="+[i,o,"$"].join("|")+")",s+"+"+p+"(?="+[i,o+c,"$"].join("|")+")",o+"?"+c+"+"+u,o+"+"+p,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])","\\d+",d].join("|"),"g");e.exports=function(e){return e.match(f)||[]}},75948:(e,t,n)=>{var o=n(83729),s=n(15325),i=[["ary",128],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",32],["partialRight",64],["rearg",256]];e.exports=function(n,r){return o(i,function(e){var t="_."+e[0];r&e[1]&&!s(n,t)&&n.push(t)}),n.sort()}},80257:(e,t,n)=>{var r=n(30980),o=n(56017),s=n(23007);e.exports=function(e){if(e instanceof r)return e.clone();var t=new o(e.__wrapped__,e.__chain__);return t.__actions__=s(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}},64626:(e,t,n)=>{var r=n(66977);e.exports=function(e,t,n){return t=n?void 0:t,t=e&&null==t?e.length:t,r(e,128,void 0,void 0,void 0,void 0,t)}},84058:(e,t,n)=>{var r=n(14792),n=n(45539)(function(e,t,n){return t=t.toLowerCase(),e+(n?r(t):t)});e.exports=n},14792:(e,t,n)=>{var r=n(13222),o=n(55808);e.exports=function(e){return o(r(e).toLowerCase())}},32629:(e,t,n)=>{var r=n(9999);e.exports=function(e){return r(e,4)}},37334:e=>{e.exports=function(e){return function(){return e}}},49747:(e,t,n)=>{var r=n(66977);function o(e,t,n){e=r(e,8,void 0,void 0,void 0,void 0,void 0,t=n?void 0:t);return e.placeholder=o.placeholder,e}o.placeholder={},e.exports=o},38221:(e,t,n)=>{var v=n(23805),b=n(10124),w=n(99374),E=Math.max,S=Math.min;e.exports=function(r,n,e){var o,s,i,a,l,c,u=0,p=!1,h=!1,t=!0;if("function"!=typeof r)throw new TypeError("Expected a function");function d(e){var t=o,n=s;return o=s=void 0,u=e,a=r.apply(n,t)}function f(e){var t=e-c;return void 0===c||n<=t||t<0||h&&i<=e-u}function m(){var e,t=b();if(f(t))return g(t);l=setTimeout(m,(e=n-((t=t)-c),h?S(e,i-(t-u)):e))}function g(e){return l=void 0,t&&o?d(e):(o=s=void 0,a)}function y(){var e=b(),t=f(e);if(o=arguments,s=this,c=e,t){if(void 0===l)return u=e=c,l=setTimeout(m,n),p?d(e):a;if(h)return clearTimeout(l),l=setTimeout(m,n),d(c)}return void 0===l&&(l=setTimeout(m,n)),a}return n=w(n)||0,v(e)&&(p=!!e.leading,i=(h="maxWait"in e)?E(w(e.maxWait)||0,n):i,t="trailing"in e?!!e.trailing:t),y.cancel=function(){void 0!==l&&clearTimeout(l),o=c=s=l=void(u=0)},y.flush=function(){return void 0===l?a:g(b())},y}},50828:(e,t,n)=>{var r=n(24647),o=n(13222),s=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,i=RegExp("[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]","g");e.exports=function(e){return(e=o(e))&&e.replace(s,r).replace(i,"")}},75288:e=>{e.exports=function(e,t){return e===t||e!=e&&t!=t}},7309:(e,t,n)=>{n=n(62006)(n(24713));e.exports=n},24713:(e,t,n)=>{var o=n(2523),s=n(15389),i=n(61489),a=Math.max;e.exports=function(e,t,n){var r=null==e?0:e.length;if(!r)return-1;n=null==n?0:i(n);return n<0&&(n=a(r+n,0)),o(e,s(t,3),n)}},35970:(e,t,n)=>{var r=n(83120);e.exports=function(e){return null!=e&&e.length?r(e,1):[]}},73424:(e,t,n)=>{var B=n(16962),L=n(2874),q=Array.prototype.push;function $(n,e){return 2==e?function(e,t){return n(e,t)}:function(e){return n(e)}}function z(e){for(var t=e?e.length:0,n=Array(t);t--;)n[t]=e[t];return n}function U(r,o){return function(){var e=arguments.length;if(e){for(var t=Array(e);e--;)t[e]=arguments[e];var n=t[0]=o.apply(void 0,t);return r.apply(void 0,t),n}}}e.exports=function a(n,e,t,l){var c="function"==typeof e,r=e===Object(e);if(r&&(l=t,t=e,e=void 0),null==t)throw new TypeError;var u={cap:!("cap"in(l=l||{}))||l.cap,curry:!("curry"in l)||l.curry,fixed:!("fixed"in l)||l.fixed,immutable:!("immutable"in l)||l.immutable,rearg:!("rearg"in l)||l.rearg},o=c?t:L,p="curry"in l&&l.curry,h="fixed"in l&&l.fixed,s="rearg"in l&&l.rearg,d=c?t.runInContext():void 0,f=c?t:{ary:n.ary,assign:n.assign,clone:n.clone,curry:n.curry,forEach:n.forEach,isArray:n.isArray,isError:n.isError,isFunction:n.isFunction,isWeakMap:n.isWeakMap,iteratee:n.iteratee,keys:n.keys,rearg:n.rearg,toInteger:n.toInteger,toPath:n.toPath},m=f.ary,g=f.assign,y=f.clone,v=f.curry,b=f.forEach,i=f.isArray,w=f.isError,E=f.isFunction,S=f.isWeakMap,x=f.keys,_=f.rearg,k=f.toInteger,A=f.toPath,O=x(B.aryMethod),C={castArray:function(t){return function(){var e=arguments[0];return i(e)?t(z(e)):t.apply(void 0,arguments)}},iteratee:function(r){return function(){var e=arguments[1],t=r(arguments[0],e),n=t.length;return u.cap&&"number"==typeof e?(e=2{s.aliasToReal={each:"forEach",eachRight:"forEachRight",entries:"toPairs",entriesIn:"toPairsIn",extend:"assignIn",extendAll:"assignInAll",extendAllWith:"assignInAllWith",extendWith:"assignInWith",first:"head",conforms:"conformsTo",matches:"isMatch",property:"get",__:"placeholder",F:"stubFalse",T:"stubTrue",all:"every",allPass:"overEvery",always:"constant",any:"some",anyPass:"overSome",apply:"spread",assoc:"set",assocPath:"set",complement:"negate",compose:"flowRight",contains:"includes",dissoc:"unset",dissocPath:"unset",dropLast:"dropRight",dropLastWhile:"dropRightWhile",equals:"isEqual",identical:"eq",indexBy:"keyBy",init:"initial",invertObj:"invert",juxt:"over",omitAll:"omit",nAry:"ary",path:"get",pathEq:"matchesProperty",pathOr:"getOr",paths:"at",pickAll:"pick",pipe:"flow",pluck:"map",prop:"get",propEq:"matchesProperty",propOr:"getOr",props:"at",symmetricDifference:"xor",symmetricDifferenceBy:"xorBy",symmetricDifferenceWith:"xorWith",takeLast:"takeRight",takeLastWhile:"takeRightWhile",unapply:"rest",unnest:"flatten",useWith:"overArgs",where:"conformsTo",whereEq:"isMatch",zipObj:"zipObject"},s.aryMethod={1:["assignAll","assignInAll","attempt","castArray","ceil","create","curry","curryRight","defaultsAll","defaultsDeepAll","floor","flow","flowRight","fromPairs","invert","iteratee","memoize","method","mergeAll","methodOf","mixin","nthArg","over","overEvery","overSome","rest","reverse","round","runInContext","spread","template","trim","trimEnd","trimStart","uniqueId","words","zipAll"],2:["add","after","ary","assign","assignAllWith","assignIn","assignInAllWith","at","before","bind","bindAll","bindKey","chunk","cloneDeepWith","cloneWith","concat","conformsTo","countBy","curryN","curryRightN","debounce","defaults","defaultsDeep","defaultTo","delay","difference","divide","drop","dropRight","dropRightWhile","dropWhile","endsWith","eq","every","filter","find","findIndex","findKey","findLast","findLastIndex","findLastKey","flatMap","flatMapDeep","flattenDepth","forEach","forEachRight","forIn","forInRight","forOwn","forOwnRight","get","groupBy","gt","gte","has","hasIn","includes","indexOf","intersection","invertBy","invoke","invokeMap","isEqual","isMatch","join","keyBy","lastIndexOf","lt","lte","map","mapKeys","mapValues","matchesProperty","maxBy","meanBy","merge","mergeAllWith","minBy","multiply","nth","omit","omitBy","overArgs","pad","padEnd","padStart","parseInt","partial","partialRight","partition","pick","pickBy","propertyOf","pull","pullAll","pullAt","random","range","rangeRight","rearg","reject","remove","repeat","restFrom","result","sampleSize","some","sortBy","sortedIndex","sortedIndexOf","sortedLastIndex","sortedLastIndexOf","sortedUniqBy","split","spreadFrom","startsWith","subtract","sumBy","take","takeRight","takeRightWhile","takeWhile","tap","throttle","thru","times","trimChars","trimCharsEnd","trimCharsStart","truncate","union","uniqBy","uniqWith","unset","unzipWith","without","wrap","xor","zip","zipObject","zipObjectDeep"],3:["assignInWith","assignWith","clamp","differenceBy","differenceWith","findFrom","findIndexFrom","findLastFrom","findLastIndexFrom","getOr","includesFrom","indexOfFrom","inRange","intersectionBy","intersectionWith","invokeArgs","invokeArgsMap","isEqualWith","isMatchWith","flatMapDepth","lastIndexOfFrom","mergeWith","orderBy","padChars","padCharsEnd","padCharsStart","pullAllBy","pullAllWith","rangeStep","rangeStepRight","reduce","reduceRight","replace","set","slice","sortedIndexBy","sortedLastIndexBy","transform","unionBy","unionWith","update","xorBy","xorWith","zipWith"],4:["fill","setWith","updateWith"]},s.aryRearg={2:[1,0],3:[2,0,1],4:[3,2,0,1]},s.iterateeAry={dropRightWhile:1,dropWhile:1,every:1,filter:1,find:1,findFrom:1,findIndex:1,findIndexFrom:1,findKey:1,findLast:1,findLastFrom:1,findLastIndex:1,findLastIndexFrom:1,findLastKey:1,flatMap:1,flatMapDeep:1,flatMapDepth:1,forEach:1,forEachRight:1,forIn:1,forInRight:1,forOwn:1,forOwnRight:1,map:1,mapKeys:1,mapValues:1,partition:1,reduce:2,reduceRight:2,reject:1,remove:1,some:1,takeRightWhile:1,takeWhile:1,times:1,transform:2},s.iterateeRearg={mapKeys:[1],reduceRight:[1,0]},s.methodRearg={assignInAllWith:[1,0],assignInWith:[1,2,0],assignAllWith:[1,0],assignWith:[1,2,0],differenceBy:[1,2,0],differenceWith:[1,2,0],getOr:[2,1,0],intersectionBy:[1,2,0],intersectionWith:[1,2,0],isEqualWith:[1,2,0],isMatchWith:[2,1,0],mergeAllWith:[1,0],mergeWith:[1,2,0],padChars:[2,1,0],padCharsEnd:[2,1,0],padCharsStart:[2,1,0],pullAllBy:[2,1,0],pullAllWith:[2,1,0],rangeStep:[1,2,0],rangeStepRight:[1,2,0],setWith:[3,1,2,0],sortedIndexBy:[2,1,0],sortedLastIndexBy:[2,1,0],unionBy:[1,2,0],unionWith:[1,2,0],updateWith:[3,1,2,0],xorBy:[1,2,0],xorWith:[1,2,0],zipWith:[1,2,0]},s.methodSpread={assignAll:{start:0},assignAllWith:{start:0},assignInAll:{start:0},assignInAllWith:{start:0},defaultsAll:{start:0},defaultsDeepAll:{start:0},invokeArgs:{start:2},invokeArgsMap:{start:2},mergeAll:{start:0},mergeAllWith:{start:0},partial:{start:1},partialRight:{start:1},without:{start:1},zipAll:{start:0}},s.mutate={array:{fill:!0,pull:!0,pullAll:!0,pullAllBy:!0,pullAllWith:!0,pullAt:!0,remove:!0,reverse:!0},object:{assign:!0,assignAll:!0,assignAllWith:!0,assignIn:!0,assignInAll:!0,assignInAllWith:!0,assignInWith:!0,assignWith:!0,defaults:!0,defaultsAll:!0,defaultsDeep:!0,defaultsDeepAll:!0,merge:!0,mergeAll:!0,mergeAllWith:!0,mergeWith:!0},set:{set:!0,setWith:!0,unset:!0,update:!0,updateWith:!0}},s.realToAlias=function(){var e,t=Object.prototype.hasOwnProperty,n=s.aliasToReal,r={};for(e in n){var o=n[e];t.call(r,o)?r[o].push(e):r[o]=[e]}return r}(),s.remap={assignAll:"assign",assignAllWith:"assignWith",assignInAll:"assignIn",assignInAllWith:"assignInWith",curryN:"curry",curryRightN:"curryRight",defaultsAll:"defaults",defaultsDeepAll:"defaultsDeep",findFrom:"find",findIndexFrom:"findIndex",findLastFrom:"findLast",findLastIndexFrom:"findLastIndex",getOr:"get",includesFrom:"includes",indexOfFrom:"indexOf",invokeArgs:"invoke",invokeArgsMap:"invokeMap",lastIndexOfFrom:"lastIndexOf",mergeAll:"merge",mergeAllWith:"mergeWith",padChars:"pad",padCharsEnd:"padEnd",padCharsStart:"padStart",propertyOf:"get",rangeStep:"range",rangeStepRight:"rangeRight",restFrom:"rest",spreadFrom:"spread",trimChars:"trim",trimCharsEnd:"trimEnd",trimCharsStart:"trimStart",zipAll:"zip"},s.skipFixed={castArray:!0,flow:!0,flowRight:!0,iteratee:!0,mixin:!0,rearg:!0,runInContext:!0},s.skipRearg={add:!0,assign:!0,assignIn:!0,bind:!0,bindKey:!0,concat:!0,difference:!0,divide:!0,eq:!0,gt:!0,gte:!0,isEqual:!0,lt:!0,lte:!0,matchesProperty:!0,merge:!0,multiply:!0,overArgs:!0,partial:!0,partialRight:!0,propertyOf:!0,random:!0,range:!0,rangeRight:!0,subtract:!0,zip:!0,zipObject:!0,zipObjectDeep:!0}},47934:(e,t,n)=>{e.exports={ary:n(64626),assign:n(74733),clone:n(32629),curry:n(49747),forEach:n(83729),isArray:n(56449),isError:n(23546),isFunction:n(1882),isWeakMap:n(47886),iteratee:n(33855),keys:n(88984),rearg:n(84195),toInteger:n(61489),toPath:n(42072)}},56367:(e,t,n)=>{e.exports=n(77731)},79920:(e,t,n)=>{var r=n(73424),o=n(47934);e.exports=function(e,t,n){return r(o,e,t,n)}},2874:e=>{e.exports={}},77731:(e,t,n)=>{var r=n(79920)("set",n(63560));r.placeholder=n(2874),e.exports=r},58156:(e,t,n)=>{var r=n(47422);e.exports=function(e,t,n){e=null==e?void 0:r(e,t);return void 0===e?n:e}},80631:(e,t,n)=>{var r=n(28077),o=n(49326);e.exports=function(e,t){return null!=e&&o(e,t,r)}},83488:e=>{e.exports=function(e){return e}},72428:(e,t,n)=>{var r=n(27534),o=n(40346),n=Object.prototype,s=n.hasOwnProperty,i=n.propertyIsEnumerable,n=r(function(){return arguments}())?r:function(e){return o(e)&&s.call(e,"callee")&&!i.call(e,"callee")};e.exports=n},56449:e=>{var t=Array.isArray;e.exports=t},64894:(e,t,n)=>{var r=n(1882),o=n(30294);e.exports=function(e){return null!=e&&o(e.length)&&!r(e)}},83693:(e,t,n)=>{var r=n(64894),o=n(40346);e.exports=function(e){return o(e)&&r(e)}},53812:(e,t,n)=>{var r=n(72552),o=n(40346);e.exports=function(e){return!0===e||!1===e||o(e)&&"[object Boolean]"==r(e)}},3656:(e,t,n)=>{e=n.nmd(e);var r=n(9325),n=n(89935),t=t&&!t.nodeType&&t,o=t&&e&&!e.nodeType&&e,o=o&&o.exports===t?r.Buffer:void 0,t=(o?o.isBuffer:void 0)||n;e.exports=t},62193:(e,t,n)=>{var r=n(88984),o=n(5861),s=n(72428),i=n(56449),a=n(64894),l=n(3656),c=n(55527),u=n(37167),p=Object.prototype.hasOwnProperty;e.exports=function(e){if(null==e)return!0;if(a(e)&&(i(e)||"string"==typeof e||"function"==typeof e.splice||l(e)||u(e)||s(e)))return!e.length;var t,n=o(e);if("[object Map]"==n||"[object Set]"==n)return!e.size;if(c(e))return!r(e).length;for(t in e)if(p.call(e,t))return!1;return!0}},2404:(e,t,n)=>{var r=n(60270);e.exports=function(e,t){return r(e,t)}},23546:(e,t,n)=>{var r=n(72552),o=n(40346),s=n(11331);e.exports=function(e){if(!o(e))return!1;var t=r(e);return"[object Error]"==t||"[object DOMException]"==t||"string"==typeof e.message&&"string"==typeof e.name&&!s(e)}},1882:(e,t,n)=>{var r=n(72552),o=n(23805);e.exports=function(e){if(!o(e))return!1;e=r(e);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}},30294:e=>{e.exports=function(e){return"number"==typeof e&&-1{var r=n(29172),o=n(27301),n=n(86009),n=n&&n.isMap,o=n?o(n):r;e.exports=o},5187:e=>{e.exports=function(e){return null===e}},98023:(e,t,n)=>{var r=n(72552),o=n(40346);e.exports=function(e){return"number"==typeof e||o(e)&&"[object Number]"==r(e)}},23805:e=>{e.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},40346:e=>{e.exports=function(e){return null!=e&&"object"==typeof e}},11331:(e,t,n)=>{var r=n(72552),o=n(28879),s=n(40346),n=Function.prototype,i=Object.prototype,a=n.toString,l=i.hasOwnProperty,c=a.call(Object);e.exports=function(e){if(!s(e)||"[object Object]"!=r(e))return!1;e=o(e);if(null===e)return!0;e=l.call(e,"constructor")&&e.constructor;return"function"==typeof e&&e instanceof e&&a.call(e)==c}},38440:(e,t,n)=>{var r=n(16038),o=n(27301),n=n(86009),n=n&&n.isSet,o=n?o(n):r;e.exports=o},85015:(e,t,n)=>{var r=n(72552),o=n(56449),s=n(40346);e.exports=function(e){return"string"==typeof e||!o(e)&&s(e)&&"[object String]"==r(e)}},44394:(e,t,n)=>{var r=n(72552),o=n(40346);e.exports=function(e){return"symbol"==typeof e||o(e)&&"[object Symbol]"==r(e)}},37167:(e,t,n)=>{var r=n(4901),o=n(27301),n=n(86009),n=n&&n.isTypedArray,o=n?o(n):r;e.exports=o},47886:(e,t,n)=>{var r=n(5861),o=n(40346);e.exports=function(e){return o(e)&&"[object WeakMap]"==r(e)}},33855:(e,t,n)=>{var r=n(9999),o=n(15389);e.exports=function(e){return o("function"==typeof e?e:r(e,1))}},95950:(e,t,n)=>{var r=n(70695),o=n(88984),s=n(64894);e.exports=function(e){return(s(e)?r:o)(e)}},37241:(e,t,n)=>{var r=n(70695),o=n(72903),s=n(64894);e.exports=function(e){return s(e)?r(e,!0):o(e)}},68090:e=>{e.exports=function(e){var t=null==e?0:e.length;return t?e[t-1]:void 0}},50104:(e,t,n)=>{var i=n(53661);function a(r,o){if("function"!=typeof r||null!=o&&"function"!=typeof o)throw new TypeError("Expected a function");function s(){var e=arguments,t=o?o.apply(this,e):e[0],n=s.cache;return n.has(t)?n.get(t):(e=r.apply(this,e),s.cache=n.set(t,e)||n,e)}return s.cache=new(a.Cache||i),s}a.Cache=i,e.exports=a},55364:(e,t,n)=>{var r=n(85250),n=n(20999)(function(e,t,n){r(e,t,n)});e.exports=n},6048:e=>{e.exports=function(t){if("function"!=typeof t)throw new TypeError("Expected a function");return function(){var e=arguments;switch(e.length){case 0:return!t.call(this);case 1:return!t.call(this,e[0]);case 2:return!t.call(this,e[0],e[1]);case 3:return!t.call(this,e[0],e[1],e[2])}return!t.apply(this,e)}}},63950:e=>{e.exports=function(){}},10124:(e,t,n)=>{var r=n(9325);e.exports=function(){return r.Date.now()}},90179:(e,t,n)=>{var s=n(34932),i=n(9999),a=n(19931),l=n(31769),c=n(21791),u=n(53138),r=n(38816),p=n(83349),n=r(function(t,e){var n={};if(null==t)return n;var r=!1;e=s(e,function(e){return e=l(e,t),r=r||1{var r=n(47237),o=n(17255),s=n(28586),i=n(77797);e.exports=function(e){return s(e)?r(i(e)):o(e)}},84195:(e,t,n)=>{var r=n(66977),n=n(38816)(function(e,t){return r(e,256,void 0,void 0,void 0,t)});e.exports=n},40860:(e,t,n)=>{var s=n(40882),i=n(80909),a=n(15389),l=n(85558),c=n(56449);e.exports=function(e,t,n){var r=c(e)?s:l,o=arguments.length<3;return r(e,a(t,4),n,o,i)}},63560:(e,t,n)=>{var r=n(73170);e.exports=function(e,t,n){return null==e?e:r(e,t,n)}},42426:(e,t,n)=>{var o=n(14248),s=n(15389),i=n(90916),a=n(56449),l=n(36800);e.exports=function(e,t,n){var r=a(e)?o:i;return n&&l(e,t,n)&&(t=void 0),r(e,s(t,3))}},63345:e=>{e.exports=function(){return[]}},89935:e=>{e.exports=function(){return!1}},17400:(e,t,n)=>{var r=n(99374);e.exports=function(e){return e?(e=r(e))===1/0||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}},61489:(e,t,n)=>{var r=n(17400);e.exports=function(e){var e=r(e),t=e%1;return e==e?t?e-t:e:0}},80218:(e,t,n)=>{var r=n(13222);e.exports=function(e){return r(e).toLowerCase()}},99374:(e,t,n)=>{var r=n(54128),o=n(23805),s=n(44394),i=/^[-+]0x[0-9a-f]+$/i,a=/^0b[01]+$/i,l=/^0o[0-7]+$/i,c=parseInt;e.exports=function(e){if("number"==typeof e)return e;if(s(e))return NaN;if(o(e)&&(t="function"==typeof e.valueOf?e.valueOf():e,e=o(t)?t+"":t),"string"!=typeof e)return 0===e?e:+e;e=r(e);var t=a.test(e);return t||l.test(e)?c(e.slice(2),t?2:8):i.test(e)?NaN:+e}},42072:(e,t,n)=>{var r=n(34932),o=n(23007),s=n(56449),i=n(44394),a=n(61802),l=n(77797),c=n(13222);e.exports=function(e){return s(e)?r(e,l):i(e)?[e]:o(a(c(e)))}},69884:(e,t,n)=>{var r=n(21791),o=n(37241);e.exports=function(e){return r(e,o(e))}},13222:(e,t,n)=>{var r=n(77556);e.exports=function(e){return null==e?"":r(e)}},55808:(e,t,n)=>{n=n(12507)("toUpperCase");e.exports=n},66645:(e,t,n)=>{var r=n(1733),o=n(45434),s=n(13222),i=n(22225);e.exports=function(e,t,n){return e=s(e),void 0===(t=n?void 0:t)?(o(e)?i:r)(e):e.match(t)||[]}},53758:(e,t,n)=>{var r=n(30980),o=n(56017),s=n(94033),i=n(56449),a=n(40346),l=n(80257),c=Object.prototype.hasOwnProperty;function u(e){if(a(e)&&!i(e)&&!(e instanceof r)){if(e instanceof o)return e;if(c.call(e,"__wrapped__"))return l(e)}return new o(e)}u.prototype=s.prototype,e.exports=u.prototype.constructor=u},47248:(e,t,n)=>{var r=n(16547),o=n(51234);e.exports=function(e,t){return o(e||[],t||[],r)}},43768:(e,t,n)=>{"use strict";var u=n(45981),p=n(85587),o=(t.highlight=h,t.highlightAuto=function(e,t){var n,r,o,s,i=t||{},a=i.subset||u.listLanguages(),i=i.prefix,l=a.length,c=-1;if(null==i&&0,"string"!=typeof e)throw p("Expected `string` for value, got `%s`",e);for(r={relevance:0,language:null,value:[]},n={relevance:0,language:null,value:[]};++cr.relevance&&(r=o),o.relevance>n.relevance&&(r=n,n=o));return r.language&&(n.secondBest=r),n},t.registerLanguage=function(e,t){u.registerLanguage(e,t)},t.listLanguages=function(){return u.listLanguages()},t.registerAlias=function(e,t){var n,r=e;for(n in t&&((r={})[e]=t),r)u.registerAliases(r[n],{languageName:n})},s.prototype.addText=function(e){var t,n=this.stack;""!==e&&((t=(n=n[n.length-1]).children[n.children.length-1])&&"text"===t.type?t.value+=e:n.children.push({type:"text",value:e}))},s.prototype.addKeyword=function(e,t){this.openNode(t),this.addText(e),this.closeNode()},s.prototype.addSublanguage=function(e,t){var n=this.stack,n=n[n.length-1],e=e.rootNode.children;n.children=n.children.concat(t?{type:"element",tagName:"span",properties:{className:[t]},children:e}:e)},s.prototype.openNode=function(e){var t=this.stack,e={type:"element",tagName:"span",properties:{className:[this.options.classPrefix+e]},children:[]};t[t.length-1].children.push(e),t.push(e)},s.prototype.closeNode=function(){this.stack.pop()},s.prototype.closeAllNodes=r,s.prototype.finalize=r,s.prototype.toHTML=function(){return""},"hljs-");function h(e,t,n){var r=u.configure({}),n=(n||{}).prefix;if("string"!=typeof e)throw p("Expected `string` for name, got `%s`",e);if(!u.getLanguage(e))throw p("Unknown language: `%s` is not registered",e);if("string"!=typeof t)throw p("Expected `string` for value, got `%s`",t);if(u.configure({__emitter:s,classPrefix:n=null==n?o:n}),n=u.highlight(t,{language:e,ignoreIllegals:!0}),u.configure(r||{}),n.errorRaised)throw n.errorRaised;return{relevance:n.relevance,language:n.language,value:n.emitter.rootNode.children}}function s(e){this.options=e,this.rootNode={children:[]},this.stack=[this.rootNode]}function r(){}},92340:(e,t,n)=>{const r=n(6048);function o(t){return"string"==typeof t?e=>e.element===t:t.constructor&&t.extend?e=>e instanceof t:t}class s{constructor(e){this.elements=e||[]}toValue(){return this.elements.map(e=>e.toValue())}map(e,t){return this.elements.map(e,t)}flatMap(e,t){return this.map(e,t).reduce((e,t)=>e.concat(t),[])}compactMap(t,n){const r=[];return this.forEach(e=>{e=t.bind(n)(e);e&&r.push(e)}),r}filter(e,t){return e=o(e),new s(this.elements.filter(e,t))}reject(e,t){return e=o(e),new s(this.elements.filter(r(e),t))}find(e,t){return e=o(e),this.elements.find(e,t)}forEach(e,t){this.elements.forEach(e,t)}reduce(e,t){return this.elements.reduce(e,t)}includes(t){return this.elements.some(e=>e.equals(t))}shift(){return this.elements.shift()}unshift(e){this.elements.unshift(this.refract(e))}push(e){return this.elements.push(this.refract(e)),this}add(e){this.push(e)}get(e){return this.elements[e]}getValue(e){const t=this.elements[e];if(t)return t.toValue()}get length(){return this.elements.length}get isEmpty(){return 0===this.elements.length}get first(){return this.elements[0]}}"undefined"!=typeof Symbol&&(s.prototype[Symbol.iterator]=function(){return this.elements[Symbol.iterator]()}),e.exports=s},55973:e=>{e.exports=class t{constructor(e,t){this.key=e,this.value=t}clone(){const e=new t;return this.key&&(e.key=this.key.clone()),this.value&&(e.value=this.value.clone()),e}}},3110:(e,t,n)=>{const r=n(5187),o=n(85015),s=n(98023),i=n(53812),a=n(23805),l=n(85105),c=n(86804);class u{constructor(e){this.elementMap={},this.elementDetection=[],this.Element=c.Element,this.KeyValuePair=c.KeyValuePair,e&&e.noDefault||this.useDefault(),this._attributeElementKeys=[],this._attributeElementArrayKeys=[]}use(e){return e.namespace&&e.namespace({base:this}),e.load&&e.load({base:this}),this}useDefault(){return this.register("null",c.NullElement).register("string",c.StringElement).register("number",c.NumberElement).register("boolean",c.BooleanElement).register("array",c.ArrayElement).register("object",c.ObjectElement).register("member",c.MemberElement).register("ref",c.RefElement).register("link",c.LinkElement),this.detect(r,c.NullElement,!1).detect(o,c.StringElement,!1).detect(s,c.NumberElement,!1).detect(i,c.BooleanElement,!1).detect(Array.isArray,c.ArrayElement,!1).detect(a,c.ObjectElement,!1),this}register(e,t){return this._elements=void 0,this.elementMap[e]=t,this}unregister(e){return this._elements=void 0,delete this.elementMap[e],this}detect(e,t,n){return void 0===n||n?this.elementDetection.unshift([e,t]):this.elementDetection.push([e,t]),this}toElement(t){if(t instanceof this.Element)return t;let n;for(let e=0;e{var t=e[0].toUpperCase()+e.substr(1);this._elements[t]=this.elementMap[e]})),this._elements}get serialiser(){return new l(this)}}l.prototype.Namespace=u,e.exports=u},10866:(e,t,n)=>{const r=n(6048),o=n(92340);class s extends o{map(t,n){return this.elements.map(e=>t.bind(n)(e.value,e.key,e))}filter(t,n){return new s(this.elements.filter(e=>t.bind(n)(e.value,e.key,e)))}reject(e,t){return this.filter(r(e.bind(t)))}forEach(n,r){return this.elements.forEach((e,t)=>{n.bind(r)(e.value,e.key,e,t)})}keys(){return this.map((e,t)=>t.toValue())}values(){return this.map(e=>e.toValue())}}e.exports=s},86804:(e,t,n)=>{const r=n(10316),o=n(41067),s=n(71167),i=n(40239),a=n(12242),l=n(6233),c=n(87726),u=n(61045),p=n(86303),h=n(14540),d=n(92340),f=n(10866),m=n(55973);function g(e){return e instanceof r?e:"string"==typeof e?new s(e):"number"==typeof e?new i(e):"boolean"==typeof e?new a(e):null===e?new o:Array.isArray(e)?new l(e.map(g)):"object"==typeof e?new u(e):e}r.prototype.ObjectElement=u,r.prototype.RefElement=h,r.prototype.MemberElement=c,r.prototype.refract=g,d.prototype.refract=g,e.exports={Element:r,NullElement:o,StringElement:s,NumberElement:i,BooleanElement:a,ArrayElement:l,MemberElement:c,ObjectElement:u,LinkElement:p,RefElement:h,refract:g,ArraySlice:d,ObjectSlice:f,KeyValuePair:m}},86303:(e,t,n)=>{n=n(10316);e.exports=class extends n{constructor(e,t,n){super(e||[],t,n),this.element="link"}get relation(){return this.attributes.get("relation")}set relation(e){this.attributes.set("relation",e)}get href(){return this.attributes.get("href")}set href(e){this.attributes.set("href",e)}}},14540:(e,t,n)=>{n=n(10316);e.exports=class extends n{constructor(e,t,n){super(e||[],t,n),this.element="ref",this.path||(this.path="element")}get path(){return this.attributes.get("path")}set path(e){this.attributes.set("path",e)}}},34035:(e,t,n)=>{var r=n(3110),o=n(86804);t.g$=r,t.KeyValuePair=n(55973),t.G6=o.ArraySlice,t.ot=o.ObjectSlice,t.Hg=o.Element,t.Om=o.StringElement,t.kT=o.NumberElement,t.bd=o.BooleanElement,t.Os=o.NullElement,t.wE=o.ArrayElement,t.Sh=o.ObjectElement,t.Pr=o.MemberElement,t.sI=o.RefElement,t.Ft=o.LinkElement,t.e=o.refract,n(85105),n(75147)},6233:(e,t,n)=>{const r=n(6048),o=n(10316),s=n(92340);class i extends o{constructor(e,t,n){super(e||[],t,n),this.element="array"}primitive(){return"array"}get(e){return this.content[e]}getValue(e){const t=this.get(e);if(t)return t.toValue()}getIndex(e){return this.content[e]}set(e,t){return this.content[e]=this.refract(t),this}remove(e){e=this.content.splice(e,1);return e.length?e[0]:null}map(e,t){return this.content.map(e,t)}flatMap(e,t){return this.map(e,t).reduce((e,t)=>e.concat(t),[])}compactMap(t,n){const r=[];return this.forEach(e=>{e=t.bind(n)(e);e&&r.push(e)}),r}filter(e,t){return new s(this.content.filter(e,t))}reject(e,t){return this.filter(r(e),t)}reduce(t,e){let n,r;r=void 0!==e?(n=0,this.refract(e)):(n=1,"object"===this.primitive()?this.first.value:this.first);for(let e=n;e{n.bind(r)(e,this.refract(t))})}shift(){return this.content.shift()}unshift(e){this.content.unshift(this.refract(e))}push(e){return this.content.push(this.refract(e)),this}add(e){this.push(e)}findElements(r,e){const t=e||{},o=!!t.recursive,s=void 0===t.results?[]:t.results;return this.forEach((e,t,n)=>{o&&void 0!==e.findElements&&e.findElements(r,{results:s,recursive:o}),r(e,t,n)&&s.push(e)}),s}find(e){return new s(this.findElements(e,{recursive:!0}))}findByElement(t){return this.find(e=>e.element===t)}findByClass(t){return this.find(e=>e.classes.includes(t))}getById(t){return this.find(e=>e.id.toValue()===t).first}includes(t){return this.content.some(e=>e.equals(t))}contains(e){return this.includes(e)}empty(){return new this.constructor([])}"fantasy-land/empty"(){return this.empty()}concat(e){return new this.constructor(this.content.concat(e.content))}"fantasy-land/concat"(e){return this.concat(e)}"fantasy-land/map"(e){return new this.constructor(this.map(e))}"fantasy-land/chain"(t){return this.map(e=>t(e),this).reduce((e,t)=>e.concat(t),this.empty())}"fantasy-land/filter"(e){return new this.constructor(this.content.filter(e))}"fantasy-land/reduce"(e,t){return this.content.reduce(e,t)}get length(){return this.content.length}get isEmpty(){return 0===this.content.length}get first(){return this.getIndex(0)}get second(){return this.getIndex(1)}get last(){return this.getIndex(this.length-1)}}i["fantasy-land/empty"]=i.empty=function(){return new this},"undefined"!=typeof Symbol&&(i.prototype[Symbol.iterator]=function(){return this.content[Symbol.iterator]()}),e.exports=i},12242:(e,t,n)=>{n=n(10316);e.exports=class extends n{constructor(e,t,n){super(e,t,n),this.element="boolean"}primitive(){return"boolean"}}},10316:(e,t,n)=>{const r=n(2404),a=n(55973),l=n(92340);e.exports=class o{constructor(e,t,n){t&&(this.meta=t),n&&(this.attributes=n),this.content=e}freeze(){Object.isFrozen(this)||(this._meta&&(this.meta.parent=this).meta.freeze(),this._attributes&&(this.attributes.parent=this).attributes.freeze(),this.children.forEach(e=>{e.parent=this,e.freeze()},this),this.content&&Array.isArray(this.content)&&Object.freeze(this.content),Object.freeze(this))}primitive(){}clone(){const e=new this.constructor;return e.element=this.element,this.meta.length&&(e._meta=this.meta.clone()),this.attributes.length&&(e._attributes=this.attributes.clone()),this.content?this.content.clone?e.content=this.content.clone():Array.isArray(this.content)?e.content=this.content.map(e=>e.clone()):e.content=this.content:e.content=this.content,e}toValue(){return this.content instanceof o?this.content.toValue():this.content instanceof a?{key:this.content.key.toValue(),value:this.content.value?this.content.value.toValue():void 0}:this.content&&this.content.map?this.content.map(e=>e.toValue(),this):this.content}toRef(e){if(""===this.id.toValue())throw Error("Cannot create reference to an element that does not contain an ID");const t=new this.RefElement(this.id.toValue());return e&&(t.path=e),t}findRecursive(...r){if(1(e.push(t),e),i=(e,t)=>{t.element===o&&e.push(t);const n=t.findRecursive(o);return n&&n.reduce(s,e),t.content instanceof a&&(t.content.key&&i(e,t.content.key),t.content.value&&i(e,t.content.value)),e};return this.content&&(this.content.element&&i(e,this.content),Array.isArray(this.content)&&this.content.reduce(i,e)),e=r.isEmpty?e:e.filter(e=>{let t=e.parents.map(e=>e.element);for(const e in r){var n=r[e];if(-1===(n=t.indexOf(n)))return!1;t=t.splice(0,n)}return!0})}set(e){return this.content=e,this}equals(e){return r(this.toValue(),e)}getMetaProperty(e,t){if(!this.meta.hasKey(e)){if(this.isFrozen){const e=this.refract(t);return e.freeze(),e}this.meta.set(e,t)}return this.meta.get(e)}setMetaProperty(e,t){this.meta.set(e,t)}get element(){return this._storedElement||"element"}set element(e){this._storedElement=e}get content(){return this._content}set content(t){if(t instanceof o)this._content=t;else if(t instanceof l)this.content=t.elements;else if("string"==typeof t||"number"==typeof t||"boolean"==typeof t||"null"===t||null==t)this._content=t;else if(t instanceof a)this._content=t;else if(Array.isArray(t))this._content=t.map(this.refract);else{if("object"!=typeof t)throw new Error("Cannot set content to given value");this._content=Object.keys(t).map(e=>new this.MemberElement(e,t[e]))}}get meta(){if(!this._meta){if(this.isFrozen){const e=new this.ObjectElement;return e.freeze(),e}this._meta=new this.ObjectElement}return this._meta}set meta(e){e instanceof this.ObjectElement?this._meta=e:this.meta.set(e||{})}get attributes(){if(!this._attributes){if(this.isFrozen){const e=new this.ObjectElement;return e.freeze(),e}this._attributes=new this.ObjectElement}return this._attributes}set attributes(e){e instanceof this.ObjectElement?this._attributes=e:this.attributes.set(e||{})}get id(){return this.getMetaProperty("id","")}set id(e){this.setMetaProperty("id",e)}get classes(){return this.getMetaProperty("classes",[])}set classes(e){this.setMetaProperty("classes",e)}get title(){return this.getMetaProperty("title","")}set title(e){this.setMetaProperty("title",e)}get description(){return this.getMetaProperty("description","")}set description(e){this.setMetaProperty("description",e)}get links(){return this.getMetaProperty("links",[])}set links(e){this.setMetaProperty("links",e)}get isFrozen(){return Object.isFrozen(this)}get parents(){let e=this.parent;const t=new l;for(;e;)t.push(e),e=e.parent;return t}get children(){if(Array.isArray(this.content))return new l(this.content);if(this.content instanceof a){const e=new l([this.content.key]);return this.content.value&&e.push(this.content.value),e}return this.content instanceof o?new l([this.content]):new l}get recursiveChildren(){const t=new l;return this.children.forEach(e=>{t.push(e),e.recursiveChildren.forEach(e=>{t.push(e)})}),t}}},87726:(e,t,n)=>{const o=n(55973),r=n(10316);e.exports=class extends r{constructor(e,t,n,r){super(new o,n,r),this.element="member",this.key=e,this.value=t}get key(){return this.content.key}set key(e){this.content.key=this.refract(e)}get value(){return this.content.value}set value(e){this.content.value=this.refract(e)}}},41067:(e,t,n)=>{n=n(10316);e.exports=class extends n{constructor(e,t,n){super(e||null,t,n),this.element="null"}primitive(){return"null"}set(){return new Error("Cannot set the value of null")}}},40239:(e,t,n)=>{n=n(10316);e.exports=class extends n{constructor(e,t,n){super(e,t,n),this.element="number"}primitive(){return"number"}}},61045:(e,t,n)=>{const r=n(6048),o=n(23805),s=n(6233),i=n(87726),a=n(10866);e.exports=class extends s{constructor(e,t,n){super(e||[],t,n),this.element="object"}primitive(){return"object"}toValue(){return this.content.reduce((e,t)=>(e[t.key.toValue()]=t.value?t.value.toValue():void 0,e),{})}get(e){e=this.getMember(e);if(e)return e.value}getMember(t){if(void 0!==t)return this.content.find(e=>e.key.toValue()===t)}remove(t){let n=null;return this.content=this.content.filter(e=>e.key.toValue()!==t||(n=e,!1)),n}getKey(e){e=this.getMember(e);if(e)return e.key}set(t,e){if(o(t))return Object.keys(t).forEach(e=>{this.set(e,t[e])}),this;const n=t,r=this.getMember(n);return r?r.value=e:this.content.push(new i(n,e)),this}keys(){return this.content.map(e=>e.key.toValue())}values(){return this.content.map(e=>e.value.toValue())}hasKey(t){return this.content.some(e=>e.key.equals(t))}items(){return this.content.map(e=>[e.key.toValue(),e.value.toValue()])}map(t,n){return this.content.map(e=>t.bind(n)(e.value,e.key,e))}compactMap(r,o){const s=[];return this.forEach((e,t,n)=>{e=r.bind(o)(e,t,n);e&&s.push(e)}),s}filter(e,t){return new a(this.content).filter(e,t)}reject(e,t){return this.filter(r(e),t)}forEach(t,n){return this.content.forEach(e=>t.bind(n)(e.value,e.key,e))}}},71167:(e,t,n)=>{n=n(10316);e.exports=class extends n{constructor(e,t,n){super(e,t,n),this.element="string"}primitive(){return"string"}get length(){return this.content.length}}},75147:(e,t,n)=>{n=n(85105);e.exports=class extends n{serialise(t){if(!(t instanceof this.namespace.elements.Element))throw new TypeError(`Given element \`${t}\` is not an Element instance`);let n;t._attributes&&t.attributes.get("variable")&&(n=t.attributes.get("variable"));const r={element:t.element};t._meta&&0{e.content&&e.content.element&&e.content.attributes.remove("typeAttributes")}),e.content&&0!==n.length&&o.unshift(e.content),(o=o.map(e=>e instanceof this.namespace.elements.Array?[e]:new this.namespace.elements.Array([e.content]))).length&&t.set("samples",o),0{const t=e.clone();return t.attributes.remove("typeAttributes"),this.serialise(t)})}if(e.content){const n=e.content.clone();return n.attributes.remove("typeAttributes"),[this.serialise(n)]}return[]}deserialise(t){if("string"==typeof t)return new this.namespace.elements.String(t);if("number"==typeof t)return new this.namespace.elements.Number(t);if("boolean"==typeof t)return new this.namespace.elements.Boolean(t);if(null===t)return new this.namespace.elements.Null;if(Array.isArray(t))return new this.namespace.elements.Array(t.map(this.deserialise,this));const r=this.namespace.getElementClass(t.element),o=new r,s=(o.element!==t.element&&(o.element=t.element),t.meta&&this.deserialiseObject(t.meta,o.meta),t.attributes&&this.deserialiseObject(t.attributes,o.attributes),this.deserialiseContent(t.content));if(void 0===s&&null!==o.content||(o.content=s),"enum"===o.element){o.content&&o.attributes.set("enumerations",o.content);let n=o.attributes.get("samples");if(o.attributes.remove("samples"),n){const s=n;n=new this.namespace.elements.Array,s.forEach(e=>{e.forEach(e=>{const t=new r(e);t.element=o.element,n.push(t)})});t=n.shift();o.content=t?t.content:void 0,o.attributes.set("samples",n)}else o.content=void 0;let e=o.attributes.get("default");if(e&&0this.shouldRefract(e)||"default"===t?this.serialise(e):"array"===e.element||"object"===e.element||"enum"===e.element?e.children.map(e=>this.serialise(e)):e.toValue()):"object"===e.element?(e.content||[]).map(this.serialise,this):e.toValue()}serialiseEnum(e){return e.children.map(e=>this.serialise(e))}serialiseObject(e){const n={};return e.forEach((e,t)=>{e&&(t=t.toValue(),n[t]=this.convertKeyToRefract(t,e))}),n}deserialiseObject(t,n){Object.keys(t).forEach(e=>{n.set(e,this.deserialise(t[e]))})}}},85105:e=>{e.exports=class{constructor(e){this.namespace=e||new this.Namespace}serialise(e){if(!(e instanceof this.namespace.elements.Element))throw new TypeError(`Given element \`${e}\` is not an Element instance`);const t={element:e.element};e._meta&&0{e&&(n[t.toValue()]=this.serialise(e))}),0!==Object.keys(n).length)return n}deserialiseObject(t,n){Object.keys(t).forEach(e=>{n.set(e,this.deserialise(t[e]))})}}},58859:(n,r,w)=>{var e="function"==typeof Map&&Map.prototype,t=Object.getOwnPropertyDescriptor&&e?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,E=e&&t&&"function"==typeof t.get?t.get:null,S=e&&Map.prototype.forEach,t="function"==typeof Set&&Set.prototype,e=Object.getOwnPropertyDescriptor&&t?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,x=t&&e&&"function"==typeof e.get?e.get:null,_=t&&Set.prototype.forEach,k="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,A="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,O="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,X=Boolean.prototype.valueOf,s=Object.prototype.toString,Q=Function.prototype.toString,Z=String.prototype.match,C=String.prototype.slice,j=String.prototype.replace,i=String.prototype.toUpperCase,P=String.prototype.toLowerCase,u=RegExp.prototype.test,N=Array.prototype.concat,I=Array.prototype.join,ee=Array.prototype.slice,o=Math.floor,T="function"==typeof BigInt?BigInt.prototype.valueOf:null,p=Object.getOwnPropertySymbols,R="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,M="function"==typeof Symbol&&"object"==typeof Symbol.iterator,D="function"==typeof Symbol&&Symbol.toStringTag&&(Symbol.toStringTag,1)?Symbol.toStringTag:null,F=Object.prototype.propertyIsEnumerable,B=("function"==typeof Reflect?Reflect:Object).getPrototypeOf||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function L(e,t){if(e===1/0||e===-1/0||e!=e||e&&-1e3 0, or `null`');if(K(i,"numericSeparator")&&"boolean"!=typeof i.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var t=i.numericSeparator;if(void 0===n)return"undefined";if(null===n)return"null";if("boolean"==typeof n)return n?"true":"false";if("string"==typeof n)return function e(t,n){{var r;if(t.length>n.maxStringLength)return r=t.length-n.maxStringLength,r="... "+r+" more character"+(1"}if(U(n)){if(0===n.length)return"[]";var b=Y(n,m);return a&&!function(e){for(var t=0;t "+m(e,n))}),oe("Map",E.call(n),u,a)):function(e){if(x&&e&&"object"==typeof e)try{x.call(e);try{E.call(e)}catch(e){return 1}return e instanceof Set}catch(e){}}(n)?(p=[],_&&_.call(n,function(e){p.push(m(e,n))}),oe("Set",x.call(n),p,a)):function(e){if(k&&e&&"object"==typeof e)try{k.call(e,k);try{A.call(e,A)}catch(e){return 1}return e instanceof WeakMap}catch(e){}}(n)?H("WeakMap"):function(e){if(A&&e&&"object"==typeof e)try{A.call(e,A);try{k.call(e,k)}catch(e){return 1}return e instanceof WeakSet}catch(e){}}(n)?H("WeakSet"):function(e){if(O&&e&&"object"==typeof e)try{return O.call(e),1}catch(e){}}(n)?H("WeakRef"):"[object Number]"!==W(h=n)||D&&"object"==typeof h&&D in h?function(e){if(e&&"object"==typeof e&&T)try{return T.call(e),1}catch(e){}}(n)?J(m(T.call(n))):"[object Boolean]"!==W(t=n)||D&&"object"==typeof t&&D in t?"[object String]"!==W(e=n)||D&&"object"==typeof e&&D in e?"undefined"!=typeof window&&n===window?"{ [object Window] }":n===w.g?"{ [object globalThis] }":("[object Date]"!==W(t=n)||D&&"object"==typeof t&&D in t)&&!V(n)?(e=Y(n,m),t=B?B(n)===Object.prototype:n instanceof Object||n.constructor===Object,d=n instanceof Object?"":"null prototype",f=!t&&D&&Object(n)===n&&D in n?C.call(W(n),8,-1):d?"Object":"",t=(!t&&"function"==typeof n.constructor&&n.constructor.name?n.constructor.name+" ":"")+(f||d?"["+I.call(N.call([],f||[],d||[]),": ")+"] ":""),0===e.length?t+"{}":a?t+"{"+G(e,a)+"}":t+"{ "+I.call(e,", ")+" }"):String(n):J(m(String(n))):J(X.call(n)):J(m(Number(n)))};var a=Object.prototype.hasOwnProperty||function(e){return e in this};function K(e,t){return a.call(e,t)}function W(e){return s.call(e)}function ne(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0,r=e.length;n{var n,r,e=e.exports={};function o(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function i(t){if(n===setTimeout)return setTimeout(t,0);if((n===o||!n)&&setTimeout)return(n=setTimeout)(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}try{n="function"==typeof setTimeout?setTimeout:o}catch(e){n=o}try{r="function"==typeof clearTimeout?clearTimeout:s}catch(e){r=s}var a,l=[],c=!1,u=-1;function p(){c&&a&&(c=!1,a.length?l=a.concat(l):u=-1,l.length&&h())}function h(){if(!c){var e=i(p);c=!0;for(var t=l.length;t;){for(a=l,l=[];++u{"use strict";var i=n(6925);function r(){}function o(){}o.resetWarningCache=r,e.exports=function(){function e(e,t,n,r,o,s){if(s!==i)throw(s=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types")).name="Invariant Violation",s}function t(){return e}var n={array:e.isRequired=e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:o,resetWarningCache:r};return n.PropTypes=n}},5556:(e,t,n)=>{e.exports=n(2694)()},6925:e=>{"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},74765:e=>{"use strict";var t=String.prototype.replace,n=/%20/g;e.exports={default:"RFC3986",formatters:{RFC1738:function(e){return t.call(e,n,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:"RFC3986"}},55373:(e,t,n)=>{"use strict";var r=n(98636),o=n(62642),n=n(74765);e.exports={formats:n,parse:o,stringify:r}},62642:(e,t,n)=>{"use strict";function y(e,t){return e&&"string"==typeof e&&t.comma&&-1{"use strict";function I(e,t){r.apply(e,D(t)?t:[t])}function T(e,t,n,r,o,s,i,a,l,c,u,p,h,d,f,m){for(var g=e,y=m,v=0,b=!1;void 0!==(y=y.get(L))&&!b;){var w=y.get(e);if(v+=1,void 0!==w){if(w===v)throw new RangeError("Cyclic object value");b=!0}void 0===y.get(L)&&(v=0)}if("function"==typeof a?g=a(t,g):g instanceof Date?g=u(g):"comma"===n&&D(g)&&(g=M.maybeMap(g,function(e){return e instanceof Date?u(e):e})),null===g){if(o)return i&&!d?i(t,B.encoder,f,"key",p):t;g=""}if("string"==typeof(E=g)||"number"==typeof E||"boolean"==typeof E||"symbol"==typeof E||"bigint"==typeof E||M.isBuffer(g)){if(i){var E=d?t:i(t,B.encoder,f,"key",p);if("comma"===n&&d){for(var S=F.call(String(g),","),x="",_=0;_{"use strict";function a(e,t){for(var n=t&&t.plainObjects?Object.create(null):{},r=0;r>6]+u[128|63&l]:l<55296||57344<=l?i+=u[224|l>>12]+u[128|l>>6&63]+u[128|63&l]:(a+=1,l=65536+((1023&l)<<10|1023&s.charCodeAt(a)),i+=u[240|l>>18]+u[128|l>>12&63]+u[128|l>>6&63]+u[128|63&l])}return i},isBuffer:function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},maybeMap:function(e,t){if(m(e)){for(var n=[],r=0;r{"use strict";var s=Object.prototype.hasOwnProperty;function i(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(e){return null}}function a(e){try{return encodeURIComponent(e)}catch(e){return null}}t.stringify=function(e,t){var n,r,o=[];for(r in"string"!=typeof(t=t||"")&&(t="?"),e)if(s.call(e,r)){if((n=e[r])||null!=n&&!isNaN(n)||(n=""),r=a(r),n=a(n),null===r||null===n)continue;o.push(r+"="+n)}return o.length?t+o.join("&"):""},t.parse=function(e){for(var t=/([^=?#&]+)=?([^&]*)/g,n={};o=t.exec(e);){var r=i(o[1]),o=i(o[2]);null===r||null===o||r in n||(n[r]=o)}return n}},41859:(e,t,n)=>{const i=n(27096),a=n(78004),l=i.types;e.exports=class r{constructor(e,t){if(this._setDefaults(e),e instanceof RegExp)this.ignoreCase=e.ignoreCase,this.multiline=e.multiline,e=e.source;else{if("string"!=typeof e)throw new Error("Expected a regexp or string");this.ignoreCase=t&&-1!==t.indexOf("i"),this.multiline=t&&-1!==t.indexOf("m")}this.tokens=i(e)}_setDefaults(e){this.max=null!=e.max?e.max:null!=r.prototype.max?r.prototype.max:100,this.defaultRange=e.defaultRange||this.defaultRange.clone(),e.randInt&&(this.randInt=e.randInt)}gen(){return this._gen(this.tokens,[])}_gen(e,t){var n,r,o,s,i;switch(e.type){case l.ROOT:case l.GROUP:if(e.followedBy||e.notFollowedBy)return"";for(e.remember&&void 0===e.groupNumber&&(e.groupNumber=t.push(null)-1),r="",s=0,i=(n=e.options?this._randSelect(e.options):e.stack).length;s{"use strict";var o=n(65606),s=n(92861).Buffer,i=n.g.crypto||n.g.msCrypto;i&&i.getRandomValues?e.exports=function(e,t){if(4294967295{"use strict";function s(e){return(s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.CopyToClipboard=void 0;var l=r(n(96540)),c=r(n(17965)),u=["text","onCopy","options","children"];function r(e){return e&&e.__esModule?e:{default:e}}function o(t,e){var n,r=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)),r}function p(t){for(var e=1;e{"use strict";n=n(25264).CopyToClipboard;n.CopyToClipboard=n,e.exports=n},81214:(e,t,n)=>{"use strict";function a(e){return(a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.DebounceInput=void 0;var l=r(n(96540)),c=r(n(20181)),u=["element","onChange","value","minLength","debounceTimeout","forceNotifyByEnter","forceNotifyOnBlur","onKeyDown","onBlur","inputRef"];function r(e){return e&&e.__esModule?e:{default:e}}function o(t,e){var n,r=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)),r}function p(t){for(var e=1;e=r?o.notify(t):n.length>e.length&&o.notify(p(p({},t),{},{target:p(p({},t.target),{},{value:""})}))})}),g(f(o),"onKeyDown",function(e){"Enter"===e.key&&o.forceNotify(e);var t=o.props.onKeyDown;t&&(e.persist(),t(e))}),g(f(o),"onBlur",function(e){o.forceNotify(e);var t=o.props.onBlur;t&&(e.persist(),t(e))}),g(f(o),"createNotifier",function(e){var t;e<0?o.notify=function(){return null}:0===e?o.notify=o.doNotify:(t=(0,c.default)(function(e){o.isDebouncing=!1,o.doNotify(e)},e),o.notify=function(e){o.isDebouncing=!0,t(e)},o.flush=function(){return t.flush()},o.cancel=function(){o.isDebouncing=!1,t.cancel()})}),g(f(o),"doNotify",function(){o.props.onChange.apply(void 0,arguments)}),g(f(o),"forceNotify",function(e){var t,n=o.props.debounceTimeout;!o.isDebouncing&&0=t?o.doNotify(e):o.doNotify(p(p({},e),{},{target:p(p({},e.target),{},{value:n})})))}),o.isDebouncing=!1,o.state={value:void 0===e.value||null===e.value?"":e.value};e=o.props.debounceTimeout;return o.createNotifier(e),o}return t=i,(e=[{key:"componentDidUpdate",value:function(e){var t,n,r,o;this.isDebouncing||(t=(n=this.props).value,n=n.debounceTimeout,r=e.debounceTimeout,e=e.value,o=this.state.value,void 0!==t&&e!==t&&o!==t&&this.setState({value:t}),n!==r&&this.createNotifier(n))}},{key:"componentWillUnmount",value:function(){this.flush&&this.flush()}},{key:"render",value:function(){var e=this.props,t=e.element,n=(e.onChange,e.value,e.minLength,e.debounceTimeout,e.forceNotifyByEnter),r=e.forceNotifyOnBlur,o=e.onKeyDown,s=e.onBlur,i=e.inputRef,e=function(e,t){if(null==e)return{};var n,r=function(e,t){if(null==e)return{};for(var n,r={},o=Object.keys(e),s=0;s{"use strict";n=n(81214).DebounceInput;n.DebounceInput=n,e.exports=n},22551:(l,f,e)=>{"use strict";var O=e(96540),n=e(69982);function q(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n