Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(cloudfront): accept DistributionConfigWithTags on CreateDistribution (#446)

david-hay4f4004d04d25
diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.py
index 49ce897b..73afb45e 100644
--- a/ministack/services/cloudfront.py
+++ b/ministack/services/cloudfront.py
@@ -4,7 +4,8 @@ REST/XML API — service credential scope: cloudfront.
Paths are under /2020-05-31/
Supports:
- Distributions: CreateDistribution, GetDistribution, GetDistributionConfig,
+ Distributions: CreateDistribution, CreateDistributionWithTags (DistributionConfigWithTags),
+ GetDistribution, GetDistributionConfig,
ListDistributions, UpdateDistribution, DeleteDistribution
Invalidations: CreateInvalidation, ListInvalidations, GetInvalidation
Origin Access Control (OAC): CreateOriginAccessControl, GetOriginAccessControl,
@@ -166,12 +167,63 @@ def _parse_body(body: bytes):
return None
+def _local_tag_name(el) -> str:
+ t = el.tag
+ return t.split("}")[-1] if "}" in t else t
+
+
+def _unwrap_distribution_create_xml(root_el):
+ """Return ``(DistributionConfig element, Tags element or None)``.
+
+ Terraform / boto3 ``CreateDistributionWithTags`` posts a
+ ``DistributionConfigWithTags`` root; ``CreateDistribution`` uses
+ ``DistributionConfig`` directly.
+ """
+ if root_el is None:
+ return None, None
+ if _local_tag_name(root_el) == "DistributionConfigWithTags":
+ cfg = _find(root_el, "DistributionConfig")
+ tags_el = _find(root_el, "Tags")
+ return cfg, tags_el
+ return root_el, None
+
+
+def _ingest_distribution_tags_from_xml(dist_arn: str, tags_el):
+ """Apply tag Items from CreateDistributionWithTags onto ``_tags``."""
+ if tags_el is None:
+ return
+ items_el = _find(tags_el, "Items") or tags_el
+ existing = {t["Key"]: t for t in _tags.get(dist_arn, [])}
+ for tag_el in items_el:
+ local = _local_tag_name(tag_el)
+ if local == "Tag":
+ key = _text(tag_el, "Key")
+ val = _text(tag_el, "Value")
+ if key:
+ existing[key] = {"Key": key, "Value": val}
+ _tags[dist_arn] = list(existing.values())
+
+
def _get_enabled(config_el) -> bool:
"""Extract Enabled boolean from a DistributionConfig XML element."""
val = _text(config_el, "Enabled", "true")
return val.strip().lower() != "false"
+def _ensure_distribution_config_sdk_compat(config_el):
+ """Patch DistributionConfig XML so hashicorp/aws CloudFront flatten does not nil-deref.
+
+ terraform-provider-aws (e.g. v6.42) does ``OriginGroups.Quantity`` without checking
+ ``OriginGroups``; real AWS returns ``<OriginGroups><Quantity>0</Quantity></OriginGroups>``
+ even when empty. Requests often omit that block.
+ """
+ if config_el is None:
+ return
+ if _find(config_el, "OriginGroups") is None:
+ og = SubElement(config_el, "OriginGroups")
+ SubElement(og, "Quantity").text = "0"
+
+
def _build_distribution_xml(parent, dist):
"""Append Distribution child elements to parent."""
SubElement(parent, "Id").text = dist["Id"]
@@ -182,6 +234,7 @@ def _build_distribution_xml(parent, dist):
SubElement(parent, "DomainName").text = dist["DomainName"]
# Re-parse and embed the stored config XML
config_el = fromstring(dist["config_xml"])
+ _ensure_distribution_config_sdk_compat(config_el)
config_el.tag = "DistributionConfig"
parent.append(config_el)
@@ -617,7 +670,8 @@ async def handle_request(method, path, headers, body, query_params):
# ---------------------------------------------------------------------------
def _create_distribution(headers, body):
- config_el = _parse_body(body)
+ root_el = _parse_body(body)
+ config_el, tags_el = _unwrap_distribution_create_xml(root_el)
if config_el is None:
return _error("MalformedXML", "The XML document is malformed.", 400)
@@ -653,6 +707,8 @@ def _create_distribution(headers, body):
_distributions[dist_id] = dist
_invalidations[dist_id] = []
+ _ingest_distribution_tags_from_xml(dist["ARN"], tags_el)
+
logger.info("CreateDistribution id=%s", dist_id)
def build(root):
@@ -681,6 +737,7 @@ def _get_distribution_config(dist_id):
return _error("NoSuchDistribution", "The specified distribution does not exist.", 404)
config_el = fromstring(dist["config_xml"])
+ _ensure_distribution_config_sdk_compat(config_el)
config_el.tag = "DistributionConfig"
config_el.set("xmlns", NS)
body = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(config_el, encoding="unicode").encode("utf-8")
diff --git a/tests/test_cloudfront.py b/tests/test_cloudfront.py
index 59878a77..3e5cc25c 100644
--- a/tests/test_cloudfront.py
+++ b/tests/test_cloudfront.py
@@ -44,6 +44,30 @@ def test_cloudfront_create_distribution(cloudfront):
assert dist["Status"] == "Deployed"
assert resp["ResponseMetadata"]["HTTPStatusCode"] == 201
+
+def test_cloudfront_create_distribution_with_tags(cloudfront):
+ """CreateDistributionWithTags (Terraform aws_cloudfront_distribution tags) unwraps inner config."""
+ if not hasattr(cloudfront, "create_distribution_with_tags"):
+ pytest.skip("boto3 has no create_distribution_with_tags")
+ ref = f"cf-with-tags-{_uuid_mod.uuid4().hex[:12]}"
+ cfg = {**_CF_DIST_CONFIG, "CallerReference": ref}
+ resp = cloudfront.create_distribution_with_tags(
+ DistributionConfigWithTags={
+ "DistributionConfig": cfg,
+ "Tags": {"Items": [{"Key": "env", "Value": "test"}]},
+ }
+ )
+ dist = resp["Distribution"]
+ dist_id = dist["Id"]
+ dist_arn = dist["ARN"]
+ assert dist["DomainName"].endswith(".cloudfront.net")
+ tags = cloudfront.list_tags_for_resource(Resource=dist_arn)["Tags"]["Items"]
+ assert any(t["Key"] == "env" and t["Value"] == "test" for t in tags)
+ etag = resp["ETag"]
+ disabled_cfg = {**cfg, "Enabled": False}
+ upd = cloudfront.update_distribution(DistributionConfig=disabled_cfg, Id=dist_id, IfMatch=etag)
+ cloudfront.delete_distribution(Id=dist_id, IfMatch=upd["ETag"])
+
def test_cloudfront_list_distributions(cloudfront):
cfg_a = {**_CF_DIST_CONFIG, "CallerReference": "cf-list-a", "Comment": "list-a"}
cfg_b = {**_CF_DIST_CONFIG, "CallerReference": "cf-list-b", "Comment": "list-b"}
@@ -64,6 +88,8 @@ def test_cloudfront_get_distribution(cloudfront):
assert dist["Id"] == dist_id
assert dist["DomainName"] == f"{dist_id}.cloudfront.net"
assert dist["Status"] == "Deployed"
+ # terraform-provider-aws v6+ dereferences OriginGroups without a nil check
+ assert dist["DistributionConfig"]["OriginGroups"]["Quantity"] == 0
def test_cloudfront_get_distribution_config(cloudfront):
cfg = {**_CF_DIST_CONFIG, "CallerReference": "cf-getcfg-1", "Comment": "getcfg-test"}
@@ -74,6 +100,7 @@ def test_cloudfront_get_distribution_config(cloudfront):
resp = cloudfront.get_distribution_config(Id=dist_id)
assert resp["ETag"] == etag
assert resp["DistributionConfig"]["Comment"] == "getcfg-test"
+ assert resp["DistributionConfig"]["OriginGroups"]["Quantity"] == 0
def test_cloudfront_update_distribution(cloudfront):
cfg = {**_CF_DIST_CONFIG, "CallerReference": "cf-upd-1", "Comment": "before-update"}
@@ -618,3 +645,18 @@ def test_cloudfront_function_describe_requires_stage(cloudfront):
cloudfront.describe_function(Name=name)
assert exc.value.response["Error"]["Code"] == "InvalidArgument"
assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+
+
+def test_cloudfront_sdk_compat_injects_origin_groups():
+ """terraform-provider-aws dereferences OriginGroups.Quantity without a nil check."""
+ from xml.etree.ElementTree import Element, SubElement
+
+ import ministack.services.cloudfront as cf
+
+ el = Element("DistributionConfig")
+ SubElement(el, "CallerReference").text = "unit-ref"
+ assert cf._find(el, "OriginGroups") is None
+ cf._ensure_distribution_config_sdk_compat(el)
+ og = cf._find(el, "OriginGroups")
+ assert og is not None
+ assert cf._text(og, "Quantity") == "0"