Skip to content

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

#92: [FEAT] Add CloudFront service (#93)

Nikhil Adigaf861ec7b7b1c
diff --git a/ministack/app.py b/ministack/app.py
index 7a4d4156..502df2c4 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -73,6 +73,7 @@ from ministack.services import (
ssm,
stepfunctions,
waf,
+ cloudfront,
)
from ministack.services import iam_sts
from ministack.services.iam_sts import handle_iam_request, handle_sts_request
@@ -120,6 +121,7 @@ SERVICE_HANDLERS = {
"elasticloadbalancing": alb.handle_request,
"elasticfilesystem": efs.handle_request,
"kms": kms.handle_request,
+ "cloudfront": cloudfront.handle_request,
}
SERVICE_NAME_ALIASES = {
@@ -173,7 +175,7 @@ BANNER = r"""
Services: S3, SQS, SNS, DynamoDB, Lambda, IAM, STS, SecretsManager, CloudWatch Logs,
SSM, EventBridge, Kinesis, CloudWatch, SES, SES v2, ACM, WAF v2, Step Functions,
ECS, RDS, ElastiCache, Glue, Athena, API Gateway, Firehose, Route53,
- Cognito, EC2, EMR, EBS, EFS, ALB/ELBv2, CloudFormation, KMS, ECR
+ Cognito, EC2, EMR, EBS, EFS, ALB/ELBv2, CloudFormation, KMS, ECR, CloudFront
"""
@@ -623,6 +625,7 @@ def _reset_all_state():
(efs, efs.reset),
(cloudformation, cloudformation.reset),
(kms, kms.reset),
+ (cloudfront, cloudfront.reset),
]:
try:
fn()
diff --git a/ministack/core/router.py b/ministack/core/router.py
index c39d536a..df230b9b 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -156,7 +156,11 @@ SERVICE_PATTERNS = {
},
"kms": {
"target_prefixes": ["TrentService"],
- "host_patterns": [r"kms\."],
+ "host_patterns": [r"kms\."]
+ },
+ "cloudfront": {
+ "host_patterns": [r"cloudfront\."],
+ "credential_scope": "cloudfront",
},
}
@@ -208,6 +212,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
"elasticfilesystem": "elasticfilesystem",
"cloudformation": "cloudformation",
"kms": "kms",
+ "cloudfront": "cloudfront",
}
if svc_name in scope_map:
return scope_map[svc_name]
@@ -402,6 +407,8 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
# 4. Check URL path patterns
path_lower = path.lower()
+ if path_lower.startswith("/2020-05-31/"):
+ return "cloudfront"
if path_lower.startswith("/2013-04-01/"):
return "route53"
if path_lower.startswith("/v2/apis"):
diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.py
new file mode 100644
index 00000000..0533ce76
--- /dev/null
+++ b/ministack/services/cloudfront.py
@@ -0,0 +1,415 @@
+"""
+CloudFront Service Emulator.
+REST/XML API — service credential scope: cloudfront.
+Paths are under /2020-05-31/
+
+Supports:
+ Distributions: CreateDistribution, GetDistribution, GetDistributionConfig,
+ ListDistributions, UpdateDistribution, DeleteDistribution
+ Invalidations: CreateInvalidation, ListInvalidations, GetInvalidation
+"""
+
+import logging
+import random
+import re
+import string
+from datetime import datetime, timezone
+from xml.etree.ElementTree import Element, SubElement, fromstring, tostring
+
+from ministack.core.responses import new_uuid
+
+logger = logging.getLogger("cloudfront")
+
+ACCOUNT_ID = "000000000000"
+NS = "http://cloudfront.amazonaws.com/doc/2020-05-31/"
+
+# ---------------------------------------------------------------------------
+# Path regexes — note: _DIST_CFG_RE must be matched before _DIST_ID_RE
+# ---------------------------------------------------------------------------
+_DIST_RE = re.compile(r"^/2020-05-31/distribution/?$")
+_DIST_CFG_RE = re.compile(r"^/2020-05-31/distribution/([^/]+)/config$")
+_DIST_ID_RE = re.compile(r"^/2020-05-31/distribution/([^/]+)/?$")
+_INV_RE = re.compile(r"^/2020-05-31/distribution/([^/]+)/invalidation/?$")
+_INV_ID_RE = re.compile(r"^/2020-05-31/distribution/([^/]+)/invalidation/([^/]+)$")
+
+# ---------------------------------------------------------------------------
+# In-memory state
+# ---------------------------------------------------------------------------
+_distributions: dict = {} # Id -> distribution record
+_invalidations: dict = {} # distribution_id -> [invalidation record, ...]
+
+
+def reset():
+ _distributions.clear()
+ _invalidations.clear()
+
+
+# ---------------------------------------------------------------------------
+# ID generators — real CloudFront uses 14-char uppercase alphanumeric IDs
+# ---------------------------------------------------------------------------
+_ID_CHARS = string.ascii_uppercase + string.digits
+
+
+def _dist_id() -> str:
+ return "E" + "".join(random.choices(_ID_CHARS, k=13))
+
+
+def _inv_id() -> str:
+ return "I" + "".join(random.choices(_ID_CHARS, k=13))
+
+
+def _now_iso() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
+
+
+# ---------------------------------------------------------------------------
+# XML helpers
+# ---------------------------------------------------------------------------
+
+def _xml_response(root_tag: str, builder_fn, status: int = 200, extra_headers: dict = None) -> tuple:
+ root = Element(root_tag, xmlns=NS)
+ builder_fn(root)
+ body = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(root, encoding="unicode").encode("utf-8")
+ headers = {"Content-Type": "text/xml"}
+ if extra_headers:
+ headers.update(extra_headers)
+ return status, headers, body
+
+
+def _error(code: str, message: str, status: int) -> tuple:
+ root = Element("ErrorResponse", xmlns=NS)
+ err = SubElement(root, "Error")
+ SubElement(err, "Code").text = code
+ SubElement(err, "Message").text = message
+ SubElement(root, "RequestId").text = new_uuid()
+ body = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(root, encoding="unicode").encode("utf-8")
+ return status, {"Content-Type": "text/xml"}, body
+
+
+def _find(el, tag):
+ """Find direct child by local tag name, ignoring namespace prefix."""
+ for child in el:
+ local = child.tag.split("}")[-1] if "}" in child.tag else child.tag
+ if local == tag:
+ return child
+ return None
+
+
+def _text(el, tag, default=""):
+ child = _find(el, tag)
+ return child.text or default if child is not None else default
+
+
+def _parse_body(body: bytes):
+ if not body:
+ return None
+ try:
+ return fromstring(body.decode("utf-8"))
+ except Exception:
+ return None
+
+
+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 _build_distribution_xml(parent, dist):
+ """Append Distribution child elements to parent."""
+ SubElement(parent, "Id").text = dist["Id"]
+ SubElement(parent, "ARN").text = dist["ARN"]
+ SubElement(parent, "Status").text = dist["Status"]
+ SubElement(parent, "LastModifiedTime").text = dist["LastModifiedTime"]
+ SubElement(parent, "InProgressInvalidationBatches").text = "0"
+ SubElement(parent, "DomainName").text = dist["DomainName"]
+ # Re-parse and embed the stored config XML
+ config_el = fromstring(dist["config_xml"])
+ config_el.tag = "DistributionConfig"
+ parent.append(config_el)
+
+
+def _build_invalidation_xml(parent, inv):
+ """Append Invalidation child elements to parent."""
+ SubElement(parent, "Id").text = inv["Id"]
+ SubElement(parent, "Status").text = inv["Status"]
+ SubElement(parent, "CreateTime").text = inv["CreateTime"]
+ batch = SubElement(parent, "InvalidationBatch")
+ paths_el = SubElement(batch, "Paths")
+ items = inv["InvalidationBatch"]["Paths"]["Items"]
+ SubElement(paths_el, "Quantity").text = str(len(items))
+ items_el = SubElement(paths_el, "Items")
+ for p in items:
+ SubElement(items_el, "Path").text = p
+ SubElement(batch, "CallerReference").text = inv["InvalidationBatch"]["CallerReference"]
+
+
+# ---------------------------------------------------------------------------
+# Request dispatcher
+# ---------------------------------------------------------------------------
+
+async def handle_request(method, path, headers, body, query_params):
+ logger.debug("%s %s", method, path)
+
+ m = _DIST_RE.match(path)
+ if m:
+ if method == "POST":
+ return _create_distribution(headers, body)
+ if method == "GET":
+ return _list_distributions()
+
+ m = _DIST_CFG_RE.match(path)
+ if m:
+ dist_id = m.group(1)
+ if method == "GET":
+ return _get_distribution_config(dist_id)
+ if method == "PUT":
+ return _update_distribution(dist_id, headers, body)
+
+ m = _DIST_ID_RE.match(path)
+ if m:
+ dist_id = m.group(1)
+ if method == "GET":
+ return _get_distribution(dist_id)
+ if method == "DELETE":
+ return _delete_distribution(dist_id, headers)
+
+ m = _INV_RE.match(path)
+ if m:
+ dist_id = m.group(1)
+ if method == "POST":
+ return _create_invalidation(dist_id, body)
+ if method == "GET":
+ return _list_invalidations(dist_id)
+
+ m = _INV_ID_RE.match(path)
+ if m:
+ dist_id = m.group(1)
+ inv_id = m.group(2)
+ if method == "GET":
+ return _get_invalidation(dist_id, inv_id)
+
+ return _error("NoSuchResource", f"No route for {method} {path}", 404)
+
+
+# ---------------------------------------------------------------------------
+# Distribution handlers
+# ---------------------------------------------------------------------------
+
+def _create_distribution(headers, body):
+ config_el = _parse_body(body)
+ if config_el is None:
+ return _error("MalformedXML", "The XML document is malformed.", 400)
+
+ if not _text(config_el, "CallerReference"):
+ return _error("InvalidArgument", "CallerReference is required.", 400)
+ if _find(config_el, "Origins") is None:
+ return _error("InvalidArgument", "Origins is required.", 400)
+ if _find(config_el, "DefaultCacheBehavior") is None:
+ return _error("InvalidArgument", "DefaultCacheBehavior is required.", 400)
+
+ dist_id = _dist_id()
+ etag = new_uuid()
+ now = _now_iso()
+
+ dist = {
+ "Id": dist_id,
+ "ARN": f"arn:aws:cloudfront::{ACCOUNT_ID}:distribution/{dist_id}",
+ "Status": "Deployed",
+ "DomainName": f"{dist_id}.cloudfront.net",
+ "LastModifiedTime": now,
+ "ETag": etag,
+ "config_xml": tostring(config_el, encoding="unicode"),
+ "enabled": _get_enabled(config_el),
+ }
+ _distributions[dist_id] = dist
+ _invalidations[dist_id] = []
+
+ logger.info("CreateDistribution id=%s", dist_id)
+
+ def build(root):
+ _build_distribution_xml(root, dist)
+
+ return _xml_response("Distribution", build, status=201, extra_headers={
+ "ETag": etag,
+ "Location": f"/2020-05-31/distribution/{dist_id}",
+ })
+
+
+def _get_distribution(dist_id):
+ dist = _distributions.get(dist_id)
+ if not dist:
+ return _error("NoSuchDistribution", "The specified distribution does not exist.", 404)
+
+ def build(root):
+ _build_distribution_xml(root, dist)
+
+ return _xml_response("Distribution", build, extra_headers={"ETag": dist["ETag"]})
+
+
+def _get_distribution_config(dist_id):
+ dist = _distributions.get(dist_id)
+ if not dist:
+ return _error("NoSuchDistribution", "The specified distribution does not exist.", 404)
+
+ config_el = fromstring(dist["config_xml"])
+ 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")
+ return 200, {"Content-Type": "text/xml", "ETag": dist["ETag"]}, body
+
+
+def _list_distributions():
+ items = list(_distributions.values())
+
+ def build(root):
+ SubElement(root, "Marker").text = ""
+ SubElement(root, "MaxItems").text = "100"
+ SubElement(root, "IsTruncated").text = "false"
+ SubElement(root, "Quantity").text = str(len(items))
+ if items:
+ items_el = SubElement(root, "Items")
+ for dist in items:
+ ds = SubElement(items_el, "DistributionSummary")
+ SubElement(ds, "Id").text = dist["Id"]
+ SubElement(ds, "ARN").text = dist["ARN"]
+ SubElement(ds, "Status").text = dist["Status"]
+ SubElement(ds, "LastModifiedTime").text = dist["LastModifiedTime"]
+ SubElement(ds, "DomainName").text = dist["DomainName"]
+ SubElement(ds, "Enabled").text = str(dist["enabled"]).lower()
+ SubElement(ds, "Comment").text = _text(fromstring(dist["config_xml"]), "Comment")
+
+ return _xml_response("DistributionList", build)
+
+
+def _update_distribution(dist_id, headers, body):
+ dist = _distributions.get(dist_id)
+ if not dist:
+ return _error("NoSuchDistribution", "The specified distribution does not exist.", 404)
+
+ if_match = headers.get("if-match", "")
+ if not if_match:
+ return _error("InvalidIfMatchVersion", "The If-Match version is missing or not valid for the resource.", 400)
+ if if_match != dist["ETag"]:
+ return _error("PreconditionFailed", "The precondition given in one or more of the request-header fields evaluated to false.", 412)
+
+ config_el = _parse_body(body)
+ if config_el is None:
+ return _error("MalformedXML", "The XML document is malformed.", 400)
+
+ new_etag = new_uuid()
+ dist["config_xml"] = tostring(config_el, encoding="unicode")
+ dist["enabled"] = _get_enabled(config_el)
+ dist["ETag"] = new_etag
+ dist["LastModifiedTime"] = _now_iso()
+
+ logger.info("UpdateDistribution id=%s", dist_id)
+
+ def build(root):
+ _build_distribution_xml(root, dist)
+
+ return _xml_response("Distribution", build, extra_headers={"ETag": new_etag})
+
+
+def _delete_distribution(dist_id, headers):
+ dist = _distributions.get(dist_id)
+ if not dist:
+ return _error("NoSuchDistribution", "The specified distribution does not exist.", 404)
+
+ if_match = headers.get("if-match", "")
+ if not if_match:
+ return _error("InvalidIfMatchVersion", "The If-Match version is missing or not valid for the resource.", 400)
+ if if_match != dist["ETag"]:
+ return _error("PreconditionFailed", "The precondition given in one or more of the request-header fields evaluated to false.", 412)
+
+ if dist["enabled"]:
+ return _error("DistributionNotDisabled", "The distribution you are trying to delete has not been disabled.", 409)
+
+ del _distributions[dist_id]
+ _invalidations.pop(dist_id, None)
+
+ logger.info("DeleteDistribution id=%s", dist_id)
+ return 204, {}, b""
+
+
+# ---------------------------------------------------------------------------
+# Invalidation handlers
+# ---------------------------------------------------------------------------
+
+def _create_invalidation(dist_id, body):
+ if dist_id not in _distributions:
+ return _error("NoSuchDistribution", "The specified distribution does not exist.", 404)
+
+ batch_el = _parse_body(body)
+ if batch_el is None:
+ return _error("MalformedXML", "The XML document is malformed.", 400)
+
+ paths_el = _find(batch_el, "Paths")
+ caller_ref = _text(batch_el, "CallerReference")
+
+ path_items = []
+ if paths_el is not None:
+ items_el = _find(paths_el, "Items")
+ if items_el is not None:
+ for child in items_el:
+ if child.text:
+ path_items.append(child.text)
+
+ inv_id = _inv_id()
+ now = _now_iso()
+ inv = {
+ "Id": inv_id,
+ "Status": "Completed",
+ "CreateTime": now,
+ "InvalidationBatch": {
+ "Paths": {"Quantity": len(path_items), "Items": path_items},
+ "CallerReference": caller_ref,
+ },
+ }
+ _invalidations[dist_id].append(inv)
+
+ logger.info("CreateInvalidation dist=%s inv=%s paths=%d", dist_id, inv_id, len(path_items))
+
+ def build(root):
+ _build_invalidation_xml(root, inv)
+
+ return _xml_response("Invalidation", build, status=201, extra_headers={
+ "Location": f"/2020-05-31/distribution/{dist_id}/invalidation/{inv_id}",
+ })
+
+
+def _list_invalidations(dist_id):
+ if dist_id not in _distributions:
+ return _error("NoSuchDistribution", "The specified distribution does not exist.", 404)
+
+ invs = _invalidations.get(dist_id, [])
+
+ def build(root):
+ SubElement(root, "Marker").text = ""
+ SubElement(root, "MaxItems").text = "100"
+ SubElement(root, "IsTruncated").text = "false"
+ SubElement(root, "Quantity").text = str(len(invs))
+ if invs:
+ items_el = SubElement(root, "Items")
+ for inv in invs:
+ summary = SubElement(items_el, "InvalidationSummary")
+ SubElement(summary, "Id").text = inv["Id"]
+ SubElement(summary, "Status").text = inv["Status"]
+ SubElement(summary, "CreateTime").text = inv["CreateTime"]
+
+ return _xml_response("InvalidationList", build)
+
+
+def _get_invalidation(dist_id, inv_id):
+ if dist_id not in _distributions:
+ return _error("NoSuchDistribution", "The specified distribution does not exist.", 404)
+
+ invs = _invalidations.get(dist_id, [])
+ inv = next((i for i in invs if i["Id"] == inv_id), None)
+ if not inv:
+ return _error("NoSuchInvalidation", "The specified invalidation does not exist.", 404)
+
+ def build(root):
+ _build_invalidation_xml(root, inv)
+
+ return _xml_response("Invalidation", build)
diff --git a/tests/conftest.py b/tests/conftest.py
index a0a8293a..1f9bf8c2 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -215,3 +215,7 @@ def sfn_sync():
inject_host_prefix=False,
),
)
+
[email protected](scope="session")
+def cloudfront():
+ return make_client("cloudfront")
diff --git a/tests/test_services.py b/tests/test_services.py
index c65bc273..e37cd5f3 100644
--- a/tests/test_services.py
+++ b/tests/test_services.py
@@ -17254,3 +17254,194 @@ def test_persist_kms_roundtrip():
assert key_id in _kms._keys
assert _kms._keys[key_id]["Description"] == "persist-key"
_kms._keys.pop(key_id)
+
+# ========== CloudFront ==========
+
+_CF_DIST_CONFIG = {
+ "CallerReference": "cf-test-ref-1",
+ "Origins": {
+ "Quantity": 1,
+ "Items": [
+ {
+ "Id": "myS3Origin",
+ "DomainName": "mybucket.s3.amazonaws.com",
+ "S3OriginConfig": {"OriginAccessIdentity": ""},
+ }
+ ],
+ },
+ "DefaultCacheBehavior": {
+ "TargetOriginId": "myS3Origin",
+ "ViewerProtocolPolicy": "redirect-to-https",
+ "ForwardedValues": {
+ "QueryString": False,
+ "Cookies": {"Forward": "none"},
+ },
+ "MinTTL": 0,
+ },
+ "Comment": "test distribution",
+ "Enabled": True,
+}
+
+
+def test_cloudfront_create_distribution(cloudfront):
+ resp = cloudfront.create_distribution(DistributionConfig=_CF_DIST_CONFIG)
+ dist = resp["Distribution"]
+ assert dist["Id"]
+ assert dist["DomainName"].endswith(".cloudfront.net")
+ assert dist["Status"] == "Deployed"
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 201
+
+
+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"}
+ cloudfront.create_distribution(DistributionConfig=cfg_a)
+ cloudfront.create_distribution(DistributionConfig=cfg_b)
+ resp = cloudfront.list_distributions()
+ dist_list = resp["DistributionList"]
+ ids = [d["Id"] for d in dist_list.get("Items", [])]
+ assert len(ids) >= 2
+
+
+def test_cloudfront_get_distribution(cloudfront):
+ cfg = {**_CF_DIST_CONFIG, "CallerReference": "cf-get-1", "Comment": "get-test"}
+ create_resp = cloudfront.create_distribution(DistributionConfig=cfg)
+ dist_id = create_resp["Distribution"]["Id"]
+
+ resp = cloudfront.get_distribution(Id=dist_id)
+ dist = resp["Distribution"]
+ assert dist["Id"] == dist_id
+ assert dist["DomainName"] == f"{dist_id}.cloudfront.net"
+ assert dist["Status"] == "Deployed"
+
+
+def test_cloudfront_get_distribution_config(cloudfront):
+ cfg = {**_CF_DIST_CONFIG, "CallerReference": "cf-getcfg-1", "Comment": "getcfg-test"}
+ create_resp = cloudfront.create_distribution(DistributionConfig=cfg)
+ dist_id = create_resp["Distribution"]["Id"]
+ etag = create_resp["ETag"]
+
+ resp = cloudfront.get_distribution_config(Id=dist_id)
+ assert resp["ETag"] == etag
+ assert resp["DistributionConfig"]["Comment"] == "getcfg-test"
+
+
+def test_cloudfront_update_distribution(cloudfront):
+ cfg = {**_CF_DIST_CONFIG, "CallerReference": "cf-upd-1", "Comment": "before-update"}
+ create_resp = cloudfront.create_distribution(DistributionConfig=cfg)
+ dist_id = create_resp["Distribution"]["Id"]
+ etag = create_resp["ETag"]
+
+ updated_cfg = {**cfg, "CallerReference": "cf-upd-1", "Comment": "after-update"}
+ upd_resp = cloudfront.update_distribution(DistributionConfig=updated_cfg, Id=dist_id, IfMatch=etag)
+ assert upd_resp["Distribution"]["Id"] == dist_id
+ assert upd_resp["ETag"] != etag # new ETag issued
+
+ get_resp = cloudfront.get_distribution_config(Id=dist_id)
+ assert get_resp["DistributionConfig"]["Comment"] == "after-update"
+
+
+def test_cloudfront_update_distribution_etag_mismatch(cloudfront):
+ cfg = {**_CF_DIST_CONFIG, "CallerReference": "cf-etag-mismatch", "Comment": "mismatch-test"}
+ create_resp = cloudfront.create_distribution(DistributionConfig=cfg)
+ dist_id = create_resp["Distribution"]["Id"]
+
+ with pytest.raises(ClientError) as exc:
+ cloudfront.update_distribution(
+ DistributionConfig=cfg, Id=dist_id, IfMatch="wrong-etag-value"
+ )
+ assert exc.value.response["Error"]["Code"] == "PreconditionFailed"
+
+
+def test_cloudfront_delete_distribution(cloudfront):
+ cfg = {**_CF_DIST_CONFIG, "CallerReference": "cf-del-1", "Comment": "delete-test", "Enabled": True}
+ create_resp = cloudfront.create_distribution(DistributionConfig=cfg)
+ dist_id = create_resp["Distribution"]["Id"]
+ etag = create_resp["ETag"]
+
+ # Must disable before deleting
+ disabled_cfg = {**cfg, "Enabled": False}
+ upd_resp = cloudfront.update_distribution(DistributionConfig=disabled_cfg, Id=dist_id, IfMatch=etag)
+ new_etag = upd_resp["ETag"]
+
+ cloudfront.delete_distribution(Id=dist_id, IfMatch=new_etag)
+
+ with pytest.raises(ClientError) as exc:
+ cloudfront.get_distribution(Id=dist_id)
+ assert exc.value.response["Error"]["Code"] == "NoSuchDistribution"
+
+
+def test_cloudfront_delete_enabled_distribution(cloudfront):
+ cfg = {**_CF_DIST_CONFIG, "CallerReference": "cf-del-enabled", "Comment": "del-enabled-test", "Enabled": True}
+ create_resp = cloudfront.create_distribution(DistributionConfig=cfg)
+ dist_id = create_resp["Distribution"]["Id"]
+ etag = create_resp["ETag"]
+
+ with pytest.raises(ClientError) as exc:
+ cloudfront.delete_distribution(Id=dist_id, IfMatch=etag)
+ assert exc.value.response["Error"]["Code"] == "DistributionNotDisabled"
+
+
+def test_cloudfront_get_nonexistent(cloudfront):
+ with pytest.raises(ClientError) as exc:
+ cloudfront.get_distribution(Id="ENONEXISTENT1234")
+ assert exc.value.response["Error"]["Code"] == "NoSuchDistribution"
+
+
+def test_cloudfront_create_invalidation(cloudfront):
+ cfg = {**_CF_DIST_CONFIG, "CallerReference": "cf-inv-1", "Comment": "inv-test"}
+ create_resp = cloudfront.create_distribution(DistributionConfig=cfg)
+ dist_id = create_resp["Distribution"]["Id"]
+
+ inv_resp = cloudfront.create_invalidation(
+ DistributionId=dist_id,
+ InvalidationBatch={
+ "Paths": {"Quantity": 2, "Items": ["/index.html", "/static/*"]},
+ "CallerReference": "inv-ref-1",
+ },
+ )
+ inv = inv_resp["Invalidation"]
+ assert inv["Id"]
+ assert inv["Status"] == "Completed"
+ assert inv_resp["ResponseMetadata"]["HTTPStatusCode"] == 201
+
+
+def test_cloudfront_list_invalidations(cloudfront):
+ cfg = {**_CF_DIST_CONFIG, "CallerReference": "cf-listinv-1", "Comment": "listinv-test"}
+ create_resp = cloudfront.create_distribution(DistributionConfig=cfg)
+ dist_id = create_resp["Distribution"]["Id"]
+
+ cloudfront.create_invalidation(
+ DistributionId=dist_id,
+ InvalidationBatch={"Paths": {"Quantity": 1, "Items": ["/a"]}, "CallerReference": "inv-list-a"},
+ )
+ cloudfront.create_invalidation(
+ DistributionId=dist_id,
+ InvalidationBatch={"Paths": {"Quantity": 1, "Items": ["/b"]}, "CallerReference": "inv-list-b"},
+ )
+
+ resp = cloudfront.list_invalidations(DistributionId=dist_id)
+ inv_list = resp["InvalidationList"]
+ assert inv_list["Quantity"] == 2
+ assert len(inv_list["Items"]) == 2
+
+
+def test_cloudfront_get_invalidation(cloudfront):
+ cfg = {**_CF_DIST_CONFIG, "CallerReference": "cf-getinv-1", "Comment": "getinv-test"}
+ create_resp = cloudfront.create_distribution(DistributionConfig=cfg)
+ dist_id = create_resp["Distribution"]["Id"]
+
+ inv_resp = cloudfront.create_invalidation(
+ DistributionId=dist_id,
+ InvalidationBatch={
+ "Paths": {"Quantity": 1, "Items": ["/getinv-path"]},
+ "CallerReference": "inv-get-ref",
+ },
+ )
+ inv_id = inv_resp["Invalidation"]["Id"]
+
+ get_resp = cloudfront.get_invalidation(DistributionId=dist_id, Id=inv_id)
+ inv = get_resp["Invalidation"]
+ assert inv["Id"] == inv_id
+ assert inv["Status"] == "Completed"
+ assert "/getinv-path" in inv["InvalidationBatch"]["Paths"]["Items"]