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): enforce Capabilities under AUTH=true (#1660)
iot-rocketb38b5f980904
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a5326eb7..90fe0aef 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,11 @@ All notable changes to MiniStack will be documented here.Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).Versioning follows [Semantic Versioning](https://semver.org/).+## [Unreleased]++### Fixed+- **CloudFormation — `Capabilities` are enforced under `AUTH=true`** — `CreateStack`, `UpdateStack` and `CreateChangeSet` accepted a template with IAM resources or a `Transform` whatever the request acknowledged, so a deploy that CloudFormation refuses with `InsufficientCapabilitiesException` went through. With `AUTH=true` they now answer that error (HTTP 400, `Requires capabilities : [CAPABILITY_IAM]`, measured) and create nothing: an IAM resource needs `CAPABILITY_IAM` or `CAPABILITY_NAMED_IAM`, one with a custom name `CAPABILITY_NAMED_IAM`, a template with a `Transform` `CAPABILITY_AUTO_EXPAND` on `CreateStack` and `UpdateStack` (not on a change set, as the API documents). Without `AUTH` nothing changes; `GetTemplateSummary` keeps reporting the same set. Contributed by @iot-rocket.+## [1.5.9] — 2026-09-08### Addeddiff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.pyindex 53777d99..3cf81a03 100644--- a/ministack/services/cloudformation/changesets.py+++ b/ministack/services/cloudformation/changesets.py@@ -77,7 +77,10 @@ def _resolve_props_for_diff(template, params, stack_name, stack_id):def _create_change_set(params):from ministack.services.cloudformation import _change_sets, _stack_events, _stacks- from ministack.services.cloudformation.handlers import _resolve_stack+ from ministack.services.cloudformation.handlers import (+ _check_capabilities,+ _resolve_stack,+ )stack_name = _p(params, "StackName")cs_name = _p(params, "ChangeSetName")cs_type = _p(params, "ChangeSetType", "UPDATE")@@ -166,20 +169,29 @@ def _create_change_set(params):if not template_body:template_body = stack.get("_template_body", "{}")- def _rejected(message):+ def _rejected(reason):# A rejected CreateChangeSet leaves no stack behind on AWS; drop the# REVIEW_IN_PROGRESS placeholder created above for CREATE sets.+ # ``reason`` is a ValidationError message or a ready error response.if cs_type == "CREATE":_stacks.pop(stack_name, None)_stack_events.pop(stack_id, None)- return _error("ValidationError", message)+ if isinstance(reason, tuple):+ return reason+ return _error("ValidationError", reason)try:- template = _parse_template(template_body)+ template = sent = _parse_template(template_body)template = _apply_sam_transform_if_applicable(template)except Exception as e:return _rejected(f"Template format error: {e}")+ # Checked after the transform, as CreateStack and UpdateStack do.+ # CAPABILITY_AUTO_EXPAND does not apply to a change set+ # (API_CreateChangeSet), so only the IAM rule runs here.+ if caps_error := _check_capabilities(sent, template, params, macros=False):+ return _rejected(caps_error)+try:param_values = _resolve_parameters(template, provided_params, stack.get("_resolved_params", {}))diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.pyindex 0564ec6d..d38c7b26 100644--- a/ministack/services/cloudformation/handlers.py+++ b/ministack/services/cloudformation/handlers.py@@ -51,6 +51,151 @@ from .stacks import (logger = logging.getLogger("cloudformation")+# GetTemplateSummary's rule, kept as it was: every ``AWS::IAM::*`` type needs+# a capability, and these name properties make it CAPABILITY_NAMED_IAM.+_NAMED_IAM_PROPS = {+ "AWS::IAM::Role": "RoleName",+ "AWS::IAM::User": "UserName",+ "AWS::IAM::Group": "GroupName",+ "AWS::IAM::Policy": "PolicyName",+ "AWS::IAM::ManagedPolicy": "ManagedPolicyName",+ "AWS::IAM::InstanceProfile": "InstanceProfileName",+}++# The enforcement rule, from the ``Capabilities`` parameter of API_CreateStack:+# these eight types "require you to specify either the CAPABILITY_IAM or+# CAPABILITY_NAMED_IAM capability", and "If you have IAM resources with+# custom names, you must specify CAPABILITY_NAMED_IAM". ``AWS::IAM::Policy``+# is not in the named map: its ``PolicyName`` is a required property+# (aws-resource-iam-policy.html), not a custom name.+_CAPABILITY_IAM_TYPES = frozenset({+ "AWS::IAM::AccessKey",+ "AWS::IAM::Group",+ "AWS::IAM::InstanceProfile",+ "AWS::IAM::ManagedPolicy",+ "AWS::IAM::Policy",+ "AWS::IAM::Role",+ "AWS::IAM::User",+ "AWS::IAM::UserToGroupAddition",+})+_CAPABILITY_NAMED_PROPS = {+ rtype: prop for rtype, prop in _NAMED_IAM_PROPS.items()+ if rtype != "AWS::IAM::Policy"+}+++def _uses_embedded_macro(template):+ """True when a section of the template (other than ``Parameters`` and+ ``AWSTemplateFormatVersion``) contains an ``Fn::Transform`` node: a macro+ called on part of the template (intrinsic-function-reference-transform),+ which API_CreateStack counts like a top-level ``Transform`` for+ ``CAPABILITY_AUTO_EXPAND`` ("one or more macros")."""+ stack = [value for section, value in template.items()+ if section not in ("Parameters", "AWSTemplateFormatVersion", "Transform")]+ while stack:+ node = stack.pop()+ if isinstance(node, dict):+ if "Fn::Transform" in node:+ return True+ stack.extend(node.values())+ elif isinstance(node, list):+ stack.extend(node)+ return False+++def _uses_macro(template):+ """True when the template calls one or more macros: a top-level+ ``Transform`` or an embedded ``Fn::Transform`` node. Both count for the+ ``CAPABILITY_AUTO_EXPAND`` rule of API_CreateStack."""+ return bool(template.get("Transform")) or _uses_embedded_macro(template)+++def _required_capabilities(template, strict=False):+ """Return ``(capabilities, reason_types)`` for a parsed template:+ ``CAPABILITY_NAMED_IAM`` when an IAM resource carries a custom name,+ ``CAPABILITY_IAM`` for the other IAM resources, ``CAPABILITY_AUTO_EXPAND``+ when the template declares a ``Transform``. ``reason_types`` are the IAM+ types behind the IAM entry.++ The default is ``GetTemplateSummary``'s rule (``_NAMED_IAM_PROPS``, every+ ``AWS::IAM::*`` type, top-level ``Transform`` only); ``strict=True`` is+ the documented rule the enforcement uses (``_CAPABILITY_IAM_TYPES``,+ ``_CAPABILITY_NAMED_PROPS``, and an embedded ``Fn::Transform`` counts as a+ macro too).+ """+ resources = template.get("Resources", {}) or {}+ named_props = _CAPABILITY_NAMED_PROPS if strict else _NAMED_IAM_PROPS+ named_iam_ids = []+ unnamed_iam_ids = []+ for logical_id, res in resources.items():+ rtype = res.get("Type", "")+ if strict:+ if rtype not in _CAPABILITY_IAM_TYPES:+ continue+ elif not rtype.startswith("AWS::IAM::"):+ continue+ name_prop = named_props.get(rtype)+ if name_prop and (res.get("Properties") or {}).get(name_prop):+ named_iam_ids.append(logical_id)+ else:+ unnamed_iam_ids.append(logical_id)++ capabilities = []+ reason_types = []+ if named_iam_ids:+ capabilities.append("CAPABILITY_NAMED_IAM")+ reason_types.extend(+ sorted(set(resources[lid].get("Type", "") for lid in named_iam_ids))+ )+ elif unnamed_iam_ids:+ capabilities.append("CAPABILITY_IAM")+ reason_types.extend(+ sorted(set(resources[lid].get("Type", "") for lid in unnamed_iam_ids))+ )+ macro = _uses_macro(template) if strict else bool(template.get("Transform"))+ if macro:+ capabilities.append("CAPABILITY_AUTO_EXPAND")+ return capabilities, reason_types+++def _check_capabilities(sent, template, params, macros=True):+ """Refuse a template whose required capabilities the request does not+ acknowledge, the way CreateStack does: HTTP 400+ ``InsufficientCapabilitiesException`` with ``Requires capabilities :+ [CAPABILITY_IAM]`` and no stack created (measured on AWS for the IAM case).++ ``sent`` is the template as the request sent it, ``template`` the same one+ after the SAM transform. The macro rule reads ``sent``, because the+ transform drops the ``Transform`` key it looks at; the IAM rule reads+ ``template``, because a macro may add IAM resources and AWS asks for those+ to be acknowledged as well (template-macros-overview.html).++ Capabilities are IAM scope, so the check only runs under ``AUTH=true``;+ without it every template is accepted as before. ``CAPABILITY_IAM`` is+ satisfied by either IAM capability, ``CAPABILITY_NAMED_IAM`` only by+ itself. Pass ``macros=False`` for ``CreateChangeSet``: the API reference+ says ``CAPABILITY_AUTO_EXPAND`` "doesn't apply to creating change sets".+ Returns an error response or ``None``."""+ from ministack.app import AUTH+ if not AUTH:+ return None+ given = set(_extract_string_members(params, "Capabilities"))+ required = [cap for cap in _required_capabilities(template, strict=True)[0]+ if cap != "CAPABILITY_AUTO_EXPAND"]+ if macros and _uses_macro(sent):+ required.append("CAPABILITY_AUTO_EXPAND")+ missing = []+ for cap in required:+ if cap == "CAPABILITY_IAM" and "CAPABILITY_NAMED_IAM" in given:+ continue+ if cap not in given:+ missing.append(cap)+ if not missing:+ return None+ return _error("InsufficientCapabilitiesException",+ "Requires capabilities : [" + ", ".join(missing) + "]")++# --- CreateStack ---def _create_stack(params):@@ -76,7 +221,7 @@ def _create_stack(params):f"Stack [{stack_name}] already exists")try:- template = _parse_template(template_body)+ template = sent = _parse_template(template_body)template = _apply_sam_transform_if_applicable(template)except Exception as e:return _error("ValidationError", f"Template format error: {e}")@@ -89,6 +234,12 @@ def _create_stack(params):if tags_error:return tags_error+ # The macro rule reads the template as sent (the SAM transform above drops+ # the Transform key), the IAM rule the transformed one (a macro can add+ # IAM resources, and AWS asks for those to be acknowledged too).+ if caps_error := _check_capabilities(sent, template, params):+ return caps_error+# Resolve parameterstry:param_values = _resolve_parameters(template, provided_params)@@ -703,7 +854,7 @@ def _update_stack(params):return _error("ValidationError", "TemplateBody or TemplateURL is required")try:- template = _parse_template(template_body)+ template = sent = _parse_template(template_body)template = _apply_sam_transform_if_applicable(template)except Exception as e:return _error("ValidationError", f"Template format error: {e}")@@ -720,6 +871,12 @@ def _update_stack(params):if tags_error:return tags_error+ # The macro rule reads the template as sent (the SAM transform above drops+ # the Transform key), the IAM rule the transformed one (a macro can add+ # IAM resources, and AWS asks for those to be acknowledged too).+ if caps_error := _check_capabilities(sent, template, params):+ return caps_error+try:param_values = _resolve_parameters(template, provided_params, stack.get("_resolved_params", {}))@@ -916,40 +1073,7 @@ def _get_template_summary(params):"</member>")- _NAMED_IAM_PROPS = {- "AWS::IAM::Role": "RoleName",- "AWS::IAM::User": "UserName",- "AWS::IAM::Group": "GroupName",- "AWS::IAM::Policy": "PolicyName",- "AWS::IAM::ManagedPolicy": "ManagedPolicyName",- "AWS::IAM::InstanceProfile": "InstanceProfileName",- }- named_iam_ids = []- unnamed_iam_ids = []- for logical_id, res in resources.items():- rtype = res.get("Type", "")- if not rtype.startswith("AWS::IAM::"):- continue- name_prop = _NAMED_IAM_PROPS.get(rtype)- if name_prop and res.get("Properties", {}).get(name_prop):- named_iam_ids.append(logical_id)- else:- unnamed_iam_ids.append(logical_id)-- capabilities = []- caps_reason_types = []- if named_iam_ids:- capabilities.append("CAPABILITY_NAMED_IAM")- caps_reason_types.extend(- sorted(set(resources[lid].get("Type", "") for lid in named_iam_ids))- )- elif unnamed_iam_ids:- capabilities.append("CAPABILITY_IAM")- caps_reason_types.extend(- sorted(set(resources[lid].get("Type", "") for lid in unnamed_iam_ids))- )- if template.get("Transform"):- capabilities.append("CAPABILITY_AUTO_EXPAND")+ capabilities, caps_reason_types = _required_capabilities(template)caps_xml = "".join(f"<member>{c}</member>" for c in capabilities)# AWS'es behavior here is very inconsistent with their docs. AWS doesn't necessarily returndiff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 1cb75fdf..c3745ca8 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -2499,6 +2499,473 @@ def test_cfn_get_template_summary(cfn):result = cfn.get_template_summary(TemplateBody=json.dumps(transform_tpl))assert "CAPABILITY_AUTO_EXPAND" in result["Capabilities"]++# --- Capabilities are enforced under AUTH=true (in-process, no server) ---+#+# API_CreateStack / API_UpdateStack / API_CreateChangeSet, "Capabilities":+# IAM resources need CAPABILITY_IAM or CAPABILITY_NAMED_IAM, custom-named+# ones CAPABILITY_NAMED_IAM, a template with macros CAPABILITY_AUTO_EXPAND on+# CreateStack / UpdateStack ("doesn't apply to creating change sets");+# otherwise the InsufficientCapabilities error, HTTP 400. Measured on AWS for+# an unnamed role: "Requires capabilities : [CAPABILITY_IAM]", no stack.++_CAPS_ROLE_TEMPLATE = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Role": {+ "Type": "AWS::IAM::Role",+ "Properties": {+ "AssumeRolePolicyDocument": {"Version": "2012-10-17", "Statement": []},+ },+ }+ },+}+_CAPS_NAMED_ROLE_TEMPLATE = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Role": {+ "Type": "AWS::IAM::Role",+ "Properties": {+ "RoleName": "cfn-caps-named-role",+ "AssumeRolePolicyDocument": {"Version": "2012-10-17", "Statement": []},+ },+ }+ },+}+# A SAM template the transform accepts. The transform generates an unnamed+# execution role for the function, so a handler needs CAPABILITY_IAM for the+# transformed template and CAPABILITY_AUTO_EXPAND for the macro. The helper+# tests below pass this template untransformed, where only the macro counts.+_CAPS_TRANSFORM_TEMPLATE = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Transform": "AWS::Serverless-2016-10-31",+ "Resources": {+ "Fn": {+ "Type": "AWS::Serverless::Function",+ "Properties": {+ "Handler": "index.handler",+ "Runtime": "python3.12",+ "InlineCode": "def handler(event, context): return None",+ },+ },+ },+}+_CAPS_BUCKET_TEMPLATE = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {"Bucket": {"Type": "AWS::S3::Bucket"}},+}+# PolicyName is a required property of AWS::IAM::Policy, not a custom name+# (aws-resource-iam-policy.html): CAPABILITY_IAM is enough.+_CAPS_POLICY_TEMPLATE = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Policy": {+ "Type": "AWS::IAM::Policy",+ "Properties": {+ "PolicyName": "cfn-caps-inline",+ "PolicyDocument": {"Version": "2012-10-17", "Statement": []},+ "Roles": ["cfn-caps-some-role"],+ },+ }+ },+}+# Not one of the eight documented types: no capability needed.+_CAPS_SERVICE_LINKED_ROLE_TEMPLATE = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Slr": {+ "Type": "AWS::IAM::ServiceLinkedRole",+ "Properties": {"AWSServiceName": "autoscaling.amazonaws.com"},+ }+ },+}+_CAPS_NULL_PROPS_ROLE_TEMPLATE = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {"Role": {"Type": "AWS::IAM::Role", "Properties": None}},+}+++def _caps_params(template, *capabilities, **extra):+ """A parsed query-protocol request the way ``handle_request`` builds it."""+ params = {"TemplateBody": [json.dumps(template)]}+ for i, cap in enumerate(capabilities, 1):+ params[f"Capabilities.member.{i}"] = [cap]+ for key, value in extra.items():+ params[key] = [value]+ return params+++def _caps_error(response):+ """``(status, code, message)`` of an in-process CloudFormation response."""+ status, _headers, body = response+ text = body.decode("utf-8")+ code = re.search(r"<Code>([^<]*)</Code>", text)+ message = re.search(r"<Message>([^<]*)</Message>", text)+ return status, code.group(1) if code else "", message.group(1) if message else ""+++def test_cfn_required_capabilities_helper():+ from ministack.services.cloudformation.handlers import _required_capabilities++ assert _required_capabilities(_CAPS_BUCKET_TEMPLATE) == ([], [])+ assert _required_capabilities(_CAPS_ROLE_TEMPLATE) == (+ ["CAPABILITY_IAM"], ["AWS::IAM::Role"])+ assert _required_capabilities(_CAPS_NAMED_ROLE_TEMPLATE) == (+ ["CAPABILITY_NAMED_IAM"], ["AWS::IAM::Role"])+ assert _required_capabilities(_CAPS_TRANSFORM_TEMPLATE) == (+ ["CAPABILITY_AUTO_EXPAND"], [])+ both = dict(_CAPS_NAMED_ROLE_TEMPLATE, Transform="AWS::LanguageExtensions")+ assert _required_capabilities(both) == (+ ["CAPABILITY_NAMED_IAM", "CAPABILITY_AUTO_EXPAND"], ["AWS::IAM::Role"])+ assert _required_capabilities(_CAPS_NULL_PROPS_ROLE_TEMPLATE) == (+ ["CAPABILITY_IAM"], ["AWS::IAM::Role"])++ # The summary's rule stays as it was: PolicyName counts as a name and every+ # AWS::IAM::* type needs a capability. The documented rule the enforcement+ # uses (strict=True) differs on both.+ assert _required_capabilities(_CAPS_POLICY_TEMPLATE) == (+ ["CAPABILITY_NAMED_IAM"], ["AWS::IAM::Policy"])+ assert _required_capabilities(_CAPS_POLICY_TEMPLATE, strict=True) == (+ ["CAPABILITY_IAM"], ["AWS::IAM::Policy"])+ assert _required_capabilities(_CAPS_SERVICE_LINKED_ROLE_TEMPLATE) == (+ ["CAPABILITY_IAM"], ["AWS::IAM::ServiceLinkedRole"])+ assert _required_capabilities(_CAPS_SERVICE_LINKED_ROLE_TEMPLATE, strict=True) == ([], [])+ assert _required_capabilities(_CAPS_NAMED_ROLE_TEMPLATE, strict=True) == (+ ["CAPABILITY_NAMED_IAM"], ["AWS::IAM::Role"])+++def test_cfn_capabilities_not_enforced_without_auth(monkeypatch):+ import ministack.app as app_mod+ from ministack.services.cloudformation import _change_sets, _stack_events, _stacks+ from ministack.services.cloudformation.changesets import _create_change_set+ from ministack.services.cloudformation.handlers import _check_capabilities++ monkeypatch.setattr(app_mod, "AUTH", False)+ # The check takes the template as sent and the transformed one; these+ # templates are passed untransformed, so both arguments are the same.+ assert _check_capabilities(+ _CAPS_ROLE_TEMPLATE, _CAPS_ROLE_TEMPLATE, _caps_params(_CAPS_ROLE_TEMPLATE)) is None+ assert _check_capabilities(+ _CAPS_NAMED_ROLE_TEMPLATE, _CAPS_NAMED_ROLE_TEMPLATE,+ _caps_params(_CAPS_NAMED_ROLE_TEMPLATE)) is None+ assert _check_capabilities(+ _CAPS_TRANSFORM_TEMPLATE, _CAPS_TRANSFORM_TEMPLATE,+ _caps_params(_CAPS_TRANSFORM_TEMPLATE)) is None++ # A handler accepts the IAM template without any capability, as before.+ stack_name = "cfn-caps-noauth-cs"+ try:+ response = _create_change_set(_caps_params(+ _CAPS_ROLE_TEMPLATE, StackName=stack_name,+ ChangeSetName="cs1", ChangeSetType="CREATE"))+ status, code, _ = _caps_error(response)+ assert status == 200, code+ assert stack_name in _stacks+ finally:+ stack = _stacks.pop(stack_name, None)+ if stack:+ _stack_events.pop(stack["StackId"], None)+ for cs_id in [k for k, v in _change_sets.items()+ if v.get("StackName") == stack_name]:+ _change_sets.pop(cs_id, None)+++def test_cfn_capabilities_check_under_auth(monkeypatch):+ import ministack.app as app_mod+ from ministack.services.cloudformation.handlers import _check_capabilities++ monkeypatch.setattr(app_mod, "AUTH", True)++ def check(template, *caps, **kw):+ # Untransformed: the template as sent and the transformed one are equal.+ response = _check_capabilities(+ template, template, _caps_params(template, *caps), **kw)+ return None if response is None else _caps_error(response)++ refused = (400, "InsufficientCapabilitiesException",+ "Requires capabilities : [CAPABILITY_IAM]")+ assert check(_CAPS_BUCKET_TEMPLATE) is None+ assert check(_CAPS_ROLE_TEMPLATE) == refused+ assert check(_CAPS_ROLE_TEMPLATE, "CAPABILITY_AUTO_EXPAND") == refused+ # "If you have IAM resources, you can specify either capability."+ assert check(_CAPS_ROLE_TEMPLATE, "CAPABILITY_IAM") is None+ assert check(_CAPS_ROLE_TEMPLATE, "CAPABILITY_NAMED_IAM") is None+ # "If you have IAM resources with custom names, you must specify+ # CAPABILITY_NAMED_IAM."+ assert check(_CAPS_NAMED_ROLE_TEMPLATE, "CAPABILITY_IAM") == (+ 400, "InsufficientCapabilitiesException",+ "Requires capabilities : [CAPABILITY_NAMED_IAM]")+ assert check(_CAPS_NAMED_ROLE_TEMPLATE, "CAPABILITY_NAMED_IAM") is None+ assert check(_CAPS_NAMED_ROLE_TEMPLATE, "CAPABILITY_IAM", "CAPABILITY_NAMED_IAM") is None+ # A macro template needs CAPABILITY_AUTO_EXPAND on CreateStack / UpdateStack+ # but not on CreateChangeSet.+ assert check(_CAPS_TRANSFORM_TEMPLATE) == (+ 400, "InsufficientCapabilitiesException",+ "Requires capabilities : [CAPABILITY_AUTO_EXPAND]")+ assert check(_CAPS_TRANSFORM_TEMPLATE, "CAPABILITY_AUTO_EXPAND") is None+ assert check(_CAPS_TRANSFORM_TEMPLATE, macros=False) is None+ both = dict(_CAPS_ROLE_TEMPLATE, Transform="AWS::LanguageExtensions")+ assert check(both, "CAPABILITY_IAM") == (+ 400, "InsufficientCapabilitiesException",+ "Requires capabilities : [CAPABILITY_AUTO_EXPAND]")+ assert check(both, "CAPABILITY_AUTO_EXPAND") == refused+ assert check(both, "CAPABILITY_AUTO_EXPAND", "CAPABILITY_IAM") is None+ # An AWS::IAM::Policy needs CAPABILITY_IAM only; a type outside the+ # documented eight needs nothing; a null Properties is an unnamed resource.+ assert check(_CAPS_POLICY_TEMPLATE) == refused+ assert check(_CAPS_POLICY_TEMPLATE, "CAPABILITY_IAM") is None+ assert check(_CAPS_SERVICE_LINKED_ROLE_TEMPLATE) is None+ assert check(_CAPS_NULL_PROPS_ROLE_TEMPLATE) == refused+++def test_cfn_create_stack_refuses_missing_capabilities_under_auth(monkeypatch):+ import ministack.app as app_mod+ from ministack.services.cloudformation import _stack_events, _stacks+ from ministack.services.cloudformation.handlers import _create_stack++ monkeypatch.setattr(app_mod, "AUTH", True)+ stack_name = "cfn-caps-auth-create"++ try:+ response = _create_stack(_caps_params(_CAPS_ROLE_TEMPLATE, StackName=stack_name))+ assert _caps_error(response) == (+ 400, "InsufficientCapabilitiesException",+ "Requires capabilities : [CAPABILITY_IAM]")+ assert stack_name not in _stacks++ response = _create_stack(_caps_params(+ _CAPS_NAMED_ROLE_TEMPLATE, "CAPABILITY_IAM", StackName=stack_name))+ assert _caps_error(response) == (+ 400, "InsufficientCapabilitiesException",+ "Requires capabilities : [CAPABILITY_NAMED_IAM]")+ assert stack_name not in _stacks++ # Two capabilities missing at once. The macro rule reads the template+ # as sent, whose Transform the SAM transform drops; the IAM rule reads+ # the transformed template, which carries the generated function role.+ pytest.importorskip("samtranslator")+ response = _create_stack(_caps_params(_CAPS_TRANSFORM_TEMPLATE, StackName=stack_name))+ assert _caps_error(response) == (+ 400, "InsufficientCapabilitiesException",+ "Requires capabilities : [CAPABILITY_IAM, CAPABILITY_AUTO_EXPAND]")+ assert stack_name not in _stacks++ response = _create_stack(_caps_params(+ _CAPS_TRANSFORM_TEMPLATE, "CAPABILITY_AUTO_EXPAND", StackName=stack_name))+ assert _caps_error(response) == (+ 400, "InsufficientCapabilitiesException",+ "Requires capabilities : [CAPABILITY_IAM]")+ assert stack_name not in _stacks++ response = _create_stack(_caps_params(+ _CAPS_NULL_PROPS_ROLE_TEMPLATE, StackName=stack_name))+ assert _caps_error(response) == (+ 400, "InsufficientCapabilitiesException",+ "Requires capabilities : [CAPABILITY_IAM]")+ assert stack_name not in _stacks+ finally:+ stack = _stacks.pop(stack_name, None)+ if stack:+ _stack_events.pop(stack["StackId"], None)+++def test_cfn_embedded_fn_transform_needs_auto_expand_under_auth(monkeypatch):+ """A macro called on part of the template (``Fn::Transform``, e.g.+ ``AWS::Include``) has no top-level ``Transform`` but is a macro all the+ same, so CreateStack needs CAPABILITY_AUTO_EXPAND for it. The summary's+ rule stays top-level only."""+ import ministack.app as app_mod+ from ministack.services.cloudformation import _stacks+ from ministack.services.cloudformation.handlers import (+ _check_capabilities,+ _create_stack,+ _required_capabilities,+ )++ embedded = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Bucket": {+ "Type": "AWS::S3::Bucket",+ "Properties": {+ "Fn::Transform": {+ "Name": "AWS::Include",+ "Parameters": {"Location": "s3://example.local/bucket-props.yaml"},+ },+ },+ },+ },+ }+ assert _required_capabilities(embedded) == ([], [])+ assert _required_capabilities(embedded, strict=True) == (["CAPABILITY_AUTO_EXPAND"], [])+ # A parameter default is not walked: a macro name there is not a macro call.+ in_parameters = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Parameters": {"P": {"Type": "String", "Default": "Fn::Transform"}},+ "Resources": {"Bucket": {"Type": "AWS::S3::Bucket"}},+ }+ assert _required_capabilities(in_parameters, strict=True) == ([], [])++ monkeypatch.setattr(app_mod, "AUTH", True)+ refused = (400, "InsufficientCapabilitiesException",+ "Requires capabilities : [CAPABILITY_AUTO_EXPAND]")+ assert _caps_error(+ _check_capabilities(embedded, embedded, _caps_params(embedded))) == refused+ assert _check_capabilities(+ embedded, embedded, _caps_params(embedded, "CAPABILITY_AUTO_EXPAND")) is None+ # Not on a change set (macros=False).+ assert _check_capabilities(embedded, embedded, _caps_params(embedded), macros=False) is None++ stack_name = "cfn-caps-auth-embedded"+ response = _create_stack(_caps_params(embedded, StackName=stack_name))+ assert _caps_error(response) == refused+ assert stack_name not in _stacks+++def test_cfn_create_stack_capabilities_parsed_from_wire_under_auth(monkeypatch):+ import asyncio+ from urllib.parse import urlencode++ import ministack.app as app_mod+ from ministack.services.cloudformation import _stacks, handle_request++ monkeypatch.setattr(app_mod, "AUTH", True)+ stack_name = "cfn-caps-auth-wire"+ body = urlencode({+ "Action": "CreateStack",+ "Version": "2010-05-15",+ "StackName": stack_name,+ "TemplateBody": json.dumps(_CAPS_NAMED_ROLE_TEMPLATE),+ "Capabilities.member.1": "CAPABILITY_IAM",+ "Capabilities.member.2": "CAPABILITY_AUTO_EXPAND",+ }).encode()+ headers = {"content-type": "application/x-www-form-urlencoded"}+ response = asyncio.run(handle_request("POST", "/", headers, body, {}))+ # CAPABILITY_IAM arrived and was considered: only NAMED_IAM is missing.+ assert _caps_error(response) == (+ 400, "InsufficientCapabilitiesException",+ "Requires capabilities : [CAPABILITY_NAMED_IAM]")+ assert stack_name not in _stacks+++def test_cfn_update_stack_refuses_missing_capabilities_under_auth(monkeypatch):+ import ministack.app as app_mod+ from ministack.services.cloudformation import _stack_events, _stacks+ from ministack.services.cloudformation.handlers import _update_stack++ monkeypatch.setattr(app_mod, "AUTH", True)+ stack_name = "cfn-caps-auth-update"+ stack_id = f"arn:aws:cloudformation:us-east-1:000000000000:stack/{stack_name}/caps-1"+ _stacks[stack_name] = {+ "StackName": stack_name,+ "StackId": stack_id,+ "StackStatus": "CREATE_COMPLETE",+ "Parameters": [],+ "Tags": [],+ "Outputs": [],+ "_region": "us-east-1",+ "_resources": {},+ "_template": _CAPS_BUCKET_TEMPLATE,+ "_template_body": json.dumps(_CAPS_BUCKET_TEMPLATE),+ "_resolved_params": {},+ "_conditions": {},+ }+ _stack_events[stack_id] = []+ try:+ response = _update_stack(_caps_params(_CAPS_ROLE_TEMPLATE, StackName=stack_name))+ assert _caps_error(response) == (+ 400, "InsufficientCapabilitiesException",+ "Requires capabilities : [CAPABILITY_IAM]")+ assert _stacks[stack_name]["StackStatus"] == "CREATE_COMPLETE"++ pytest.importorskip("samtranslator")+ response = _update_stack(_caps_params(_CAPS_TRANSFORM_TEMPLATE, StackName=stack_name))+ assert _caps_error(response) == (+ 400, "InsufficientCapabilitiesException",+ "Requires capabilities : [CAPABILITY_IAM, CAPABILITY_AUTO_EXPAND]")+ assert _stacks[stack_name]["StackStatus"] == "CREATE_COMPLETE"++ # UsePreviousTemplate re-checks the stored template (unmeasured on AWS).+ _stacks[stack_name]["_template"] = _CAPS_ROLE_TEMPLATE+ _stacks[stack_name]["_template_body"] = json.dumps(_CAPS_ROLE_TEMPLATE)+ response = _update_stack({+ "StackName": [stack_name], "UsePreviousTemplate": ["true"],+ "Parameters.member.1.ParameterKey": ["Unused"],+ })+ assert _caps_error(response) == (+ 400, "InsufficientCapabilitiesException",+ "Requires capabilities : [CAPABILITY_IAM]")+ assert _stacks[stack_name]["StackStatus"] == "CREATE_COMPLETE"+ finally:+ _stacks.pop(stack_name, None)+ _stack_events.pop(stack_id, None)+++def test_cfn_create_change_set_refuses_missing_iam_capability_under_auth(monkeypatch):+ import ministack.app as app_mod+ from ministack.services.cloudformation import _change_sets, _stack_events, _stacks+ from ministack.services.cloudformation.changesets import _create_change_set++ monkeypatch.setattr(app_mod, "AUTH", True)+ stack_name = "cfn-caps-auth-cs"++ try:+ response = _create_change_set(_caps_params(+ _CAPS_ROLE_TEMPLATE, StackName=stack_name,+ ChangeSetName="cs1", ChangeSetType="CREATE"))+ assert _caps_error(response) == (+ 400, "InsufficientCapabilitiesException",+ "Requires capabilities : [CAPABILITY_IAM]")+ # A refused CREATE change set leaves no REVIEW_IN_PROGRESS stack behind.+ assert stack_name not in _stacks++ response = _create_change_set(_caps_params(+ _CAPS_NAMED_ROLE_TEMPLATE, "CAPABILITY_IAM", StackName=stack_name,+ ChangeSetName="cs1", ChangeSetType="CREATE"))+ assert _caps_error(response) == (+ 400, "InsufficientCapabilitiesException",+ "Requires capabilities : [CAPABILITY_NAMED_IAM]")+ assert stack_name not in _stacks+ finally:+ stack = _stacks.pop(stack_name, None)+ if stack:+ _stack_events.pop(stack["StackId"], None)+ for cs_id in [k for k, v in _change_sets.items()+ if v.get("StackName") == stack_name]:+ _change_sets.pop(cs_id, None)++ # With CAPABILITY_IAM the set is created and the REVIEW_IN_PROGRESS+ # placeholder stays.+ try:+ response = _create_change_set(_caps_params(+ _CAPS_ROLE_TEMPLATE, "CAPABILITY_IAM", StackName=stack_name,+ ChangeSetName="cs1", ChangeSetType="CREATE"))+ status, code, _ = _caps_error(response)+ assert status == 200, code+ assert _stacks[stack_name]["StackStatus"] == "REVIEW_IN_PROGRESS"+ finally:+ stack = _stacks.pop(stack_name, None)+ if stack:+ _stack_events.pop(stack["StackId"], None)+ for cs_id in [k for k, v in _change_sets.items()+ if v.get("StackName") == stack_name]:+ _change_sets.pop(cs_id, None)++ # CAPABILITY_AUTO_EXPAND "doesn't apply to creating change sets": a macro+ # template without it is not refused for capabilities.+ macro = dict(_CAPS_BUCKET_TEMPLATE, Transform="AWS::LanguageExtensions")+ try:+ response = _create_change_set(_caps_params(+ macro, StackName=stack_name, ChangeSetName="cs1", ChangeSetType="CREATE"))+ assert _caps_error(response)[1] != "InsufficientCapabilitiesException"+ finally:+ stack = _stacks.pop(stack_name, None)+ if stack:+ _stack_events.pop(stack["StackId"], None)+ for cs_id in [k for k, v in _change_sets.items()+ if v.get("StackName") == stack_name]:+ _change_sets.pop(cs_id, None)+def test_cfn_list_stacks(cfn):for name in ("cfn-t12-a", "cfn-t12-b"):template = {