Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inclusion of AWS type validation #239

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 77 additions & 6 deletions src/cloud_radar/cf/unit/_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,7 @@ def validate_parameter_constraints(
against
parameter_value (str): The supplied parameter value being validated
"""

if parameter_definition["Type"] == "String":
validate_string_parameter_constraints(
parameter_name, parameter_definition, parameter_value
Expand All @@ -417,14 +418,84 @@ def validate_parameter_constraints(
validate_number_parameter_constraints(
parameter_name, parameter_definition, parameter_value
)
elif parameter_definition["Type"] == "List<Number>":
# The docs are not as clear here but I think it will be
# the same as CommaDelimitedList - run the number parameter
# constraints for each item in the list
elif parameter_definition["Type"].startswith("AWS::"):
validate_aws_parameter_constraints(
parameter_name, parameter_definition["Type"], parameter_value
)
elif parameter_definition["Type"].startswith("List<"):
# All list types runs the single value validation for all items
trimmed_type = parameter_definition["Type"][5:-1]

# There are a couple though that are not supported
if trimmed_type == "AWS::EC2::KeyPair::KeyName" or trimmed_type == "String":
# this is a type that isn't valid as a list, but is
# as a single item
raise ValueError(f"Type {trimmed_type} is not valid in a List<>")

# Iterate over each item and call this method again with an
# updated definition for the non-list type
updated_defintion = parameter_definition.copy()
updated_defintion["Type"] = trimmed_type

for part in parameter_value.split(","):
validate_number_parameter_constraints(
parameter_name, parameter_definition, part.strip()
validate_parameter_constraints(
parameter_name, updated_defintion, part.strip()
)


def validate_aws_parameter_constraints(
parameter_name: str, parameter_type: str, parameter_value: str
):
"""
Validate that the parameter value matches any constraints
that are applicable for an AWS type parameter

This method will raise a ValueError if any validation constraints
are not met.
Args:
parameter_name (str): The name of the parameter being validated
parameter_type (str): The AWS type of the parameter being validated
against
parameter_value (str): The supplied parameter value being validated
"""

parameter_type_regexes = {
# Reference for this was
# https://gist.github.com/rams3sh/4858d5150acba5383dd697fda54dda2c
"AWS::EC2::AvailabilityZone::Name": (
"^(af|ap|ca|eu|me|sa|us)-(central|north|(north(?:east|west))|"
"south|south(?:east|west)|east|west)-[0-9]+[a-z]{1}$"
),
# Reference for the next few are
# https://blog.skeddly.com/2016/01/long-ec2-instance-ids-are-fully-supported.html
"AWS::EC2::Image::Id": "^ami-[a-f0-9]{8}([a-f0-9]{9})?$",
"AWS::EC2::Instance::Id": "^i-[a-f0-9]{8}([a-f0-9]{9})?$",
"AWS::EC2::SecurityGroup::Id": "^sg-[a-f0-9]{8}([a-f0-9]{9})?$",
"AWS::EC2::Subnet::Id": "^subnet-[a-f0-9]{8}([a-f0-9]{9})?$",
"AWS::EC2::VPC::Id": "^vpc-[a-f0-9]{8}([a-f0-9]{9})?$",
"AWS::EC2::Volume::Id": "^vol-[a-f0-9]{8}([a-f0-9]{9})?$",
# Reference for this was
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-groupname
"AWS::EC2::SecurityGroup::GroupName": r"^[a-zA-Z0-9 ._\-:\/()#,@\[\]+=&;{}!$*]{1,255}$",
# Bit of a guess this one, not sure what the minimum bound should be
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-hostedzoneid
"AWS::Route53::HostedZone::Id": "^[A-Z0-9]{,32}$",
# All the docs say for this type is up to 255 ascii characters
"AWS::EC2::KeyPair::KeyName": "^[ -~]{1,255}$",
}
param_regex = parameter_type_regexes.get(parameter_type)

if param_regex is None:
# If a regex is defined, we know the regex to validate the parameter
raise KeyError(f"Unsupported parameter type {parameter_type}")

if not re.match(param_regex, parameter_value):
raise ValueError(
(
f"Value {parameter_value} does not match the expected pattern "
f"for parameter {parameter_name} and type {parameter_type}"
)
)


def validate_number_parameter_constraints(
Expand Down
181 changes: 181 additions & 0 deletions tests/test_cf/test_unit/test_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,187 @@ def test_set_params_list_number_min_max():
template.set_parameters({"ASGCapacity": "2, 5, 11"})


@pytest.mark.parametrize(
"type,valid_input,invalid_input,fail_message_value,fail_message_type",
[
(
"AWS::EC2::AvailabilityZone::Name",
"us-east-1a",
"xx-west-1c",
"xx-west-1c",
"AWS::EC2::AvailabilityZone::Name",
),
(
"AWS::EC2::Image::Id",
"ami-0ff8a91507f77f867",
"mygreatimage",
"mygreatimage",
"AWS::EC2::Image::Id",
),
(
"AWS::EC2::Instance::Id",
"i-1e731a32",
"ke-1e731a32",
"ke-1e731a32",
"AWS::EC2::Instance::Id",
),
(
"AWS::EC2::KeyPair::KeyName",
"my-nv-keypair",
"t" * 256,
"t" * 256,
"AWS::EC2::KeyPair::KeyName",
),
(
"AWS::EC2::SecurityGroup::GroupName",
"my-sg-abc",
"'sg",
"'sg",
"AWS::EC2::SecurityGroup::GroupName",
),
(
"AWS::EC2::SecurityGroup::Id",
"sg-a123fd85",
"ke-1e731a32",
"ke-1e731a32",
"AWS::EC2::SecurityGroup::Id",
),
(
"AWS::EC2::Subnet::Id",
"subnet-123a351e",
"sunbet-123a351e",
"sunbet-123a351e",
"AWS::EC2::Subnet::Id",
),
(
"AWS::EC2::Volume::Id",
"vol-3cdd3f56",
"vl-3cdd3f56",
"vl-3cdd3f56",
"AWS::EC2::Volume::Id",
),
(
"AWS::EC2::Volume::Id",
"vol-3cdd3f56ae231cef5",
"vol-3cdd3f56ae231cef5a",
"vol-3cdd3f56ae231cef5a",
"AWS::EC2::Volume::Id",
),
(
"AWS::EC2::VPC::Id",
"vpc-a123baa3",
"vpc-a123-baa3",
"vpc-a123-baa3",
"AWS::EC2::VPC::Id",
),
(
"AWS::Route53::HostedZone::Id",
"Z23YXV4OVPL04A",
"Z23Y-XV4O-VPL04A",
"Z23Y-XV4O-VPL04A",
"AWS::Route53::HostedZone::Id",
),
(
"List<AWS::EC2::AvailabilityZone::Name>",
"eu-west-1a, us-east-1b",
"eu-west-1a, xx-west-1b",
"xx-west-1b",
"AWS::EC2::AvailabilityZone::Name",
),
(
"List<AWS::EC2::Image::Id>",
"ami-0ff8a91507f77f867, ami-0a584ac55a7631c0c, ami-07d1ddc0a19021abb",
"ami-0ff8a91507f77f867, ami-0a584ac55a7631c0c, mygreatimage",
"mygreatimage",
"AWS::EC2::Image::Id",
),
(
"List<AWS::EC2::Instance::Id>",
"i-1e731a32, i-1e731a34, i-1e731a34213424fde, i-1234567890abcdef0",
"i-1e731a32,i-1e731a34213424fdea",
"i-1e731a34213424fdea",
"AWS::EC2::Instance::Id",
),
(
"List<AWS::EC2::SecurityGroup::GroupName>",
"my-sg-abc, my-sg-def, MySecurityGroup",
"my-sg-abc, my-sg-def'",
"my-sg-def'",
"AWS::EC2::SecurityGroup::GroupName",
),
(
"List<AWS::EC2::SecurityGroup::Id>",
"sg-a123fd85, sg-b456fd85, sg-903004f8",
"sg-a123fd85, sg-b456fd85jgkfmd",
"sg-b456fd85jgkfmd",
"AWS::EC2::SecurityGroup::Id",
),
(
"List<AWS::EC2::Subnet::Id>",
"subnet-123a351e, subnet-456b351e, subnet-5f46ec3b, subnet-9d4a7b6c",
"subnet-123a351e, subnet-z456b351e",
"subnet-z456b351e",
"AWS::EC2::Subnet::Id",
),
(
"List<AWS::EC2::Volume::Id>",
"vol-3cdd3f56, vol-4cdd3f56, vol-049df61146c4d7901",
"vol-3cdd3f56, vol-4cdd3f56, vl-3cdd3f56",
"vl-3cdd3f56",
"AWS::EC2::Volume::Id",
),
(
"List<AWS::EC2::VPC::Id>",
"vpc-a123baa3, vpc-b456baa3, vpc-010e1791024eb0af9",
"vpc-a123baa3, vapc-b456baa3",
"vapc-b456baa3",
"AWS::EC2::VPC::Id",
),
(
"List<AWS::Route53::HostedZone::Id>",
"Z23YXV4OVPL04A, Z23YXV4OVPL04B, Z7HUB22UULQXV",
"Z23YXV4OVPL04B, Z23Y-XV4O-VPL04A",
"Z23Y-XV4O-VPL04A",
"AWS::Route53::HostedZone::Id",
),
],
)
def test_set_params_aws_type(
type: str,
valid_input: str,
invalid_input: str,
fail_message_value: str,
fail_message_type: str,
):
t = {
"Parameters": {
"TargetAvailabilityZones": {
"Type": type,
"Description": ("The AZ(s) we are deploying to"),
}
}
}
template = Template(t)

# Test that supplying a list of valid AZ values works
template.set_parameters({"TargetAvailabilityZones": valid_input})

actual_value = template.template["Parameters"]["TargetAvailabilityZones"]
assert (
valid_input == actual_value["Value"]
), "Should set the value to what we pass in."

# Test the supplying an invalid AZ is rejected
with pytest.raises(
ValueError,
match=(
"Value " + fail_message_value + " does not match the expected pattern for "
"parameter TargetAvailabilityZones and type " + fail_message_type
),
):
template.set_parameters({"TargetAvailabilityZones": invalid_input})


@pytest.mark.parametrize("t", [{}, {"Metadata": {}}])
def test_metadata(t):
region = "us-east-1"
Expand Down