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): apply custom error responses on the data plane (#2069)
Jeff Heller25d69a5912d0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 335f9531..19df42ee 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **IoT — `https://<endpointAddress>` verifies under `USE_SSL=1`** — `DescribeEndpoint` hands out `<prefix>-ats.iot.<region>.<MINISTACK_HOST>` and `<prefix>.credentials.iot.<region>.<MINISTACK_HOST>`, which SDKs dial over HTTPS as on AWS, but the generated gateway certificate did not name them, so the handshake failed hostname verification. The certificate now carries `*.iot.<region>.<MINISTACK_HOST>` and `*.credentials.iot.<region>.<MINISTACK_HOST>` for every region, and a cached certificate without them is regenerated. Contributed by @iot-rocket.### Added+- **CloudFront — custom error responses on the data plane** — a distribution's `CustomErrorResponses` were stored but never applied, so an origin error reached the viewer unchanged. When the origin answers a configured `ErrorCode`, the data plane now fetches `ResponsePagePath` through the cache behavior that path matches and returns it with `ResponseCode`; a page that cannot be fetched is answered with the status its origin returned, as the Developer Guide describes. `ErrorCachingMinTTL` is stored only, since the data plane does not cache.- **IoT — job templates and `AWS::IoT::JobTemplate`** — `CreateJobTemplate`, `DescribeJobTemplate`, `ListJobTemplates` and `DeleteJobTemplate` were missing, so a `jobTemplateArn` could not be created or used. Templates now store a document or a `documentSource` (not fetched, like `CreateJob`'s), every job configuration member, maintenance windows and tags, can be copied from a job through `jobArn`, list newest first with `maxResults` / `nextToken` paging, and answer AWS's errors and messages. `CreateJob` with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a member the request names replaces the template's. CloudFormation creates and deletes `AWS::IoT::JobTemplate` (Ref is the id, `Fn::GetAtt` `Arn`); every property is create-only, so an update under the same `JobTemplateId` fails with AWS's custom-name sentence and a new id replaces the template. Contributed by @iot-rocket.### Fixeddiff --git a/README.md b/README.mdindex 7af45142..29ad48fb 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, mapping templates not modeled), 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); not modelled: caching, WAF, logging, geo restrictions, custom error pages, 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, 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.pyindex f59a3883..923190e1 100644--- a/ministack/services/cloudfront.py+++ b/ministack/services/cloudfront.py@@ -4665,11 +4665,23 @@ def parse_distribution_dataplane_config(dist: dict) -> dict:if _local_tag_name(it) == "CacheBehavior":ordered_behaviors.append(_dataplane_behavior(it, _text(it, "PathPattern")))+ custom_error_responses = {}+ errors_el = _find(config_el, "CustomErrorResponses")+ items_el = _find(errors_el, "Items") if errors_el is not None else None+ if items_el is not None:+ for it in items_el:+ # AWS takes ResponsePagePath and ResponseCode only together; ErrorCachingMinTTL alone sets no page.+ if _local_tag_name(it) == "CustomErrorResponse" and _text(it, "ResponsePagePath") and _text(it, "ResponseCode"):+ custom_error_responses[int(_text(it, "ErrorCode"))] = {+ "page": _text(it, "ResponsePagePath"), "response_code": int(_text(it, "ResponseCode")),+ }+return {"default_root_object": _opt_text(config_el, "DefaultRootObject") or "","origins": origins,"default_behavior": default_behavior,"ordered_behaviors": ordered_behaviors,+ "custom_error_responses": custom_error_responses,}diff --git a/ministack/services/cloudfront_dataplane.py b/ministack/services/cloudfront_dataplane.pyindex 26de44b7..11cdbe3a 100644--- a/ministack/services/cloudfront_dataplane.py+++ b/ministack/services/cloudfront_dataplane.py@@ -2,7 +2,7 @@# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""CloudFront data plane: serves viewer requests to ``<label>.cloudfront.net`` / ``<label>.cloudfront.<MINISTACK_HOST>``.-Not modelled: caching, WAF, logging, geo restrictions, custom error pages, signed URLs and cookies,+Not modelled: caching, WAF, logging, geo restrictions, signed URLs and cookies,Lambda@Edge, CORS preflight, synthetic ``CloudFront-Viewer-*`` headers, origins at AWS hostnames (502)."""@@ -600,6 +600,21 @@ def _serve_s3_origin(origin: dict, method: str, uri: str, headers: dict, dist_ar# ---------------------------------------------------------------------------+async def _fetch_from_origin(origin: dict, method: str, uri: str, query_string: str, headers: dict, body: bytes,+ viewer_is_https: bool, client_ip: str, viewer_xff: str, dist_arn: str) -> tuple:+ """(status, reason, headers, body) from an S3 or custom origin; raises OriginTimeout / OriginUnreachable."""+ if origin.get("s3_bucket"):+ status, header_pairs, data = await run_offloop(_serve_s3_origin, origin, method, uri, headers, dist_arn)+ pairs = header_pairs.items() if isinstance(header_pairs, dict) else header_pairs+ return status, http.client.responses.get(status, ""), _multidict_from_pairs(pairs), data+ # The origin may be MiniStack's own gateway, so the call must be reentrant.+ status, reason, header_pairs, data = await run_reentrant(+ _forward_to_origin, origin, method, (origin.get("origin_path") or "") + uri, query_string, headers, body,+ viewer_is_https, client_ip, viewer_xff,+ )+ return status, reason, _multidict_from_pairs(header_pairs), data++def _multidict_from_pairs(pairs) -> dict:out: dict = {}for name, value in pairs:@@ -797,28 +812,33 @@ async def handle_request(dist: dict, method: str, path: str, raw_uri: str, raw_qquote_via=quote,)- if origin.get("s3_bucket"):- status, origin_headers_list, origin_body = await run_offloop(- _serve_s3_origin, origin, method, request_uri, fwd_headers, dist.get("ARN", ""),+ try:+ status, reason, origin_headers, origin_body = await _fetch_from_origin(+ origin, method, request_uri, forward_qs, fwd_headers, body, viewer_is_https,+ client_ip, request_headers.get("x-forwarded-for", ""), dist.get("ARN", ""),)- reason = http.client.responses.get(status, "")- origin_headers = _multidict_from_pairs(origin_headers_list.items() if isinstance(origin_headers_list, dict)- else origin_headers_list)- else:- full_uri = (origin.get("origin_path") or "") + request_uri- try:- # The origin may be MiniStack's own gateway, so the call must be reentrant.- status, reason, origin_headers_list, origin_body = await run_reentrant(- _forward_to_origin, origin, method, full_uri, forward_qs, fwd_headers, body, viewer_is_https,- client_ip, request_headers.get("x-forwarded-for", ""),+ origin_status = status+ error_response = parsed["custom_error_responses"].get(status)+ if error_response:+ # The page is requested through the cache behavior its path matches (Developer Guide,+ # "Store objects and custom error pages in different locations").+ origin = parsed["origins"].get(_match_behavior(parsed, error_response["page"])["target_origin_id"])+ if origin is None:+ return _cf_error_response(502, "The request could not be satisfied.", _ERROR_X_CACHE)+ status, reason, origin_headers, origin_body = await _fetch_from_origin(+ origin, "GET", error_response["page"], "", {"user-agent": "Amazon CloudFront"}, b"",+ viewer_is_https, client_ip, "", dist.get("ARN", ""),)- except OriginTimeout:- logger.warning("Origin timed out for distribution=%s origin=%s", dist_id, origin["domain_name"])- return _cf_error_response(504, "The request could not be satisfied.", _ERROR_X_CACHE)- except OriginUnreachable:- logger.warning("Origin unreachable for distribution=%s origin=%s", dist_id, origin["domain_name"])- return _cf_error_response(502, "The request could not be satisfied.", _ERROR_X_CACHE)- origin_headers = _multidict_from_pairs(origin_headers_list)+ # An unavailable page is answered with the status its origin returned (Developer Guide,+ # "Generate custom error responses").+ if status < 400:+ status = error_response["response_code"]+ except OriginTimeout:+ logger.warning("Origin timed out for distribution=%s origin=%s", dist_id, origin["domain_name"])+ return _cf_error_response(504, "The request could not be satisfied.", _ERROR_X_CACHE)+ except OriginUnreachable:+ logger.warning("Origin unreachable for distribution=%s origin=%s", dist_id, origin["domain_name"])+ return _cf_error_response(502, "The request could not be satisfied.", _ERROR_X_CACHE)origin_headers = _strip_hop_by_hop_response_headers(origin_headers)policy_cfg = cloudfront.response_headers_policy_config(behavior.get("response_headers_policy_id"))@@ -829,7 +849,7 @@ async def handle_request(dist: dict, method: str, path: str, raw_uri: str, raw_qresponse_function_arn = behavior["functions"].get("viewer-response")# No viewer-response function runs when the origin answers 400 or above.- if response_function_arn and status < 400:+ if response_function_arn and origin_status < 400:event = _build_function_event("viewer-response", dist_id, dist_domain, request_id,method, request_uri, request_query, headers, client_ip,diff --git a/tests/test_cloudfront_dataplane.py b/tests/test_cloudfront_dataplane.pyindex 646655cd..3075553b 100644--- a/tests/test_cloudfront_dataplane.py+++ b/tests/test_cloudfront_dataplane.py@@ -923,6 +923,64 @@ def test_s3_origin_missing_key_returns_access_denied(cf_s3_stack):assert b"<Code>AccessDenied</Code>" in body+def _s3_oac_origin(origin_id: str, bucket: str) -> dict:+ return {"Id": origin_id, "DomainName": f"{bucket}.s3.amazonaws.com",+ "S3OriginConfig": {"OriginAccessIdentity": ""}, "OriginAccessControlId": "test-oac-id"}+++def _custom_error_dist(cloudfront, suffix: str, origins: list, error_responses: list, behaviors: list | None = None):+ return cloudfront.create_distribution(DistributionConfig={+ "CallerReference": f"cf-dp-errors-{suffix}", "Comment": "", "Enabled": True,+ "Origins": {"Quantity": len(origins), "Items": origins},+ "DefaultCacheBehavior": {"TargetOriginId": origins[0]["Id"], "ViewerProtocolPolicy": "allow-all",+ "CachePolicyId": _CACHING_DISABLED},+ "CacheBehaviors": {"Quantity": len(behaviors or []), "Items": behaviors or []},+ "CustomErrorResponses": {"Quantity": len(error_responses), "Items": error_responses},+ })["Distribution"]+++def test_custom_error_response_serves_the_page_with_the_configured_status(cloudfront, s3):+ """A single-page app: S3 answers 403 for a client route, CloudFront serves /index.html with 200."""+ suffix = _uuid_mod.uuid4().hex[:10]+ bucket = f"cf-dp-spa-{suffix}"+ s3.create_bucket(Bucket=bucket)+ s3.put_object(Bucket=bucket, Key="index.html", Body=b"<html>app</html>", ContentType="text/html")+ dist = _custom_error_dist(cloudfront, suffix, [_s3_oac_origin("site", bucket)], [+ {"ErrorCode": 403, "ResponsePagePath": "/index.html", "ResponseCode": "200", "ErrorCachingMinTTL": 10},+ ])+ s3.put_bucket_policy(Bucket=bucket, Policy=json.dumps({"Statement": [{+ "Effect": "Allow", "Principal": {"Service": "cloudfront.amazonaws.com"},+ "Action": "s3:GetObject", "Resource": f"arn:aws:s3:::{bucket}/*",+ "Condition": {"StringEquals": {"AWS:SourceArn": dist["ARN"]}},+ }]}))++ status, headers, body = _get(dist["DomainName"], "/auth/callback")+ assert status == 200+ assert body == b"<html>app</html>"+ assert headers.get("Content-Type") == "text/html"+++def test_unavailable_custom_error_page_answers_the_status_its_origin_returned(cloudfront, s3, cf_backend):+ """The Developer Guide's example ("Generate custom error responses"): the custom origin answers 500 and the+ page is missing from its S3 bucket, so the viewer gets S3's status, neither 500 nor the configured 200."""+ suffix = _uuid_mod.uuid4().hex[:10]+ pages = f"cf-dp-pages-{suffix}"+ s3.create_bucket(Bucket=pages)+ dist = _custom_error_dist(+ cloudfront, suffix,+ [{"Id": "api", "DomainName": cf_backend["origin_domain"], "CustomOriginConfig": {+ "HTTPPort": int(GATEWAY_PORT), "HTTPSPort": 443, "OriginProtocolPolicy": "http-only"}},+ _s3_oac_origin("pages", pages)],+ [{"ErrorCode": 500, "ResponsePagePath": "/errors/500.html", "ResponseCode": "200"}],+ [{"PathPattern": "/errors/*", "TargetOriginId": "pages", "ViewerProtocolPolicy": "allow-all",+ "CachePolicyId": _CACHING_DISABLED}],+ )++ status, _headers, body = _get(dist["DomainName"], "/status/500")+ assert status == 403+ assert b"<Code>AccessDenied</Code>" in body++# ---------------------------------------------------------------------------# Percent-encoding fidelity (CloudFront Developer Guide, "Restrictions on all# edge functions" > "URI, query string, and headers encoding").