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: round-trip CloudFront origin config (#703)
Shushanth Sanjay Kumarbb1d575ca959
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ba0a08fe..75af2a44 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **S3 `GetObjectAcl` and `PutObjectAcl`** — both `?acl` subresource operations are now implemented. `GetObjectAcl` returns the stored policy or, if none has been set, the AWS default of a single `FULL_CONTROL` Grant to the request's account-id owner. `PutObjectAcl` accepts either a canned ACL via the `x-amz-acl` header (`private`, `public-read`, `public-read-write`, `authenticated-read`, `aws-exec-read`, `bucket-owner-read`, `bucket-owner-full-control`) or a full `<AccessControlPolicy>` XML body; invalid canned values return `InvalidArgument` and malformed bodies return `MalformedACLError`. As with retention, legal-hold and bucket policies, the policy is stored and round-tripped but not enforced on the data plane. `NoSuchKey` returned for missing keys, matching the only error modeled in botocore. Reported by @smpial.### Fixed+- **CloudFront distribution origin configuration** — `ListDistributions` now includes origin configuration from the stored distribution config, so custom origins round-trip consistently across create, get, list, and update flows.- **RDS persistence-restore module-import race** — the v1.3.47 restore-respawn threads called `_get_docker()` which was defined further down in the same module, so a thread reaching the lookup before the parser finished raised `NameError: name '_get_docker' is not defined` and stranded the restored instance in `creating`. The `load_state("rds")` block now runs at the bottom of the module, after every helper the restore threads can touch. Reported by @doodaz.---diff --git a/README.md b/README.mdindex 049585cb..4e20d816 100644--- a/README.md+++ b/README.md@@ -375,7 +375,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` 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; 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, 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), ECC (SECG_P256K1, NIST P-256/384/521), and symmetric keys; PKCS1v15, PSS, and ECDSA 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, CreateFunction, DeleteFunction, DescribeFunction, GetFunction, ListFunctions, PublishFunction, UpdateFunction, **KeyValueStore (mgmt)**: CreateKeyValueStore, DescribeKeyValueStore, ListKeyValueStores, UpdateKeyValueStore, DeleteKeyValueStore, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; **CloudFront Functions** are API stubs (in-memory code + DEVELOPMENT/LIVE ETags for Terraform `aws_cloudfront_function`) with `KeyValueStoreAssociations` round-tripped — no `TestFunction`, no viewer-request JS execution at the edge; `UpdateFunction` clears the emulated LIVE stage until `PublishFunction` runs again |+| **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, CreateFunction, DeleteFunction, DescribeFunction, GetFunction, ListFunctions, PublishFunction, UpdateFunction, **KeyValueStore (mgmt)**: CreateKeyValueStore, DescribeKeyValueStore, ListKeyValueStores, UpdateKeyValueStore, DeleteKeyValueStore, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin config round-trip; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; **CloudFront Functions** are API stubs (in-memory code + DEVELOPMENT/LIVE ETags for Terraform `aws_cloudfront_function`) with `KeyValueStoreAssociations` round-tripped — no `TestFunction`, no viewer-request JS execution at the edge; `UpdateFunction` clears the emulated LIVE stage until `PublishFunction` runs again || **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 || **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.pyindex c8e4f58f..a0088a6d 100644--- a/ministack/services/cloudfront.py+++ b/ministack/services/cloudfront.py@@ -183,6 +183,21 @@ def _local_tag_name(el) -> str:return t.split("}")[-1] if "}" in t else t+def _add_xml_block(parent, source_el):+ block = SubElement(parent, _local_tag_name(source_el))+ block.text = source_el.text+ block.attrib.update(source_el.attrib)+ for child in source_el:+ _add_xml_block(block, child)+ return block+++def _add_config_block(parent, config_el, tag):+ child = _find(config_el, tag)+ if child is not None:+ _add_xml_block(parent, child)++def _unwrap_distribution_create_xml(root_el):"""Return ``(DistributionConfig element, Tags element or None)``.@@ -839,6 +854,9 @@ def _list_distributions():SubElement(ds, "DomainName").text = dist["DomainName"]SubElement(ds, "Enabled").text = str(dist["enabled"]).lower()SubElement(ds, "Comment").text = _text(fromstring(dist["config_xml"]), "Comment")+ config_el = fromstring(dist["config_xml"])+ _add_config_block(ds, config_el, "Origins")+ _add_config_block(ds, config_el, "DefaultCacheBehavior")return _xml_response("DistributionList", build)diff --git a/tests/test_cloudfront.py b/tests/test_cloudfront.pyindex 496ca06d..867248b7 100644--- a/tests/test_cloudfront.py+++ b/tests/test_cloudfront.py@@ -1,3 +1,4 @@+import copyimport ioimport jsonimport os@@ -37,6 +38,51 @@ _CF_DIST_CONFIG = {}+def _custom_origin_distribution_config(caller_reference):+ return {+ "CallerReference": caller_reference,+ "Origins": {+ "Quantity": 1,+ "Items": [+ {+ "Id": "custom-origin",+ "DomainName": "origin.example.com",+ "OriginPath": "/app",+ "CustomHeaders": {+ "Quantity": 1,+ "Items": [{"HeaderName": "X-Origin-Test", "HeaderValue": "yes"}],+ },+ "CustomOriginConfig": {+ "HTTPPort": 80,+ "HTTPSPort": 443,+ "OriginProtocolPolicy": "https-only",+ "OriginSslProtocols": {"Quantity": 1, "Items": ["TLSv1.2"]},+ "OriginReadTimeout": 30,+ "OriginKeepaliveTimeout": 5,+ },+ }+ ],+ },+ "DefaultCacheBehavior": {+ "TargetOriginId": "custom-origin",+ "ViewerProtocolPolicy": "redirect-to-https",+ "ForwardedValues": {+ "QueryString": True,+ "Cookies": {"Forward": "all"},+ },+ "MinTTL": 0,+ },+ "Comment": "custom origin distribution",+ "Enabled": True,+ }+++def _first_distribution_origin(config_or_summary):+ origins = config_or_summary["Origins"]+ assert origins["Quantity"] == 1+ return origins["Items"][0]++def test_cloudfront_create_distribution(cloudfront):resp = cloudfront.create_distribution(DistributionConfig=_CF_DIST_CONFIG)dist = resp["Distribution"]@@ -107,6 +153,41 @@ def test_cloudfront_get_distribution_config(cloudfront):assert resp["DistributionConfig"]["OriginGroups"]["Quantity"] == 0+def test_cloudfront_origin_configuration_round_trips(cloudfront):+ cfg = _custom_origin_distribution_config(f"cf-origin-{_uuid_mod.uuid4().hex[:12]}")+ create_resp = cloudfront.create_distribution(DistributionConfig=cfg)+ dist_id = create_resp["Distribution"]["Id"]++ get_resp = cloudfront.get_distribution(Id=dist_id)+ get_origin = _first_distribution_origin(get_resp["Distribution"]["DistributionConfig"])+ assert get_origin["Id"] == "custom-origin"+ assert get_origin["DomainName"] == "origin.example.com"+ assert get_origin["OriginPath"] == "/app"+ assert get_origin["CustomHeaders"]["Items"][0]["HeaderValue"] == "yes"+ assert get_origin["CustomOriginConfig"]["OriginProtocolPolicy"] == "https-only"+ assert get_origin["CustomOriginConfig"]["OriginSslProtocols"]["Items"] == ["TLSv1.2"]++ config_resp = cloudfront.get_distribution_config(Id=dist_id)+ config_origin = _first_distribution_origin(config_resp["DistributionConfig"])+ assert config_origin["CustomOriginConfig"]["HTTPPort"] == 80+ assert config_origin["CustomOriginConfig"]["HTTPSPort"] == 443++ list_resp = cloudfront.list_distributions()+ summary = next(item for item in list_resp["DistributionList"]["Items"] if item["Id"] == dist_id)+ summary_origin = _first_distribution_origin(summary)+ assert summary_origin["CustomOriginConfig"]["OriginReadTimeout"] == 30+ assert summary["DefaultCacheBehavior"]["TargetOriginId"] == "custom-origin"++ updated_cfg = copy.deepcopy(cfg)+ updated_cfg["Origins"]["Items"][0]["OriginPath"] = "/next"+ update_resp = cloudfront.update_distribution(+ DistributionConfig=updated_cfg,+ Id=dist_id,+ IfMatch=create_resp["ETag"],+ )+ assert update_resp["Distribution"]["DistributionConfig"]["Origins"]["Items"][0]["OriginPath"] == "/next"++def test_cloudfront_update_distribution(cloudfront):cfg = {**_CF_DIST_CONFIG, "CallerReference": "cf-upd-1", "Comment": "before-update"}create_resp = cloudfront.create_distribution(DistributionConfig=cfg)