Skip to content

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

feat(cloudfront): associate and disassociate a web ACL with a distribution (#2327)

Kiran Malsettyd4fa166ee6a1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a45a0cad..3ee4a163 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Added
+- **CloudFront — web ACL association for distributions** — `AssociateDistributionWebACL` and `DisassociateDistributionWebACL` set and clear `WebACLId` in the distribution's config, so `GetDistribution`, `GetDistributionConfig` and `ListDistributions` report it, and answer with the new `ETag`. They need the current `If-Match` (`InvalidIfMatchVersion`, `PreconditionFailed`) and a `WebACLArn`, and a missing distribution answers `NoSuchDistribution`. The web ACL is not looked up and is not evaluated. Contributed by @OS-kiranmalsetty.
- **Route 53 — VPC associations for private hosted zones** — `AssociateVPCWithHostedZone`, `DisassociateVPCFromHostedZone` and `ListHostedZonesByVPC` (paged with `MaxItems` and `NextToken`). They refuse a public zone (`PublicZoneVPCAssociation`), a VPC already associated with a zone of the same name (`ConflictingDomainExists`), a VPC the zone doesn't have (404 `VPCAssociationNotFound`) and the zone's last VPC (`LastVPCAssociation`). Contributed by @kharabasz.
### Fixed
diff --git a/README.md b/README.md
index 2f6ebf99..60b72a84 100644
--- a/README.md
+++ b/README.md
@@ -442,7 +442,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, CreateDocumentationPart, GetDocumentationPart, GetDocumentationParts, UpdateDocumentationPart, DeleteDocumentationPart, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags, CreateRequestValidator, GetRequestValidators, GetRequestValidator, UpdateRequestValidator, DeleteRequestValidator | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), non-proxy Lambda (AWS — the handler's output is the response body, Lambda request mapping templates not modeled) and non-proxy `AWS` integrations whose URI targets SQS (`arn:aws:apigateway:{region}:sqs:path/{account}/{queue}`: a request template subset — `$input.body` / `$input.json('…')` / `$input.params('…')` / `$util.urlEncode(…)`, `$context.authorizer` values including Cognito claims, `#set`, comments and interpolated strings — renders the form-encoded SQS Query call, run in the URI's account and region, and the backend result or error is mapped through `integrationResponses`), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost` Host header, path-based `/_aws/execute-api/{apiId}/{stage}/{path}`, or legacy `/restapis/{apiId}/{stage}/_user_request_/{path}`; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; resource tree with `{param}` and `{proxy+}` path matching; routing is on the resource+method pair, so a request the matched resource does not serve falls through to a `{proxy+}` elsewhere in the tree (a methodless intermediate, a CORS-preflight-only node, or any undeclared verb), as it does on AWS; TOKEN and REQUEST Lambda authorizers on the data plane, with the returned IAM policy evaluated against each request's own method ARN and `authorizerResultTtlInSeconds` caching the policy per stage and identity source; JSON Patch for all PATCH operations; state persistence; pin `id` across runs with the `ms-custom-id` tag |
| **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, SetSubnets, SetIpAddressType, SetSecurityGroups, 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`, `authenticate-oidc` actions; data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix |
| **KMS** | CreateKey, ReplicateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateMac, VerifyMac, GenerateDataKey, GenerateDataKeyWithoutPlaintext, GenerateDataKeyPair, GenerateDataKeyPairWithoutPlaintext, GenerateRandom, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, UpdateKeyDescription, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags, GetParametersForImport, ImportKeyMaterial, DeleteImportedKeyMaterial, CreateGrant, ListGrants, RevokeGrant, RetireGrant | 41 actions; multi-Region keys: `CreateKey` with `MultiRegion` mints an `mrk-` key and `ReplicateKey` creates a same-id replica in another region sharing the key material (ciphertext from the primary decrypts against the replica; a primary with live replicas waits in `PendingReplicaDeletion`); CMK specs: RSA (2048/3072/4096), ECC (SECG_P256K1, NIST P-256/384/521), Edwards25519 (`ECC_NIST_EDWARDS25519` — pure Ed25519 via `ED25519_SHA_512` with `MessageType=RAW`; `ED25519_PH_SHA_512` advertised in `SigningAlgorithms` but returns `UnsupportedOperationException` until Ed25519ph lands), HMAC (`HMAC_224`/`HMAC_256`/`HMAC_384`/`HMAC_512` with `KeyUsage=GENERATE_VERIFY_MAC`), and symmetric keys; PKCS1v15, PSS, and ECDSA signing; real RFC 2104 HMAC via `GenerateMac`/`VerifyMac` (4096-byte message cap, `KMSInvalidMacException` on mismatch, `DryRun` supported); envelope encryption, incl. asymmetric data key pairs (`KeyPairSpec` adds RSA_3072); alias resolution; key rotation; key policies; tags; enable/disable/schedule deletion; grants (stored and listed, not evaluated for authorization); 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, CreateMonitoringSubscription, GetMonitoringSubscription, DeleteMonitoringSubscription, CreateFunction, DeleteFunction, DescribeFunction, GetFunction, ListFunctions, PublishFunction, UpdateFunction, **KeyValueStore (mgmt)**: CreateKeyValueStore, DescribeKeyValueStore, ListKeyValueStores, UpdateKeyValueStore, DeleteKeyValueStore, **Policies**: CreateCachePolicy, GetCachePolicy, GetCachePolicyConfig, UpdateCachePolicy, DeleteCachePolicy, ListDistributionsByCachePolicyId, CreateOriginRequestPolicy, GetOriginRequestPolicy, GetOriginRequestPolicyConfig, UpdateOriginRequestPolicy, DeleteOriginRequestPolicy, ListDistributionsByOriginRequestPolicyId, CreateResponseHeadersPolicy, GetResponseHeadersPolicy, GetResponseHeadersPolicyConfig, UpdateResponseHeadersPolicy, DeleteResponseHeadersPolicy, ListDistributionsByResponseHeadersPolicyId, **Public keys / key groups**: CreatePublicKey, GetPublicKey, GetPublicKeyConfig, UpdatePublicKey, DeletePublicKey, ListPublicKeys, CreateKeyGroup, GetKeyGroup, GetKeyGroupConfig, UpdateKeyGroup, DeleteKeyGroup, ListKeyGroups, **SaaS Manager**: CreateConnectionGroup, GetConnectionGroup, GetConnectionGroupByRoutingEndpoint, UpdateConnectionGroup, DeleteConnectionGroup, ListConnectionGroups, CreateDistributionTenant, GetDistributionTenant, GetDistributionTenantByDomain, UpdateDistributionTenant, DeleteDistributionTenant, ListDistributionTenants, ListDistributionTenantsByCustomization, AssociateDistributionTenantWebACL, DisassociateDistributionTenantWebACL, CreateInvalidationForDistributionTenant, GetInvalidationForDistributionTenant, ListInvalidationsForDistributionTenant, VerifyDnsConfiguration, GetManagedCertificateDetails, ListDomainConflicts, UpdateDomainAssociation, ListDistributionsByConnectionMode, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin config round-trip; cache / origin request / response headers policies round-trip their full config with `ETag` / `If-Match` optimistic concurrency; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; the AWS-managed cache (7), origin request (8) and response headers (5) policies are listed and immutable; `CreateMonitoringSubscription` upserts; functions keep DEVELOPMENT/LIVE stages and `KeyValueStoreAssociations`, and `UpdateFunction` clears LIVE until `PublishFunction` runs again; **data plane**: a request to a distribution's `DomainName` (`d` + 13 characters, or `<label>.cloudfront.<MINISTACK_HOST>`) is served through its cache behaviors, policies, `viewer-request` / `viewer-response` CloudFront Functions (on Node) and an S3 or custom origin (read only as the bucket policy allows: OAC, OAI or public), with custom error responses for origin errors; not modelled: caching, WAF, logging, geo restrictions, signed URLs, Lambda@Edge, CORS preflight, and origins at AWS hostnames (502); **SaaS Manager** multi-tenant distributions: `DistributionConfig` round-trips `ConnectionMode` / `TenantConfig`, tenants require a `tenant-only` distribution, CNAMEs are unique across tenants and distribution aliases, a tenant without an explicit connection group lazily gets the account default group, and MiniStack collapses async workflows (tenants deploy, domains activate, DNS verifies, managed certificates issue immediately); key groups validate `Items` against real public keys, and deleting either while still referenced (`PublicKeyInUse` / `ResourceInUse`) is rejected |
+| **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, AssociateDistributionWebACL, DisassociateDistributionWebACL, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, CreateMonitoringSubscription, GetMonitoringSubscription, DeleteMonitoringSubscription, CreateFunction, DeleteFunction, DescribeFunction, GetFunction, ListFunctions, PublishFunction, UpdateFunction, **KeyValueStore (mgmt)**: CreateKeyValueStore, DescribeKeyValueStore, ListKeyValueStores, UpdateKeyValueStore, DeleteKeyValueStore, **Policies**: CreateCachePolicy, GetCachePolicy, GetCachePolicyConfig, UpdateCachePolicy, DeleteCachePolicy, ListDistributionsByCachePolicyId, CreateOriginRequestPolicy, GetOriginRequestPolicy, GetOriginRequestPolicyConfig, UpdateOriginRequestPolicy, DeleteOriginRequestPolicy, ListDistributionsByOriginRequestPolicyId, CreateResponseHeadersPolicy, GetResponseHeadersPolicy, GetResponseHeadersPolicyConfig, UpdateResponseHeadersPolicy, DeleteResponseHeadersPolicy, ListDistributionsByResponseHeadersPolicyId, **Public keys / key groups**: CreatePublicKey, GetPublicKey, GetPublicKeyConfig, UpdatePublicKey, DeletePublicKey, ListPublicKeys, CreateKeyGroup, GetKeyGroup, GetKeyGroupConfig, UpdateKeyGroup, DeleteKeyGroup, ListKeyGroups, **SaaS Manager**: CreateConnectionGroup, GetConnectionGroup, GetConnectionGroupByRoutingEndpoint, UpdateConnectionGroup, DeleteConnectionGroup, ListConnectionGroups, CreateDistributionTenant, GetDistributionTenant, GetDistributionTenantByDomain, UpdateDistributionTenant, DeleteDistributionTenant, ListDistributionTenants, ListDistributionTenantsByCustomization, AssociateDistributionTenantWebACL, DisassociateDistributionTenantWebACL, CreateInvalidationForDistributionTenant, GetInvalidationForDistributionTenant, ListInvalidationsForDistributionTenant, VerifyDnsConfiguration, GetManagedCertificateDetails, ListDomainConflicts, UpdateDomainAssociation, ListDistributionsByConnectionMode, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin config round-trip; cache / origin request / response headers policies round-trip their full config with `ETag` / `If-Match` optimistic concurrency; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; the AWS-managed cache (7), origin request (8) and response headers (5) policies are listed and immutable; `CreateMonitoringSubscription` upserts; functions keep DEVELOPMENT/LIVE stages and `KeyValueStoreAssociations`, and `UpdateFunction` clears LIVE until `PublishFunction` runs again; **data plane**: a request to a distribution's `DomainName` (`d` + 13 characters, or `<label>.cloudfront.<MINISTACK_HOST>`) is served through its cache behaviors, policies, `viewer-request` / `viewer-response` CloudFront Functions (on Node) and an S3 or custom origin (read only as the bucket policy allows: OAC, OAI or public), with custom error responses for origin errors; not modelled: caching, WAF, logging, geo restrictions, signed URLs, Lambda@Edge, CORS preflight, and origins at AWS hostnames (502); **SaaS Manager** multi-tenant distributions: `DistributionConfig` round-trips `ConnectionMode` / `TenantConfig`, tenants require a `tenant-only` distribution, CNAMEs are unique across tenants and distribution aliases, a tenant without an explicit connection group lazily gets the account default group, and MiniStack collapses async workflows (tenants deploy, domains activate, DNS verifies, managed certificates issue immediately); key groups validate `Items` against real public keys, and deleting either while still referenced (`PublicKeyInUse` / `ResourceInUse`) is rejected |
| **CloudFront KeyValueStore (data plane)** | DescribeKeyValueStore, ListKeys, GetKey, PutKey, DeleteKey, UpdateKeys | Separate `cloudfront-keyvaluestore` SDK service (REST/JSON, signing name `cloudfront-keyvaluestore`); ETag-based optimistic concurrency on every mutating op; `UpdateKeys` is atomic (validates whole batch, rejects on first invalid entry); `ListKeys` paginates with opaque `NextToken` capped at 50 results per AWS spec; bridges to the management plane via the shared KVS ARN |
| **CloudTrail** | LookupEvents, CreateTrail, DeleteTrail, GetTrail, DescribeTrails, ListTrails, UpdateTrail, GetTrailStatus, StartLogging, StopLogging, PutEventSelectors, GetEventSelectors, AddTags, ListTags, RemoveTags | In-memory audit log; recording opt-in via `CLOUDTRAIL_RECORDING=1` (or runtime config endpoint); per-account ring buffer (`CLOUDTRAIL_MAX_EVENTS=10000`); `LookupEvents` supports all 8 AWS `LookupAttributes`; `IsLogging` flips on Start/StopLogging; `CreateTrail`/`UpdateTrail` persist `KmsKeyId` (normalized to a key ARN; omitted when unset) so `aws_cloudtrail` converges without drift |
| **Resource Groups** | CreateGroup, GetGroup, DeleteGroup, UpdateGroup, ListGroups, GetGroupQuery, UpdateGroupQuery, GetGroupConfiguration, PutGroupConfiguration, GroupResources, UngroupResources, ListGroupResources, ListGroupingStatuses, SearchResources, Tag, Untag, GetTags, GetAccountSettings, UpdateAccountSettings | 19 of 23 spec ops; tag-sync ops omitted (not exposed by AWS CLI / Terraform); `Group` accepts bare name or full ARN |
diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.py
index 82b26add..dfe8aa10 100644
--- a/ministack/services/cloudfront.py
+++ b/ministack/services/cloudfront.py
@@ -52,6 +52,7 @@ Supports:
VerifyDnsConfiguration, GetManagedCertificateDetails,
ListDomainConflicts, UpdateDomainAssociation,
ListDistributionsByConnectionMode
+ Web ACL: AssociateDistributionWebACL, DisassociateDistributionWebACL
"""
import base64
@@ -128,6 +129,8 @@ _CONN_GROUP_RE = re.compile(r"^/2020-05-31/connection-group/?$")
_CONN_GROUP_ID_RE = re.compile(r"^/2020-05-31/connection-group/(.+?)/?$")
_CONN_GROUPS_LIST_RE = re.compile(r"^/2020-05-31/connection-groups/?$")
_TENANT_RE = re.compile(r"^/2020-05-31/distribution-tenant/?$")
+_DIST_WEBACL_ASSOC_RE = re.compile(r"^/2020-05-31/distribution/([^/]+)/associate-web-acl/?$")
+_DIST_WEBACL_DISASSOC_RE = re.compile(r"^/2020-05-31/distribution/([^/]+)/disassociate-web-acl/?$")
_TENANT_WEBACL_ASSOC_RE = re.compile(r"^/2020-05-31/distribution-tenant/([^/]+)/associate-web-acl/?$")
_TENANT_WEBACL_DISASSOC_RE = re.compile(r"^/2020-05-31/distribution-tenant/([^/]+)/disassociate-web-acl/?$")
_TENANT_INV_RE = re.compile(r"^/2020-05-31/distribution-tenant/([^/]+)/invalidation/?$")
@@ -2656,6 +2659,16 @@ async def handle_request(method, path, headers, body, query_params):
# SaaS Manager routes. Tenant sub-resource routes must be matched before
# the greedy _TENANT_ID_RE / _CONN_GROUP_ID_RE identifier routes.
+ m = _DIST_WEBACL_ASSOC_RE.match(path)
+ if m:
+ if method == "PUT":
+ return _associate_distribution_webacl(m.group(1), headers, body)
+
+ m = _DIST_WEBACL_DISASSOC_RE.match(path)
+ if m:
+ if method == "PUT":
+ return _disassociate_distribution_webacl(m.group(1), headers)
+
m = _TENANT_WEBACL_ASSOC_RE.match(path)
if m:
if method == "PUT":
@@ -4226,6 +4239,72 @@ def _tenant_list_response(tenants, root_tag):
return _xml_response(root_tag, build)
+def _set_distribution_webacl(dist, webacl_id):
+ """Set (or clear, with "") ``WebACLId`` in a stored DistributionConfig, and bump the ETag."""
+ config_el = fromstring(dist["config_xml"])
+ el = _find(config_el, "WebACLId")
+ if el is None:
+ ns = config_el.tag.split("}")[0] + "}" if config_el.tag.startswith("{") else ""
+ el = Element(ns + "WebACLId")
+ # WebACLId follows Restrictions in the DistributionConfig, so SDKs that read in order are not surprised.
+ restrictions = _find(config_el, "Restrictions")
+ children = list(config_el)
+ config_el.insert(children.index(restrictions) + 1 if restrictions is not None else len(children), el)
+ el.text = webacl_id
+ dist["config_xml"] = tostring(config_el, encoding="unicode")
+ dist["ETag"] = new_uuid()
+ dist["LastModifiedTime"] = _now_iso()
+
+
+def _distribution_webacl_precondition(dist, headers):
+ 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,
+ )
+ return None
+
+
+def _associate_distribution_webacl(dist_id, headers, body):
+ dist = _distributions.get(dist_id)
+ if not dist:
+ return _error("NoSuchDistribution", "The specified distribution does not exist.", 404)
+ err = _distribution_webacl_precondition(dist, headers)
+ if err:
+ return err
+ el = _parse_body(body)
+ webacl_arn = _text(el, "WebACLArn") if el is not None else ""
+ if not webacl_arn:
+ return _error("InvalidArgument", "WebACLArn is required.", 400)
+ _set_distribution_webacl(dist, webacl_arn)
+ logger.info("AssociateDistributionWebACL id=%s", dist_id)
+
+ def build(root):
+ SubElement(root, "Id").text = dist_id
+
+ return _xml_response("AssociateDistributionWebACLResult", build, extra_headers={"ETag": dist["ETag"]})
+
+
+def _disassociate_distribution_webacl(dist_id, headers):
+ dist = _distributions.get(dist_id)
+ if not dist:
+ return _error("NoSuchDistribution", "The specified distribution does not exist.", 404)
+ err = _distribution_webacl_precondition(dist, headers)
+ if err:
+ return err
+ _set_distribution_webacl(dist, "")
+ logger.info("DisassociateDistributionWebACL id=%s", dist_id)
+
+ def build(root):
+ SubElement(root, "Id").text = dist_id
+
+ return _xml_response("DisassociateDistributionWebACLResult", build, extra_headers={"ETag": dist["ETag"]})
+
+
def _associate_tenant_webacl(tenant_id, headers, body):
tenant = _find_distribution_tenant(tenant_id)
if not tenant:
diff --git a/tests/test_cloudfront.py b/tests/test_cloudfront.py
index 11e116c1..a0f750b2 100644
--- a/tests/test_cloudfront.py
+++ b/tests/test_cloudfront.py
@@ -3066,3 +3066,33 @@ def test_cloudfront_get_distribution_xml_has_no_namespace_prefixes(cloudfront):
raw = resp.read()
assert b"ns0:" not in raw, "namespace prefixes leaked into the response XML"
assert b"<Origins>" in raw and b"<DefaultCacheBehavior>" in raw
+
+
+def test_cf_distribution_webacl_associate_disassociate(cloudfront):
+ sfx = _uuid_mod.uuid4().hex[:8]
+ created = cloudfront.create_distribution(DistributionConfig=_custom_origin_distribution_config(f"acl-{sfx}"))
+ dist_id = created["Distribution"]["Id"]
+ acl_arn = f"arn:aws:wafv2:us-east-1:000000000000:global/webacl/test/{sfx}"
+
+ assoc = cloudfront.associate_distribution_web_acl(Id=dist_id, WebACLArn=acl_arn, IfMatch=created["ETag"])
+ assert assoc["Id"] == dist_id
+ assert assoc["ETag"] != created["ETag"]
+
+ cfg = cloudfront.get_distribution_config(Id=dist_id)
+ assert cfg["DistributionConfig"]["WebACLId"] == acl_arn
+ assert cfg["ETag"] == assoc["ETag"]
+ assert cloudfront.get_distribution(Id=dist_id)["Distribution"]["DistributionConfig"]["WebACLId"] == acl_arn
+
+ # a stale ETag is refused
+ with pytest.raises(ClientError) as exc:
+ cloudfront.associate_distribution_web_acl(Id=dist_id, WebACLArn=acl_arn, IfMatch=created["ETag"])
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 412
+
+ dis = cloudfront.disassociate_distribution_web_acl(Id=dist_id, IfMatch=assoc["ETag"])
+ assert dis["Id"] == dist_id
+ assert dis["ETag"] != assoc["ETag"]
+ assert cloudfront.get_distribution_config(Id=dist_id)["DistributionConfig"].get("WebACLId", "") == ""
+
+ with pytest.raises(ClientError) as exc:
+ cloudfront.associate_distribution_web_acl(Id="E0000000000000", WebACLArn=acl_arn, IfMatch="x")
+ assert exc.value.response["Error"]["Code"] == "NoSuchDistribution"