Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(cloudformation): Fn::Cidr, Fn::GetAZs, Fn::FindInMap and condition functions as on AWS (#1650)
iot-rocket5a3e9457ccc6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a091e979..30c9e7a7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Fixed+- **CloudFormation — `Fn::Cidr`, `Fn::GetAZs`, `Fn::FindInMap` and the condition functions follow AWS** — `Fn::Cidr` answered `10.0.{i}.0/…` whatever block it was given (now the block is split: `192.168.0.0/16, 2, 8` is `192.168.0.0/24,192.168.1.0/24`, measured; IPv6 included), `Fn::GetAZs` answered a fabricated `a/b/c` for any region (now the stack's own zones, and an empty list for another region, measured), `Fn::FindInMap` answered `""` for a missing key and had no `DefaultValue` (now the default when given, otherwise `Template error: Unable to get mapping for M::x::y` before the stack exists, measured), and `Fn::And`/`Fn::Or`/`Fn::Not` in a value position leaked the unresolved call (now a boolean; as an Output value they are refused with `The Value field of every Outputs member must evaluate to a String.`, measured). Contributed by @iot-rocket.### Added- **CloudFormation — `ListImports`, `UpdateTerminationProtection`, `SetStackPolicy`, `GetStackPolicy`, `CancelUpdateStack` and `ContinueUpdateRollback`** — the first four were routed to the service and answered `InvalidAction`, the last two did not exist, so a stack in `UPDATE_ROLLBACK_FAILED` had no way out short of a reset. `ListImports` names the stacks importing an export (a `ValidationError` when none does); termination protection is set on create or later and makes `DeleteStack` refuse with the stack unchanged (`DescribeStacks` reports `EnableTerminationProtection`); a stack policy is stored and returned (it is not enforced); `CancelUpdateStack` stops an `UPDATE_IN_PROGRESS` update before its next resource and rolls it back ("User Initiated"); `ContinueUpdateRollback` retries the deletes that failed the rollback, skips the `ResourcesToSkip` (their status becomes `UPDATE_COMPLETE`, the resource stays) and lands the stack in `UPDATE_ROLLBACK_COMPLETE`. Contributed by @iot-rocket.### Fixeddiff --git a/ministack/services/cloudformation/engine.py b/ministack/services/cloudformation/engine.pyindex 155ebc7f..6e8dd834 100644--- a/ministack/services/cloudformation/engine.py+++ b/ministack/services/cloudformation/engine.py@@ -8,6 +8,8 @@ condition evaluation, intrinsic function resolution, and topological sorting.import base64import copyimport heapq+import ipaddress+import itertoolsimport jsonimport loggingimport os@@ -279,6 +281,7 @@ def validate_template_support(template: dict, conditions: dict) -> None:"Template format error: Unrecognized resource types: ["+ ", ".join(sorted(unrecognized)) + "]")+ _validate_template_statics(template)refs: set[str] = set()_find_dynamic_references(template.get("Resources"), refs)@@ -537,6 +540,70 @@ def _evaluate_conditions(template: dict, params: dict) -> dict:# Intrinsic Function Resolver# ===========================================================================+def _cidr_blocks(ip_block: str, count: int, cidr_bits: int) -> list[str]:+ """``Fn::Cidr``: ``count`` consecutive subnets of ``ip_block`` whose mask is+ ``cidr_bits`` shorter than the address length (``cidrBits`` are subnet+ bits: 8 on an IPv4 /16 gives /24 blocks — measured on AWS:+ ``192.168.0.0/16, 2, 8`` is ``192.168.0.0/24,192.168.1.0/24``)."""+ if not 1 <= count <= 256:+ raise ValueError(+ f"Template error: Fn::Cidr count must be between 1 and 256, got {count}")+ try:+ network = ipaddress.ip_network(ip_block, strict=False)+ except ValueError:+ raise ValueError(f"Template error: Fn::Cidr ipBlock {ip_block!r} is not a CIDR block") from None+ new_prefix = network.max_prefixlen - cidr_bits+ if not network.prefixlen < new_prefix <= network.max_prefixlen:+ raise ValueError(+ f"Template error: Fn::Cidr cannot split {ip_block} into /{new_prefix} blocks")+ subnets = list(itertools.islice(network.subnets(new_prefix=new_prefix), count))+ if len(subnets) < count:+ raise ValueError(+ f"Template error: Fn::Cidr {ip_block} holds only {len(subnets)} /{new_prefix} blocks, "+ f"{count} requested")+ return [str(subnet) for subnet in subnets]+++_CONDITION_FUNCTIONS = ("Fn::And", "Fn::Or", "Fn::Not", "Fn::Equals")+++def _validate_template_statics(template: dict) -> None:+ """The template errors a real account raises before any stack exists and+ that need nothing but the template: a condition function as an Output+ value, and an Fn::FindInMap with literal keys that the Mappings section+ does not hold (both measured)."""+ for out in (template.get("Outputs") or {}).values():+ val = out.get("Value") if isinstance(out, dict) else None+ if isinstance(val, dict) and len(val) == 1 and next(iter(val)) in _CONDITION_FUNCTIONS:+ raise ValueError("Template format error: The Value field of every "+ "Outputs member must evaluate to a String.")+ mappings = template.get("Mappings") or {}++ def walk(node):+ if isinstance(node, dict):+ if len(node) == 1 and "Fn::FindInMap" in node:+ args = node["Fn::FindInMap"]+ if (isinstance(args, list) and len(args) >= 3+ and all(isinstance(a, str) for a in args[:3])+ and not (len(args) > 3 and isinstance(args[3], dict)+ and "DefaultValue" in args[3])):+ name, k1, k2 = args[:3]+ if k1 not in mappings.get(name, {}) or k2 not in mappings.get(name, {}).get(k1, {}):+ raise ValueError(+ f"Template error: Unable to get mapping for {name}::{k1}::{k2}")+ for arg in args if isinstance(args, list) else []:+ walk(arg)+ return+ for v in node.values():+ walk(v)+ elif isinstance(node, list):+ for v in node:+ walk(v)++ for section in ("Resources", "Outputs", "Conditions"):+ walk(template.get(section) or {})++def _unknown_attribute_message(res: dict, logical_id: str, attr: str) -> str:# Verbatim what CloudFormation reports in the stack event that starts the# rollback (measured on a real account against AWS::SQS::Queue).@@ -717,7 +784,17 @@ def _resolve_refs(value, resources, params, conditions, mappings,mappings, stack_name, stack_id)key2 = _resolve_refs(args[2], resources, params, conditions,mappings, stack_name, stack_id)- return mappings.get(str(map_name), {}).get(str(key1), {}).get(str(key2), "")+ top = mappings.get(str(map_name), {})+ if str(key1) in top and str(key2) in top[str(key1)]:+ return top[str(key1)][str(key2)]+ # The optional fourth argument is {"DefaultValue": ...}; without it a+ # missing key is a template error, as on AWS (measured: "Template+ # error: Unable to get mapping for M::x::y").+ if len(args) > 3 and isinstance(args[3], dict) and "DefaultValue" in args[3]:+ return _resolve_refs(args[3]["DefaultValue"], resources, params,+ conditions, mappings, stack_name, stack_id)+ raise ValueError(+ f"Template error: Unable to get mapping for {map_name}::{key1}::{key2}")# --- Fn::ImportValue ---if "Fn::ImportValue" in value:@@ -763,6 +840,11 @@ def _resolve_refs(value, resources, params, conditions, mappings,conditions, mappings, stack_name, stack_id)if not region:region = get_region()+ # The zones the emulator's EC2 DescribeAvailabilityZones reports for+ # the stack's region. For any other region a real account answered an+ # empty list (measured), not a fabricated a/b/c.+ if str(region) != get_region():+ return []return [f"{region}a", f"{region}b", f"{region}c"]# --- Fn::Cidr ---@@ -774,8 +856,7 @@ def _resolve_refs(value, resources, params, conditions, mappings,mappings, stack_name, stack_id))cidr_bits = int(_resolve_refs(args[2], resources, params, conditions,mappings, stack_name, stack_id))- # Simplified CIDR generation- return [f"10.0.{i}.0/{32 - cidr_bits}" for i in range(count)]+ return _cidr_blocks(str(ip_block), count, cidr_bits)# --- Fn::Equals (condition-like in non-condition context) ---if "Fn::Equals" in value:@@ -785,6 +866,23 @@ def _resolve_refs(value, resources, params, conditions, mappings,right = _resolve_refs(args[1], resources, params, conditions,mappings, stack_name, stack_id)return str(left) == str(right)+ for fn in ("Fn::And", "Fn::Or", "Fn::Not"):+ if fn in value:+ # Condition functions belong in Conditions and Fn::If. In a value+ # position they evaluate to a boolean here, like Fn::Equals above,+ # instead of leaking the unresolved call through to the service.+ # What AWS does with one in a property was not measured; as an+ # Output value it is refused up front (see _validate_template_statics).+ operands = [+ _resolve_refs(arg, resources, params, conditions, mappings,+ stack_name, stack_id)+ for arg in value[fn]+ ]+ if fn == "Fn::And":+ return all(bool(o) for o in operands)+ if fn == "Fn::Or":+ return any(bool(o) for o in operands)+ return not bool(operands[0]) if operands else True# --- Condition (reference) ---if "Condition" in value and len(value) == 1:diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.pyindex 4fdb8255..e3c029b9 100644--- a/ministack/services/cloudformation/stacks.py+++ b/ministack/services/cloudformation/stacks.py@@ -135,6 +135,9 @@ def _resolve_stack_outputs(outputs_defs, conditions, resources, param_values,resources, param_values, conditions,mappings, stack_name, stack_id)+ if isinstance(out_value, (bool, list, dict)):+ raise ValueError("Template format error: The Value field of every "+ "Outputs member must evaluate to a String.")output = {"OutputKey": out_name,"OutputValue": str(out_value),diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 4927fc6e..727cce2f 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -1996,6 +1996,92 @@ def test_cfn_fn_sub_literal_escape(cfn, ssm):"and ${Plain} in us-east-1")+def test_cfn_intrinsics_cidr_getazs_findinmap_and_condition_functions(cfn, ssm):+ """Fn::Cidr splits the block it is given (measured: 192.168.0.0/16, 2, 8 is+ 192.168.0.0/24,192.168.1.0/24), Fn::GetAZs answers the stack's zones for+ its own region and an empty list for another (measured), Fn::FindInMap+ takes a DefaultValue and a missing key without one is a template error+ (measured), a condition function as an Output value is refused up front+ (measured) and in a property position evaluates to a boolean."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-intrinsics-{uid}"+ region = cfn.meta.region_name+ template = json.dumps({+ "Mappings": {"M": {"a": {"b": "ok"}}},+ "Resources": {+ "P": {"Type": "AWS::SSM::Parameter", "Properties": {+ "Name": f"/cfn-intrinsics/{uid}", "Type": "String",+ "Value": {"Fn::Join": [",", {"Fn::Cidr": ["192.168.0.0/16", "2", "8"]}]}}},+ "Bools": {"Type": "AWS::SSM::Parameter", "Properties": {+ "Name": f"/cfn-intrinsics/{uid}/bools", "Type": "String",+ "Value": {"Fn::Join": [",", [+ {"Fn::Not": [{"Fn::Equals": ["a", "b"]}]},+ {"Fn::Or": [{"Fn::Equals": ["a", "b"]}, {"Fn::Equals": ["b", "b"]}]},+ {"Fn::And": [{"Fn::Equals": ["a", "a"]}, {"Fn::Equals": ["a", "b"]}]}]]}}},+ },+ "Outputs": {+ "Cidr": {"Value": {"Fn::Join": [",", {"Fn::Cidr": ["10.0.0.0/24", 6, 5]}]}},+ "OwnAzs": {"Value": {"Fn::Join": [",", {"Fn::GetAZs": ""}]}},+ "RefAzs": {"Value": {"Fn::Join": [",", {"Fn::GetAZs": {"Ref": "AWS::Region"}}]}},+ "OtherAzs": {"Value": {"Fn::Join": [",", {"Fn::GetAZs": "eu-north-1"}]}},+ "Map": {"Value": {"Fn::FindInMap": ["M", "a", "b"]}},+ "MapDefault": {"Value": {"Fn::FindInMap": ["M", "x", "y", {"DefaultValue": "dflt"}]}},+ "AndInIf": {"Value": {"Fn::If": ["Yes", "yes", "no"]}},+ },+ "Conditions": {"Yes": {"Fn::And": [{"Fn::Equals": ["a", "a"]}, {"Fn::Not": [{"Fn::Equals": ["a", "b"]}]}]}},+ })+ cfn.create_stack(StackName=stack_name, TemplateBody=template)+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}+ assert outputs["Cidr"] == ",".join(f"10.0.0.{32 * i}/27" for i in range(6))+ assert outputs["OwnAzs"] == f"{region}a,{region}b,{region}c"+ assert outputs["RefAzs"] == outputs["OwnAzs"]+ assert outputs["OtherAzs"] == ""+ assert outputs["Map"] == "ok"+ assert outputs["MapDefault"] == "dflt"+ assert outputs["AndInIf"] == "yes"+ assert ssm.get_parameter(Name=f"/cfn-intrinsics/{uid}")["Parameter"]["Value"] == (+ "192.168.0.0/24,192.168.1.0/24")+ # In a property position the condition functions evaluate to booleans+ # (joined as their string form), never to the Python repr of the call.+ assert ssm.get_parameter(Name=f"/cfn-intrinsics/{uid}/bools")["Parameter"]["Value"] == (+ "True,True,False")+ finally:+ _delete_cfn_test_stack(cfn, stack_name)++ # An impossible Fn::Cidr fails the resource with the reason.+ bad_cidr = f"cfn-intrinsics-cidr-{uid}"+ cfn.create_stack(StackName=bad_cidr, TemplateBody=json.dumps({"Resources": {+ "P": {"Type": "AWS::SSM::Parameter", "Properties": {+ "Name": f"/cfn-intrinsics/{uid}/cidr", "Type": "String",+ "Value": {"Fn::Select": [0, {"Fn::Cidr": ["10.0.0.0/24", 300, 8]}]}}}}}))+ try:+ stack = _wait_stack(cfn, bad_cidr)+ assert stack["StackStatus"] == "ROLLBACK_COMPLETE", stack.get("StackStatusReason")+ assert "Fn::Cidr count must be between 1 and 256" in _stack_event_reasons(cfn, bad_cidr)+ finally:+ _delete_cfn_test_stack(cfn, bad_cidr)++ def refused(body, message):+ name = f"cfn-intrinsics-bad-{_uuid_mod.uuid4().hex[:6]}"+ with pytest.raises(ClientError) as exc:+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(body))+ assert exc.value.response["Error"]["Code"] == "ValidationError"+ assert exc.value.response["Error"]["Message"] == message+ with pytest.raises(ClientError):+ cfn.describe_stacks(StackName=name)++ queue = {"Resources": {"Q": {"Type": "AWS::SQS::Queue"}}}+ refused({**queue, "Mappings": {"M": {"a": {"b": "ok"}}},+ "Outputs": {"Map": {"Value": {"Fn::FindInMap": ["M", "x", "y"]}}}},+ "Template error: Unable to get mapping for M::x::y")+ refused({**queue, "Outputs": {"And": {"Value": {"Fn::And": [+ {"Fn::Equals": ["a", "a"]}, {"Fn::Equals": ["a", "b"]}]}}}},+ "Template format error: The Value field of every Outputs member must evaluate to a String.")++def test_cfn_multi_resource_dependencies(cfn, iam, lam):template = {"AWSTemplateFormatVersion": "2010-09-09",