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
feat(cloudfront): add OAC CRUD with integration tests (#258)
Yiannis Skarparis22f4dbf183e6
diff --git a/README.md b/README.mdindex d78d3cf9..394f05b3 100644--- a/README.md+++ b/README.md@@ -336,6 +336,7 @@ subnet = ec2.create_subnet(| **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost`; resource tree with `{param}` and `{proxy+}` path matching; JSON Patch for all PATCH operations; state persistence || **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, RegisterTargets, DeregisterTargets, DescribeTargetHealth, AddTags, RemoveTags, DescribeTags | Control plane + data plane; ALB→Lambda live traffic routing; `path-pattern`, `host-header`, `http-method`, `query-string`, `http-header` rule conditions; `forward`, `redirect`, `fixed-response` actions; data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix || **KMS** | CreateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateDataKey, GenerateDataKeyWithoutPlaintext, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags | 27 actions; RSA (2048/4096) and symmetric keys; PKCS1v15 and PSS signing; envelope encryption; alias resolution; key rotation; key policies; tags; enable/disable/schedule deletion; full Terraform `aws_kms_key` compatible; `cryptography` package included in Docker image |+| **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; field validation and name uniqueness enforcement |### CloudFormationdiff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.pyindex 66f1d362..297fd657 100644--- a/ministack/services/cloudfront.py+++ b/ministack/services/cloudfront.py@@ -7,6 +7,10 @@ Supports:Distributions: CreateDistribution, GetDistribution, GetDistributionConfig,ListDistributions, UpdateDistribution, DeleteDistributionInvalidations: CreateInvalidation, ListInvalidations, GetInvalidation+ Origin Access Control (OAC): CreateOriginAccessControl, GetOriginAccessControl,+ GetOriginAccessControlConfig, ListOriginAccessControls,+ UpdateOriginAccessControl, DeleteOriginAccessControl+ Tags: TagResource, UntagResource, ListTagsForResource"""import copy@@ -16,9 +20,10 @@ import randomimport reimport stringfrom datetime import datetime, timezone-from defusedxml.ElementTree import fromstringfrom xml.etree.ElementTree import Element, SubElement, tostring+from defusedxml.ElementTree import fromstring+from ministack.core.persistence import PERSIST_STATE, load_statefrom ministack.core.responses import AccountScopedDict, get_account_id, new_uuid@@ -36,18 +41,25 @@ _INV_RE = re.compile(r"^/2020-05-31/distribution/([^/]+)/invalidation/?$")_INV_ID_RE = re.compile(r"^/2020-05-31/distribution/([^/]+)/invalidation/([^/]+)$")_TAG_RE = re.compile(r"^/2020-05-31/tagging/?$")+# OAC path regexes — note: _OAC_CFG_RE must be matched before _OAC_ID_RE+_OAC_RE = re.compile(r"^/2020-05-31/origin-access-control/?$")+_OAC_CFG_RE = re.compile(r"^/2020-05-31/origin-access-control/([^/]+)/config$")+_OAC_ID_RE = re.compile(r"^/2020-05-31/origin-access-control/([^/]+)/?$")+# ---------------------------------------------------------------------------# In-memory state# ---------------------------------------------------------------------------_distributions = AccountScopedDict() # Id -> distribution record_invalidations = AccountScopedDict() # distribution_id -> [invalidation record, ...]_tags = AccountScopedDict() # arn -> [{"Key": ..., "Value": ...}]+_oacs = AccountScopedDict() # Id -> OAC recorddef reset():_distributions.clear()_invalidations.clear()_tags.clear()+ _oacs.clear()def get_state():@@ -55,6 +67,7 @@ def get_state():"distributions": _distributions,"invalidations": _invalidations,"tags": _tags,+ "oacs": _oacs,})@@ -62,6 +75,7 @@ def restore_state(data):_distributions.update(data.get("distributions", {}))_invalidations.update(data.get("invalidations", {}))_tags.update(data.get("tags", {}))+ _oacs.update(data.get("oacs", {}))_restored = load_state("cloudfront")@@ -154,6 +168,55 @@ def _build_distribution_xml(parent, dist):parent.append(config_el)+_VALID_ORIGIN_TYPES = {"s3", "mediastore", "mediapackagev2", "lambda"}+_VALID_SIGNING_BEHAVIORS = {"always", "never", "no-override"}+_VALID_SIGNING_PROTOCOLS = {"sigv4"}+++def _validate_oac_config(el):+ """Validate OAC config fields from a parsed XML element.++ Returns an error tuple (via _error()) on validation failure, or None on success.+ """+ name = _text(el, "Name")+ if not name:+ return _error("InvalidArgument", "Name is required.", 400)++ origin_type = _text(el, "OriginAccessControlOriginType")+ if origin_type not in _VALID_ORIGIN_TYPES:+ return _error("InvalidArgument", "Invalid OriginAccessControlOriginType value.", 400)++ signing_behavior = _text(el, "SigningBehavior")+ if signing_behavior not in _VALID_SIGNING_BEHAVIORS:+ return _error("InvalidArgument", "Invalid SigningBehavior value.", 400)++ signing_protocol = _text(el, "SigningProtocol")+ if signing_protocol not in _VALID_SIGNING_PROTOCOLS:+ return _error("InvalidArgument", "Invalid SigningProtocol value.", 400)++ return None+++def _build_oac_xml(parent, oac):+ """Append OriginAccessControl child elements (Id + config) to parent."""+ SubElement(parent, "Id").text = oac["Id"]+ config_el = SubElement(parent, "OriginAccessControlConfig")+ SubElement(config_el, "Name").text = oac["Name"]+ SubElement(config_el, "Description").text = oac.get("Description", "")+ SubElement(config_el, "OriginAccessControlOriginType").text = oac["OriginAccessControlOriginType"]+ SubElement(config_el, "SigningBehavior").text = oac["SigningBehavior"]+ SubElement(config_el, "SigningProtocol").text = oac["SigningProtocol"]+++def _build_oac_config_xml(parent, oac):+ """Append only OAC config fields directly to parent element."""+ SubElement(parent, "Name").text = oac["Name"]+ SubElement(parent, "Description").text = oac.get("Description", "")+ SubElement(parent, "OriginAccessControlOriginType").text = oac["OriginAccessControlOriginType"]+ SubElement(parent, "SigningBehavior").text = oac["SigningBehavior"]+ SubElement(parent, "SigningProtocol").text = oac["SigningProtocol"]++def _build_invalidation_xml(parent, inv):"""Append Invalidation child elements to parent."""SubElement(parent, "Id").text = inv["Id"]@@ -225,6 +288,30 @@ async def handle_request(method, path, headers, body, query_params):if method == "POST" and operation == "Untag":return _untag_resource(resource, body)+ # OAC routes+ m = _OAC_RE.match(path)+ if m:+ if method == "POST":+ return _create_oac(headers, body)+ if method == "GET":+ return _list_oacs()++ m = _OAC_CFG_RE.match(path)+ if m:+ oac_id = m.group(1)+ if method == "GET":+ return _get_oac_config(oac_id)+ if method == "PUT":+ return _update_oac(oac_id, headers, body)++ m = _OAC_ID_RE.match(path)+ if m:+ oac_id = m.group(1)+ if method == "GET":+ return _get_oac(oac_id)+ if method == "DELETE":+ return _delete_oac(oac_id, headers)+return _error("NoSuchResource", f"No route for {method} {path}", 404)@@ -496,3 +583,159 @@ def _untag_resource(resource_arn, body):remove_keys.add(child.text or "")_tags[resource_arn] = [t for t in _tags.get(resource_arn, []) if t["Key"] not in remove_keys]return 204, {}, b""+++# ---------------------------------------------------------------------------+# OAC handlers+# ---------------------------------------------------------------------------++def _create_oac(headers, body):+ el = _parse_body(body)+ if el is None:+ return _error("MalformedXML", "The XML document is malformed.", 400)++ validation_err = _validate_oac_config(el)+ if validation_err is not None:+ return validation_err++ name = _text(el, "Name")++ # Check name uniqueness across existing OACs in the account+ for existing in _oacs.values():+ if existing["Name"] == name:+ return _error(+ "OriginAccessControlAlreadyExists",+ "An origin access control with this name already exists.",+ 409,+ )++ oac_id = _dist_id()+ etag = new_uuid()++ oac = {+ "Id": oac_id,+ "Name": name,+ "Description": _text(el, "Description"),+ "OriginAccessControlOriginType": _text(el, "OriginAccessControlOriginType"),+ "SigningBehavior": _text(el, "SigningBehavior"),+ "SigningProtocol": _text(el, "SigningProtocol"),+ "ETag": etag,+ }+ _oacs[oac_id] = oac++ logger.info("CreateOriginAccessControl id=%s name=%s", oac_id, name)++ def build(root):+ _build_oac_xml(root, oac)++ return _xml_response("OriginAccessControl", build, status=201, extra_headers={+ "ETag": etag,+ "Location": f"/2020-05-31/origin-access-control/{oac_id}",+ })+++def _get_oac(oac_id):+ oac = _oacs.get(oac_id)+ if not oac:+ return _error("NoSuchOriginAccessControl", "The specified origin access control does not exist.", 404)++ def build(root):+ _build_oac_xml(root, oac)++ return _xml_response("OriginAccessControl", build, extra_headers={"ETag": oac["ETag"]})+++def _get_oac_config(oac_id):+ oac = _oacs.get(oac_id)+ if not oac:+ return _error("NoSuchOriginAccessControl", "The specified origin access control does not exist.", 404)++ def build(root):+ _build_oac_config_xml(root, oac)++ return _xml_response("OriginAccessControlConfig", build, extra_headers={"ETag": oac["ETag"]})+++def _list_oacs():+ items = list(_oacs.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 oac in items:+ summary = SubElement(items_el, "OriginAccessControlSummary")+ SubElement(summary, "Id").text = oac["Id"]+ SubElement(summary, "Name").text = oac["Name"]+ SubElement(summary, "Description").text = oac.get("Description", "")+ SubElement(summary, "OriginAccessControlOriginType").text = oac["OriginAccessControlOriginType"]+ SubElement(summary, "SigningBehavior").text = oac["SigningBehavior"]+ SubElement(summary, "SigningProtocol").text = oac["SigningProtocol"]++ return _xml_response("OriginAccessControlList", build)+++def _update_oac(oac_id, headers, body):+ oac = _oacs.get(oac_id)+ if not oac:+ return _error("NoSuchOriginAccessControl", "The specified origin access control 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 != oac["ETag"]:+ return _error("PreconditionFailed", "The precondition given in one or more of the request-header fields evaluated to false.", 412)++ el = _parse_body(body)+ if el is None:+ return _error("MalformedXML", "The XML document is malformed.", 400)++ validation_err = _validate_oac_config(el)+ if validation_err is not None:+ return validation_err++ name = _text(el, "Name")++ # Check name uniqueness, excluding the OAC being updated+ for existing in _oacs.values():+ if existing["Id"] != oac_id and existing["Name"] == name:+ return _error(+ "OriginAccessControlAlreadyExists",+ "An origin access control with this name already exists.",+ 409,+ )++ new_etag = new_uuid()+ oac["Name"] = name+ oac["Description"] = _text(el, "Description")+ oac["OriginAccessControlOriginType"] = _text(el, "OriginAccessControlOriginType")+ oac["SigningBehavior"] = _text(el, "SigningBehavior")+ oac["SigningProtocol"] = _text(el, "SigningProtocol")+ oac["ETag"] = new_etag++ logger.info("UpdateOriginAccessControl id=%s name=%s", oac_id, name)++ def build(root):+ _build_oac_xml(root, oac)++ return _xml_response("OriginAccessControl", build, extra_headers={"ETag": new_etag})+++def _delete_oac(oac_id, headers):+ oac = _oacs.get(oac_id)+ if not oac:+ return _error("NoSuchOriginAccessControl", "The specified origin access control 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 != oac["ETag"]:+ return _error("PreconditionFailed", "The precondition given in one or more of the request-header fields evaluated to false.", 412)++ del _oacs[oac_id]++ logger.info("DeleteOriginAccessControl id=%s", oac_id)+ return 204, {}, b""diff --git a/tests/test_cloudfront.py b/tests/test_cloudfront.pyindex 94dc1224..9bae49d1 100644--- a/tests/test_cloudfront.py+++ b/tests/test_cloudfront.py@@ -2,11 +2,14 @@ import ioimport jsonimport osimport time+import urllib.error+import urllib.request+import uuid as _uuid_modimport zipfilefrom urllib.parse import urlparse+import pytestfrom botocore.exceptions import ClientError-import uuid as _uuid_mod_CF_DIST_CONFIG = {"CallerReference": "cf-test-ref-1",@@ -224,3 +227,315 @@ def test_cloudfront_tags(cloudfront):tag_keys = [t["Key"] for t in tags["Tags"]["Items"]]assert "env" in tag_keysassert "team" not in tag_keys+++# ---------------------------------------------------------------------------+# OAC happy-path integration tests+# ---------------------------------------------------------------------------++def _oac_config(name, description="", origin_type="s3", signing_behavior="always", signing_protocol="sigv4"):+ """Helper to build an OAC config dict for boto3."""+ return {+ "Name": name,+ "Description": description,+ "OriginAccessControlOriginType": origin_type,+ "SigningBehavior": signing_behavior,+ "SigningProtocol": signing_protocol,+ }+++def test_oac_create_and_get(cloudfront):+ """Create an OAC and verify all response fields via get."""+ cfg = _oac_config(+ name=f"oac-create-get-{_uuid_mod.uuid4().hex[:8]}",+ description="integration test OAC",+ origin_type="s3",+ signing_behavior="always",+ signing_protocol="sigv4",+ )+ create_resp = cloudfront.create_origin_access_control(OriginAccessControlConfig=cfg)+ assert create_resp["ResponseMetadata"]["HTTPStatusCode"] == 201++ oac = create_resp["OriginAccessControl"]+ oac_id = oac["Id"]+ etag = create_resp["ETag"]++ # Id format: E + 13 alphanumeric+ assert oac_id and len(oac_id) == 14 and oac_id[0] == "E"+ assert etag++ oac_cfg = oac["OriginAccessControlConfig"]+ assert oac_cfg["Name"] == cfg["Name"]+ assert oac_cfg["Description"] == cfg["Description"]+ assert oac_cfg["OriginAccessControlOriginType"] == "s3"+ assert oac_cfg["SigningBehavior"] == "always"+ assert oac_cfg["SigningProtocol"] == "sigv4"++ # Verify via get+ get_resp = cloudfront.get_origin_access_control(Id=oac_id)+ assert get_resp["ResponseMetadata"]["HTTPStatusCode"] == 200+ assert get_resp["ETag"] == etag++ get_oac = get_resp["OriginAccessControl"]+ assert get_oac["Id"] == oac_id+ get_cfg = get_oac["OriginAccessControlConfig"]+ assert get_cfg["Name"] == cfg["Name"]+ assert get_cfg["Description"] == cfg["Description"]+ assert get_cfg["OriginAccessControlOriginType"] == "s3"+ assert get_cfg["SigningBehavior"] == "always"+ assert get_cfg["SigningProtocol"] == "sigv4"+++def test_oac_get_config(cloudfront):+ """Create an OAC, get config only, verify config-only response matches input."""+ cfg = _oac_config(+ name=f"oac-get-config-{_uuid_mod.uuid4().hex[:8]}",+ description="config-only test",+ origin_type="mediastore",+ signing_behavior="no-override",+ signing_protocol="sigv4",+ )+ create_resp = cloudfront.create_origin_access_control(OriginAccessControlConfig=cfg)+ oac_id = create_resp["OriginAccessControl"]["Id"]+ etag = create_resp["ETag"]++ config_resp = cloudfront.get_origin_access_control_config(Id=oac_id)+ assert config_resp["ResponseMetadata"]["HTTPStatusCode"] == 200+ assert config_resp["ETag"] == etag++ returned_cfg = config_resp["OriginAccessControlConfig"]+ assert returned_cfg["Name"] == cfg["Name"]+ assert returned_cfg["Description"] == cfg["Description"]+ assert returned_cfg["OriginAccessControlOriginType"] == "mediastore"+ assert returned_cfg["SigningBehavior"] == "no-override"+ assert returned_cfg["SigningProtocol"] == "sigv4"+++def test_oac_list(cloudfront):+ """Create multiple OACs, list, verify all present with correct Quantity."""+ names = [f"oac-list-{i}-{_uuid_mod.uuid4().hex[:8]}" for i in range(3)]+ created_ids = []+ for name in names:+ resp = cloudfront.create_origin_access_control(+ OriginAccessControlConfig=_oac_config(name=name, description="list test")+ )+ created_ids.append(resp["OriginAccessControl"]["Id"])++ list_resp = cloudfront.list_origin_access_controls()+ assert list_resp["ResponseMetadata"]["HTTPStatusCode"] == 200++ oac_list = list_resp["OriginAccessControlList"]+ quantity = int(oac_list["Quantity"])+ assert quantity >= 3++ listed_ids = [item["Id"] for item in oac_list.get("Items", [])]+ for cid in created_ids:+ assert cid in listed_ids+++def test_oac_update(cloudfront):+ """Create an OAC, update config fields, verify updated fields and new ETag."""+ original_name = f"oac-update-orig-{_uuid_mod.uuid4().hex[:8]}"+ cfg = _oac_config(name=original_name, description="before update", origin_type="s3", signing_behavior="always")+ create_resp = cloudfront.create_origin_access_control(OriginAccessControlConfig=cfg)+ oac_id = create_resp["OriginAccessControl"]["Id"]+ old_etag = create_resp["ETag"]++ updated_name = f"oac-update-new-{_uuid_mod.uuid4().hex[:8]}"+ updated_cfg = _oac_config(+ name=updated_name,+ description="after update",+ origin_type="lambda",+ signing_behavior="no-override",+ )+ update_resp = cloudfront.update_origin_access_control(+ Id=oac_id,+ IfMatch=old_etag,+ OriginAccessControlConfig=updated_cfg,+ )+ assert update_resp["ResponseMetadata"]["HTTPStatusCode"] == 200++ new_etag = update_resp["ETag"]+ assert new_etag != old_etag++ updated_oac = update_resp["OriginAccessControl"]["OriginAccessControlConfig"]+ assert updated_oac["Name"] == updated_name+ assert updated_oac["Description"] == "after update"+ assert updated_oac["OriginAccessControlOriginType"] == "lambda"+ assert updated_oac["SigningBehavior"] == "no-override"+ assert updated_oac["SigningProtocol"] == "sigv4"+++def test_oac_delete(cloudfront):+ """Create an OAC, delete with correct ETag, verify 404 on subsequent get."""+ cfg = _oac_config(name=f"oac-delete-{_uuid_mod.uuid4().hex[:8]}", description="delete test")+ create_resp = cloudfront.create_origin_access_control(OriginAccessControlConfig=cfg)+ oac_id = create_resp["OriginAccessControl"]["Id"]+ etag = create_resp["ETag"]++ del_resp = cloudfront.delete_origin_access_control(Id=oac_id, IfMatch=etag)+ assert del_resp["ResponseMetadata"]["HTTPStatusCode"] == 204++ with pytest.raises(ClientError) as exc:+ cloudfront.get_origin_access_control(Id=oac_id)+ assert exc.value.response["Error"]["Code"] == "NoSuchOriginAccessControl"+++def test_oac_list_empty(cloudfront):+ """List OACs and verify Quantity field exists (may include OACs from other tests)."""+ list_resp = cloudfront.list_origin_access_controls()+ assert list_resp["ResponseMetadata"]["HTTPStatusCode"] == 200++ oac_list = list_resp["OriginAccessControlList"]+ assert "Quantity" in oac_list+ # Quantity should be a non-negative integer (string or int depending on parsing)+ quantity = int(oac_list["Quantity"])+ assert quantity >= 0+++# ---------------------------------------------------------------------------+# OAC error-path integration tests+# ---------------------------------------------------------------------------+++def test_oac_get_nonexistent(cloudfront):+ """Get a non-existent OAC Id, verify 404 NoSuchOriginAccessControl."""+ with pytest.raises(ClientError) as exc:+ cloudfront.get_origin_access_control(Id="ENONEXISTENT1234")+ assert exc.value.response["Error"]["Code"] == "NoSuchOriginAccessControl"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404+++def test_oac_delete_nonexistent(cloudfront):+ """Delete a non-existent OAC Id, verify 404 NoSuchOriginAccessControl."""+ with pytest.raises(ClientError) as exc:+ cloudfront.delete_origin_access_control(Id="ENONEXISTENT1234", IfMatch="any-etag")+ assert exc.value.response["Error"]["Code"] == "NoSuchOriginAccessControl"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404+++def test_oac_update_etag_mismatch(cloudfront):+ """Update an OAC with a wrong ETag, verify 412 PreconditionFailed."""+ cfg = _oac_config(name=f"oac-upd-etag-{_uuid_mod.uuid4().hex[:8]}")+ create_resp = cloudfront.create_origin_access_control(OriginAccessControlConfig=cfg)+ oac_id = create_resp["OriginAccessControl"]["Id"]++ with pytest.raises(ClientError) as exc:+ cloudfront.update_origin_access_control(+ Id=oac_id,+ IfMatch="wrong-etag-value",+ OriginAccessControlConfig=cfg,+ )+ assert exc.value.response["Error"]["Code"] == "PreconditionFailed"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 412+++def test_oac_delete_etag_mismatch(cloudfront):+ """Delete an OAC with a wrong ETag, verify 412 PreconditionFailed."""+ cfg = _oac_config(name=f"oac-del-etag-{_uuid_mod.uuid4().hex[:8]}")+ create_resp = cloudfront.create_origin_access_control(OriginAccessControlConfig=cfg)+ oac_id = create_resp["OriginAccessControl"]["Id"]++ with pytest.raises(ClientError) as exc:+ cloudfront.delete_origin_access_control(Id=oac_id, IfMatch="wrong-etag-value")+ assert exc.value.response["Error"]["Code"] == "PreconditionFailed"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 412+++def test_oac_update_no_if_match(cloudfront):+ """Update an OAC without If-Match header, verify error response."""+ cfg = _oac_config(name=f"oac-upd-noifm-{_uuid_mod.uuid4().hex[:8]}")+ create_resp = cloudfront.create_origin_access_control(OriginAccessControlConfig=cfg)+ oac_id = create_resp["OriginAccessControl"]["Id"]++ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ url = f"{endpoint}/2020-05-31/origin-access-control/{oac_id}/config"+ xml_body = (+ '<OriginAccessControlConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">'+ f"<Name>{cfg['Name']}</Name>"+ "<Description></Description>"+ "<OriginAccessControlOriginType>s3</OriginAccessControlOriginType>"+ "<SigningBehavior>always</SigningBehavior>"+ "<SigningProtocol>sigv4</SigningProtocol>"+ "</OriginAccessControlConfig>"+ )+ req = urllib.request.Request(+ url,+ data=xml_body.encode("utf-8"),+ method="PUT",+ headers={+ "Content-Type": "text/xml",+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20240101/us-east-1/cloudfront/aws4_request, SignedHeaders=host, Signature=fake",+ },+ )+ with pytest.raises(urllib.error.HTTPError) as exc:+ urllib.request.urlopen(req, timeout=5)+ assert exc.value.code == 400+++def test_oac_delete_no_if_match(cloudfront):+ """Delete an OAC without If-Match header, verify error response."""+ cfg = _oac_config(name=f"oac-del-noifm-{_uuid_mod.uuid4().hex[:8]}")+ create_resp = cloudfront.create_origin_access_control(OriginAccessControlConfig=cfg)+ oac_id = create_resp["OriginAccessControl"]["Id"]++ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ url = f"{endpoint}/2020-05-31/origin-access-control/{oac_id}"+ req = urllib.request.Request(+ url,+ method="DELETE",+ headers={+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20240101/us-east-1/cloudfront/aws4_request, SignedHeaders=host, Signature=fake",+ },+ )+ with pytest.raises(urllib.error.HTTPError) as exc:+ urllib.request.urlopen(req, timeout=5)+ assert exc.value.code == 400+++def test_oac_duplicate_name(cloudfront):+ """Create two OACs with the same name, verify 409 OriginAccessControlAlreadyExists."""+ name = f"oac-dup-{_uuid_mod.uuid4().hex[:8]}"+ cfg = _oac_config(name=name)+ cloudfront.create_origin_access_control(OriginAccessControlConfig=cfg)++ with pytest.raises(ClientError) as exc:+ cloudfront.create_origin_access_control(OriginAccessControlConfig=cfg)+ assert exc.value.response["Error"]["Code"] == "OriginAccessControlAlreadyExists"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409+++def test_oac_invalid_origin_type(cloudfront):+ """Create an OAC with an invalid origin type, verify 400 InvalidArgument."""+ cfg = _oac_config(+ name=f"oac-bad-origin-{_uuid_mod.uuid4().hex[:8]}",+ origin_type="invalid-origin",+ )+ with pytest.raises(ClientError) as exc:+ cloudfront.create_origin_access_control(OriginAccessControlConfig=cfg)+ assert exc.value.response["Error"]["Code"] == "InvalidArgument"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+++def test_oac_invalid_signing_behavior(cloudfront):+ """Create an OAC with an invalid signing behavior, verify 400 InvalidArgument."""+ cfg = _oac_config(+ name=f"oac-bad-sign-{_uuid_mod.uuid4().hex[:8]}",+ signing_behavior="invalid-behavior",+ )+ with pytest.raises(ClientError) as exc:+ cloudfront.create_origin_access_control(OriginAccessControlConfig=cfg)+ assert exc.value.response["Error"]["Code"] == "InvalidArgument"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+++def test_oac_invalid_signing_protocol(cloudfront):+ """Create an OAC with an invalid signing protocol, verify 400 InvalidArgument."""+ cfg = _oac_config(+ name=f"oac-bad-proto-{_uuid_mod.uuid4().hex[:8]}",+ signing_protocol="sigv2",+ )+ with pytest.raises(ClientError) as exc:+ cloudfront.create_origin_access_control(OriginAccessControlConfig=cfg)+ assert exc.value.response["Error"]["Code"] == "InvalidArgument"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400