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): apply bucket CORS, Block Public Access and website (#2343)
iot-rocket83cfea6f1a65
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 45e27273..39704e3f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **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+- **CloudFormation — S3 bucket CORS, Block Public Access and website** — `AWS::S3::Bucket` applied only `VersioningConfiguration` and `NotificationConfiguration` and dropped `CorsConfiguration`, `PublicAccessBlockConfiguration` and `WebsiteConfiguration`, so `GetBucketCors`, `GetPublicAccessBlock` and `GetBucketWebsite` found no configuration after a stack create; the three are now stored on create, replaced on update and deleted when an update removes them. Contributed by @iot-rocket.- **S3 — access point Block Public Access** — requests through an access point alias or ARN followed the bucket's Block Public Access settings alone, so a public ACL sent through an access point with the default settings was accepted. An access point's settings other than `BlockPublicPolicy` now count as the bucket's for requests through it, and its `BlockPublicAcls` refuses a public canned ACL, grant header or ACL body with 403 `AccessDenied`. Contributed by @iot-rocket.- **Lambda — Node.js HTTPS to a TLS gateway in the local executor** — with `USE_SSL=1` a Node function's `https` requests to the gateway went out as plain HTTP to its TLS port and the built-in SDK v3 clients always spoke HTTP, so custom resource callbacks and SDK calls failed with `socket hang up`; they now keep TLS on the gateway port, and `https.request` or `https.get` with a URL plus options no longer throws `ERR_INVALID_ARG_TYPE`. Contributed by @iot-rocket.- **Lambda — Node.js custom resource callbacks in the Docker executor under `USE_SSL`** — the Node shim kept the port of an https request to the gateway when `USE_SSL=1`, so a `cfn-response` or CDK style `ResponseURL` PUT (no port, or 443) went to port 443 and the stack waited out `ServiceTimeout`; it now goes to the gateway port over TLS, and other explicit ports are kept. Contributed by @iot-rocket.diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex df80f60e..56ac9d44 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -1404,6 +1404,82 @@ def _s3_apply_notification(name, notif):)+def _s3_cors_xml(cors):+ """A ``CorsConfiguration`` as the PutBucketCors body."""+ from xml.etree.ElementTree import Element, SubElement, tostring++ root = Element("CORSConfiguration", xmlns=_s3.S3_NS)+ for rule in cors.get("CorsRules") or []:+ rule_el = SubElement(root, "CORSRule")+ if rule.get("Id"):+ SubElement(rule_el, "ID").text = str(rule["Id"])+ for prop, tag in (("AllowedHeaders", "AllowedHeader"), ("AllowedMethods", "AllowedMethod"),+ ("AllowedOrigins", "AllowedOrigin"), ("ExposedHeaders", "ExposeHeader")):+ for value in rule.get(prop) or []:+ SubElement(rule_el, tag).text = str(value)+ # CloudFormation stores 0 when the rule has no MaxAge.+ SubElement(rule_el, "MaxAgeSeconds").text = str(int(rule.get("MaxAge") or 0))+ return tostring(root, encoding="utf-8")+++def _s3_public_access_block_xml(pab):+ """A ``PublicAccessBlockConfiguration`` as the PutPublicAccessBlock body; absent settings are off."""+ from xml.etree.ElementTree import Element, SubElement, tostring++ root = Element("PublicAccessBlockConfiguration", xmlns=_s3.S3_NS)+ for field in ("BlockPublicAcls", "IgnorePublicAcls", "BlockPublicPolicy", "RestrictPublicBuckets"):+ SubElement(root, field).text = str(_cfn_bool(pab.get(field, False))).lower()+ return tostring(root, encoding="utf-8")+++def _s3_website_xml(website):+ """A ``WebsiteConfiguration`` as the PutBucketWebsite body."""+ from xml.etree.ElementTree import Element, SubElement, tostring++ def _fields(parent, tag, source, names):+ el = SubElement(parent, tag)+ for name in names:+ if source.get(name) is not None:+ SubElement(el, name).text = str(source[name])+ return el++ root = Element("WebsiteConfiguration", xmlns=_s3.S3_NS)+ if website.get("RedirectAllRequestsTo"):+ _fields(root, "RedirectAllRequestsTo", website["RedirectAllRequestsTo"], ("HostName", "Protocol"))+ if website.get("IndexDocument"):+ SubElement(SubElement(root, "IndexDocument"), "Suffix").text = str(website["IndexDocument"])+ if website.get("ErrorDocument"):+ SubElement(SubElement(root, "ErrorDocument"), "Key").text = str(website["ErrorDocument"])+ rules = website.get("RoutingRules") or []+ if rules:+ rules_el = SubElement(root, "RoutingRules")+ for rule in rules:+ rule_el = SubElement(rules_el, "RoutingRule")+ if rule.get("RoutingRuleCondition"):+ _fields(rule_el, "Condition", rule["RoutingRuleCondition"],+ ("HttpErrorCodeReturnedEquals", "KeyPrefixEquals"))+ _fields(rule_el, "Redirect", rule.get("RedirectRule") or {},+ ("HostName", "HttpRedirectCode", "Protocol", "ReplaceKeyPrefixWith", "ReplaceKeyWith"))+ return tostring(root, encoding="utf-8")+++_S3_BUCKET_CONFIGURATIONS = (+ ("CorsConfiguration", _s3_cors_xml, _s3._put_bucket_cors, _s3._delete_bucket_cors),+ ("PublicAccessBlockConfiguration", _s3_public_access_block_xml,+ _s3._put_public_access_block, _s3._delete_public_access_block),+ ("WebsiteConfiguration", _s3_website_xml, _s3._put_bucket_website, _s3._delete_bucket_website),+)+++def _s3_apply_configurations(name, props, old_props=None):+ """Store the CORS, Block Public Access and website properties through the S3 API; a dropped one is deleted."""+ for prop, to_xml, put, delete in _S3_BUCKET_CONFIGURATIONS:+ if prop in props:+ put(name, to_xml(props[prop] or {}))+ elif old_props and prop in old_props:+ delete(name)++# ---------------------------------------------------------------------------# S3 Multi-Region Access Point# ---------------------------------------------------------------------------@@ -1599,6 +1675,7 @@ def _s3_create(logical_id, props, stack_name):_s3._bucket_versioning[name] = "Enabled"if "NotificationConfiguration" in props:_s3_apply_notification(name, props["NotificationConfiguration"])+ _s3_apply_configurations(name, props)return name, _s3_attrs(name)@@ -1622,6 +1699,7 @@ def _s3_update(physical_id, old_props, new_props, stack_name):elif "NotificationConfiguration" in old_props:# Property removed on update — clear the configuration, as AWS does._s3._bucket_notifications.pop(name, None)+ _s3_apply_configurations(name, new_props, old_props)else:return _s3_create(name, new_props, stack_name)return name, _s3_attrs(name)@@ -1661,6 +1739,7 @@ def _s3_delete(physical_id, props):_s3._bucket_encryption.pop(physical_id, None)_s3._bucket_lifecycle.pop(physical_id, None)_s3._bucket_cors.pop(physical_id, None)+ _s3._bucket_websites.pop(physical_id, None)_s3._bucket_acl.pop(physical_id, None)_s3._bucket_notifications.pop(physical_id, None)diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex ff10b696..9844f1bb 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -819,6 +819,101 @@ def test_cfn_s3_bucket_notification_configuration(cfn, s3, sqs):_wait_stack(cfn, "cfn-notif")+def test_cfn_s3_bucket_cors_public_access_block_and_website(cfn, s3):+ """AWS::S3::Bucket CorsConfiguration, PublicAccessBlockConfiguration and+ WebsiteConfiguration reach GetBucketCors, GetPublicAccessBlock and+ GetBucketWebsite in the S3 API's shape, the template's BlockPublicPolicy+ refuses a public bucket policy, an update replaces each one and removing a+ property deletes it."""+ bucket = "cfn-s3-configs-bucket"+ created = {+ "CorsConfiguration": {"CorsRules": [+ {"Id": "rule-z", "AllowedMethods": ["GET", "PUT"], "AllowedOrigins": ["https://a.example"],+ "AllowedHeaders": ["*"], "ExposedHeaders": ["ETag"], "MaxAge": 300},+ {"AllowedMethods": ["POST"], "AllowedOrigins": ["*"]},+ ]},+ "PublicAccessBlockConfiguration": {+ "BlockPublicAcls": True, "IgnorePublicAcls": False,+ "BlockPublicPolicy": True, "RestrictPublicBuckets": False,+ },+ "WebsiteConfiguration": {+ "IndexDocument": "index.html",+ "ErrorDocument": "error.html",+ "RoutingRules": [{+ "RoutingRuleCondition": {"KeyPrefixEquals": "docs/"},+ "RedirectRule": {"ReplaceKeyPrefixWith": "documents/", "HttpRedirectCode": "301"},+ }],+ },+ }+ changed = {+ "CorsConfiguration": {"CorsRules": [+ {"Id": "rule-y", "AllowedMethods": ["HEAD"], "AllowedOrigins": ["https://b.example"]},+ ]},+ "PublicAccessBlockConfiguration": {"BlockPublicAcls": False, "RestrictPublicBuckets": True},+ "WebsiteConfiguration": {"RedirectAllRequestsTo": {"HostName": "example.com", "Protocol": "https"}},+ }++ def template(configs):+ return json.dumps({+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {"Bucket": {"Type": "AWS::S3::Bucket",+ "Properties": {"BucketName": bucket, **configs}}},+ })++ def error_code(call):+ with pytest.raises(ClientError) as exc:+ call(Bucket=bucket)+ return exc.value.response["Error"]["Code"]++ cfn.create_stack(StackName="cfn-s3-configs", TemplateBody=template(created))+ assert _wait_stack(cfn, "cfn-s3-configs")["StackStatus"] == "CREATE_COMPLETE"+ # A rule without MaxAge reads back with MaxAgeSeconds 0.+ assert s3.get_bucket_cors(Bucket=bucket)["CORSRules"] == [+ {"ID": "rule-z", "AllowedHeaders": ["*"], "AllowedMethods": ["GET", "PUT"],+ "AllowedOrigins": ["https://a.example"], "ExposeHeaders": ["ETag"], "MaxAgeSeconds": 300},+ {"AllowedMethods": ["POST"], "AllowedOrigins": ["*"], "MaxAgeSeconds": 0},+ ]+ assert s3.get_public_access_block(Bucket=bucket)["PublicAccessBlockConfiguration"] == {+ "BlockPublicAcls": True, "IgnorePublicAcls": False,+ "BlockPublicPolicy": True, "RestrictPublicBuckets": False,+ }+ public_policy = json.dumps({"Version": "2012-10-17", "Statement": [{+ "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": f"arn:aws:s3:::{bucket}/*"}]})+ with pytest.raises(ClientError) as exc:+ s3.put_bucket_policy(Bucket=bucket, Policy=public_policy)+ assert exc.value.response["Error"]["Code"] == "AccessDenied"+ website = s3.get_bucket_website(Bucket=bucket)+ assert website["IndexDocument"] == {"Suffix": "index.html"}+ assert website["ErrorDocument"] == {"Key": "error.html"}+ assert website["RoutingRules"] == [{+ "Condition": {"KeyPrefixEquals": "docs/"},+ "Redirect": {"HttpRedirectCode": "301", "ReplaceKeyPrefixWith": "documents/"},+ }]++ cfn.update_stack(StackName="cfn-s3-configs", TemplateBody=template(changed))+ assert _wait_stack(cfn, "cfn-s3-configs")["StackStatus"] == "UPDATE_COMPLETE"+ assert s3.get_bucket_cors(Bucket=bucket)["CORSRules"] == [+ {"ID": "rule-y", "AllowedMethods": ["HEAD"], "AllowedOrigins": ["https://b.example"], "MaxAgeSeconds": 0},+ ]+ # Settings the template leaves out are off.+ assert s3.get_public_access_block(Bucket=bucket)["PublicAccessBlockConfiguration"] == {+ "BlockPublicAcls": False, "IgnorePublicAcls": False,+ "BlockPublicPolicy": False, "RestrictPublicBuckets": True,+ }+ website = s3.get_bucket_website(Bucket=bucket)+ assert website["RedirectAllRequestsTo"] == {"HostName": "example.com", "Protocol": "https"}+ assert "IndexDocument" not in website and "RoutingRules" not in website++ cfn.update_stack(StackName="cfn-s3-configs", TemplateBody=template({}))+ assert _wait_stack(cfn, "cfn-s3-configs")["StackStatus"] == "UPDATE_COMPLETE"+ assert error_code(s3.get_bucket_cors) == "NoSuchCORSConfiguration"+ assert error_code(s3.get_public_access_block) == "NoSuchPublicAccessBlockConfiguration"+ assert error_code(s3.get_bucket_website) == "NoSuchWebsiteConfiguration"++ cfn.delete_stack(StackName="cfn-s3-configs")+ _wait_stack(cfn, "cfn-s3-configs")++def test_cfn_iot_and_cognito_role_attachment(cfn, iot_client, cognito_identity):"""AWS::IoT::ThingType, AWS::IoT::Policy, andAWS::Cognito::IdentityPoolRoleAttachment provision onto their real services