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): VPC origins (#2353)
Kacper Harabasz7a96599448e6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0c906138..de680a4d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **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 `EntityNotFound`; `AssociateDistributionWebACL` returns the `WebACLArn`. The web ACL is not looked up and is not evaluated. Contributed by @OS-kiranmalsetty.- **Cognito — auth events** — `AdminListUserAuthEvents` always answered an empty list; on a pool with threat protection on (`AdvancedSecurityMode` `AUDIT` or `ENFORCED`), password, SRP and admin sign-ins, their MFA answers and password changes are now logged as `SignIn` and `PasswordChange` events with the caller's address, listed newest first with `MaxResults`/`NextToken` paging, and `AdminUpdateAuthEventFeedback` and `UpdateAuthEventFeedback` are implemented. Contributed by @iot-rocket.- **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.+- **CloudFront — VPC origins** — `CreateVpcOrigin`, `GetVpcOrigin`, `UpdateVpcOrigin`, `DeleteVpcOrigin` and `ListVpcOrigins` replace the empty `ListVpcOrigins` stub, so Terraform's `aws_cloudfront_vpc_origin` and a distribution's `vpc_origin_config` apply. As on AWS, a create, update or delete answers `Deploying`; MiniStack then finishes it at once, so the next read shows `Deployed` with the next `ETag`, or 404 after a delete. Names are unique per account, endpoints are not, and an origin a distribution names can't be deleted or changed. Validation, its order, the `TLSv1`/`TLSv1.1`/`TLSv1.2` default, `IpAddressType`, the list paging (no `Marker` or `IsTruncated`) and the IAM resources follow AWS captures. The endpoint has to be a load balancer or instance that exists in MiniStack, and viewer requests are not routed to it. Contributed by @kharabasz.### Fixed- **IoT — `#` does not match the level above it** — a subscription or topic rule with a filter ending in `/#` (`a/c2/#`) also got messages published to the level above (`a/c2`), as the MQTT specification allows; AWS IoT Core delivers only `a/c2/` and deeper, and so does the broker now, for subscriptions and rules. A republish topic at that level is still refused, as on AWS. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex aa947dd5..87ff074f 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; `url-rewrite` and `host-header-rewrite` rule transforms stored and returned (not applied to traffic); 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, 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** | 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, **VPC origins**: CreateVpcOrigin, GetVpcOrigin, UpdateVpcOrigin, DeleteVpcOrigin, ListVpcOrigins, **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; **VPC origins** answer `Deploying` and are `Deployed` on the next read, use `ETag` / `If-Match` on update and delete, take tags on their `vpcorigin` ARN, have names unique per account, and, while a distribution's `VpcOriginConfig` names them, answer `CannotDeleteEntityWhileInUse` to a delete and `CannotUpdateEntityWhileInUse` to an update that changes them; the endpoint must be an ALB, NLB or EC2 instance that exists in MiniStack, and viewer requests are not routed to it || **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/core/iam_actions.py b/ministack/core/iam_actions.pyindex 0e0a0920..b70297ad 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -1433,12 +1433,19 @@ def extract_resource_arn(service: str, method: str, path: str,return "*"if service == "cloudfront":- # REST: /2020-05-31/distribution/{id}+ # REST: /2020-05-31/distribution/{id}, /2020-05-31/vpc-origin/{id}parts = [p for p in path.split("/") if p]if "distribution" in parts:di = parts.index("distribution")if di + 1 < len(parts):return f"arn:aws:cloudfront::{account_id}:distribution/{parts[di + 1]}"+ if "vpc-origin" in parts:+ vi = parts.index("vpc-origin")+ if vi + 1 < len(parts):+ return f"arn:aws:cloudfront::{account_id}:vpcorigin/{parts[vi + 1]}"+ if method == "POST":+ # CreateVpcOrigin authorizes on every VPC origin of the account.+ return f"arn:aws:cloudfront::{account_id}:vpcorigin/*"return "*"if service in ("cognito-idp", "cognito_idp"):diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.pyindex 43750338..958aeb89 100644--- a/ministack/services/cloudfront.py+++ b/ministack/services/cloudfront.py@@ -37,6 +37,7 @@ Supports:UpdatePublicKey, DeletePublicKey, ListPublicKeysKey groups: CreateKeyGroup, GetKeyGroup, GetKeyGroupConfig,UpdateKeyGroup, DeleteKeyGroup, ListKeyGroups+ VPC origins: CreateVpcOrigin, GetVpcOrigin, UpdateVpcOrigin, DeleteVpcOrigin, ListVpcOriginsTags: TagResource, UntagResource, ListTagsForResourceSaaS Manager (multi-tenant distributions):CreateConnectionGroup, GetConnectionGroup,@@ -90,6 +91,10 @@ _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/([^/]+)/?$")+# VPC origin path regexes+_VPC_ORIGIN_RE = re.compile(r"^/2020-05-31/vpc-origin/?$")+_VPC_ORIGIN_ID_RE = re.compile(r"^/2020-05-31/vpc-origin/([^/]+)/?$")+_FUN_LIST_RE = re.compile(r"^/2020-05-31/function/?$")_FUN_DESCRIBE_RE = re.compile(r"^/2020-05-31/function/([^/]+)/describe/?$")_FUN_PUBLISH_RE = re.compile(r"^/2020-05-31/function/([^/]+)/publish/?$")@@ -157,7 +162,6 @@ _FLE_PROFILE_LIST_RE = re.compile(r"^/2020-05-31/field-level-encryption-profile/_CDP_LIST_RE = re.compile(r"^/2020-05-31/continuous-deployment-policy/?$")_OAI_LIST_RE = re.compile(r"^/2020-05-31/origin-access-identity/cloudfront/?$")_STREAMING_DIST_LIST_RE = re.compile(r"^/2020-05-31/streaming-distribution/?$")-_VPC_ORIGIN_LIST_RE = re.compile(r"^/2020-05-31/vpc-origin/?$")_REALTIME_LOG_LIST_RE = re.compile(r"^/2020-05-31/realtime-log-config/?$")_ANYCAST_IP_LIST_RE = re.compile(r"^/2020-05-31/anycast-ip-list/?$")_MONITORING_SUB_RE = re.compile(r"^/2020-05-31/distributions/([^/]+)/monitoring-subscription/?$")@@ -179,6 +183,7 @@ _key_groups = AccountScopedDict() # Id -> key group record_connection_groups = AccountScopedDict() # Id -> connection group record (SaaS Manager)_distribution_tenants = AccountScopedDict() # Id -> distribution tenant record (SaaS Manager)_tenant_invalidations = AccountScopedDict() # tenant_id -> [invalidation record, ...]+_vpc_origins = AccountScopedDict() # Id -> VPC origin recorddef reset():@@ -196,6 +201,8 @@ def reset():_connection_groups.clear()_distribution_tenants.clear()_tenant_invalidations.clear()+ _vpc_origins.clear()+ _vpc_origin_etags_issued.clear()# Drop the JS workers so their compiled-function cache does not outlive a# reset (mirrors appsync.reset()'s appsync_js.reset()).from ministack.core import cloudfront_js@@ -219,6 +226,8 @@ def get_state():"connection_groups": _connection_groups,"distribution_tenants": _distribution_tenants,"tenant_invalidations": _tenant_invalidations,+ "vpc_origins": _vpc_origins,+ "vpc_origin_max_version": max(_vpc_origin_etags_issued.values(), default=0),})@@ -241,6 +250,11 @@ def _restore_state(data):_key_groups.update(data.get("key_groups", {}))_connection_groups.update(data.get("connection_groups", {}))_distribution_tenants.update(data.get("distribution_tenants", {}))+ _vpc_origins.update(data.get("vpc_origins", {}))+ # An ETag issued before the restart, also by an origin deleted since, stays a valid If-Match.+ stored = max((vo.get("Version", 0) for vo in _vpc_origins._data.values()), default=0)+ for version in range(1, max(stored, data.get("vpc_origin_max_version", 0)) + 1):+ _vpc_origin_etag(version)_tenant_invalidations.update(data.get("tenant_invalidations", {}))@@ -316,13 +330,15 @@ def _xml_response(root_tag: str, builder_fn, status: int = 200, extra_headers: dreturn status, headers, body-def _error(code: str, message: str, status: int) -> tuple:+def _error(code: str, message, status: int) -> tuple:# rest-xml error envelope: <?xml?> declaration and <Type> (AWS captures).+ # A message of None leaves <Message> out, as AWS does for some MalformedInput errors.root = Element("ErrorResponse", xmlns=NS)err = SubElement(root, "Error")SubElement(err, "Type").text = "Sender" if status < 500 else "Receiver"SubElement(err, "Code").text = code- SubElement(err, "Message").text = message+ if message is not None:+ SubElement(err, "Message").text = messageSubElement(root, "RequestId").text = new_uuid()body = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(root, encoding="unicode").encode("utf-8")return status, {"Content-Type": "text/xml"}, body@@ -467,6 +483,32 @@ def _ensure_distribution_config_sdk_compat(config_el):if _find(config_el, "OriginGroups") is None:og = SubElement(config_el, "OriginGroups")SubElement(og, "Quantity").text = "0"+ # AWS fills in a VPC origin's timeouts when the request leaves them out.+ for vpc_cfg in _config_vpc_origin_configs(config_el):+ for tag, default in (("OriginReadTimeout", "30"), ("OriginKeepaliveTimeout", "5")):+ if _find(vpc_cfg, tag) is None:+ SubElement(vpc_cfg, tag).text = default+ # Keep the API's member order when only one timeout was sent.+ order = ("VpcOriginId", "OwnerAccountId", "OriginReadTimeout", "OriginKeepaliveTimeout")+ vpc_cfg[:] = sorted(vpc_cfg, key=lambda c: order.index(_local_tag_name(c)) if _local_tag_name(c) in order else len(order))+++def _distribution_vpc_origin_error(config_el):+ """An empty VpcOriginId, then one that names no origin."""+ ids = [_text(vpc_cfg, "VpcOriginId") for vpc_cfg in _config_vpc_origin_configs(config_el)]+ if any(not vo_id for vo_id in ids):+ return _error("InvalidArgument", "The parameter vpcOriginId must not be empty for VPC Origin.", 400)+ if any(vo_id not in _vpc_origins for vo_id in ids):+ return _error("EntityNotFound", _VPC_ORIGIN_NOT_FOUND, 404)+ return None+++def _config_vpc_origin_configs(config_el):+ """The VpcOriginConfig elements of a DistributionConfig's origins."""+ origins = _find(config_el, "Origins")+ items = _find(origins, "Items") if origins is not None else None+ found = (_find(origin, "VpcOriginConfig") for origin in (items if items is not None else ()))+ return [vpc_cfg for vpc_cfg in found if vpc_cfg is not None]# CloudFormation's DistributionConfig is the API's, in JSON, with a few@@ -687,6 +729,8 @@ def _resolve_taggable_cloudfront_arn(arn: str):"key-value-store": (_kvstores, "EntityNotFound", f"The key value store {name} was not found.", "ARN"),"distribution-tenant": (_distribution_tenants, "EntityNotFound", "The distribution tenant was not found.", "Arn"),"connection-group": (_connection_groups, "EntityNotFound", "The connection group was not found.", "Arn"),+ "vpcorigin": (_vpc_origins, "NoSuchResource",+ "The specified resource doesn't exist. Update your request and try again.", "Arn"),}entry = resources.get(resource_type)if not entry:@@ -2448,6 +2492,22 @@ async def handle_request(method, path, headers, body, query_params):if method == "POST" and operation == "Untag":return _untag_resource(resource, body)+ # VPC origin routes+ m = _VPC_ORIGIN_RE.match(path)+ if m:+ if method == "POST":+ return _create_vpc_origin(body)+ if method == "GET":+ return _list_vpc_origins(query_params)+ m = _VPC_ORIGIN_ID_RE.match(path)+ if m:+ if method == "GET":+ return _get_vpc_origin(m.group(1))+ if method == "PUT":+ return _update_vpc_origin(m.group(1), headers, body)+ if method == "DELETE":+ return _delete_vpc_origin(m.group(1), headers)+# OAC routesm = _OAC_RE.match(path)if m:@@ -2767,7 +2827,7 @@ async def handle_request(method, path, headers, body, query_params):# Read-only list surface for resource families with no backing store.# Family split matches botocore: KeyGroupList-style carry no Marker/- # IsTruncated; the OAI/StreamingDistribution/VpcOrigin family does.+ # IsTruncated; the OAI/StreamingDistribution family does.m = _FLE_LIST_RE.match(path)if m and method == "GET":return _empty_marker_list(query_params, "FieldLevelEncryptionList", with_marker=False)@@ -2788,10 +2848,6 @@ async def handle_request(method, path, headers, body, query_params):if m and method == "GET":return _empty_marker_list(query_params, "StreamingDistributionList", with_marker=True)- m = _VPC_ORIGIN_LIST_RE.match(path)- if m and method == "GET":- return _empty_marker_list(query_params, "VpcOriginList", with_marker=True)-m = _REALTIME_LOG_LIST_RE.match(path)if m and method == "GET":return _list_realtime_log_configs(query_params)@@ -2839,6 +2895,9 @@ def _create_distribution(headers, body):return _error("InvalidArgument", "Origins is required.", 400)if _find(config_el, "DefaultCacheBehavior") is None:return _error("InvalidArgument", "DefaultCacheBehavior is required.", 400)+ err = _distribution_vpc_origin_error(config_el)+ if err:+ return errdist_id = _dist_id()etag = new_uuid()@@ -2978,6 +3037,9 @@ def _update_distribution(dist_id, headers, body):config_el = _parse_body(body)if config_el is None:return _error("MalformedXML", "The XML document is malformed.", 400)+ err = _distribution_vpc_origin_error(config_el)+ if err:+ return errnew_etag = new_uuid()dist["config_xml"] = tostring(config_el, encoding="unicode")@@ -3149,6 +3211,9 @@ def _list_tags(resource_arn):if err:return errtags = _tags.get(resource_arn, [])+ if ":vpcorigin/" in resource_arn:+ # AWS lists a VPC origin's tags sorted by key.+ tags = sorted(tags, key=lambda t: t["Key"])root = Element("Tags", xmlns=NS)items = SubElement(root, "Items")for t in tags:@@ -3196,6 +3261,447 @@ def _untag_resource(resource_arn, body):return 204, {}, b""+# ---------------------------------------------------------------------------+# VPC origin handlers+# ---------------------------------------------------------------------------+# Control plane only. Codes, messages and the order of checks follow captures+# from AWS (ministackorg/ministack#2312). AWS answers a create, update or delete+# with Status Deploying and finishes it minutes later; MiniStack finishes it at+# once, so a later read shows Deployed and a deleted origin is gone; AWS's+# LastModifiedTime also moves on when a deployment ends, MiniStack's doesn't. The endpoint+# ARN's format and account are checked, and the load balancer or instance must exist+# in MiniStack's ELBv2 or EC2 state. Viewer requests are never routed to the VPC endpoint.++_VPC_ORIGIN_POLICIES = ("https-only", "http-only", "match-viewer")+_VPC_ORIGIN_SSL_PROTOCOLS = ("SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2")+_VPC_ORIGIN_DEFAULT_SSL_PROTOCOLS = ["TLSv1", "TLSv1.1", "TLSv1.2"]+_VPC_ORIGIN_IP_ADDRESS_TYPES = ("ipv4", "dualstack")+_VPC_ORIGIN_ID_FORMAT_RE = re.compile(r"^[a-z]+_[A-Za-z0-9]{22}$")+_VPC_ORIGIN_NAME_RE = re.compile(r"^[A-Za-z0-9_-]+$")+_VPC_ORIGIN_NAME_MAX = 64+_VPC_ORIGIN_INTEGER_RE = re.compile(r"^[-+]?[0-9]+$")+_VPC_ORIGIN_ENDPOINT_RESOURCE_RE = {+ "elasticloadbalancing": re.compile(r"^loadbalancer/(app|net)/[^/]+/[^/]+$"),+ "ec2": re.compile(r"^instance/i-[0-9A-Za-z]+$"),+}+_vpc_origin_etags_issued = {} # ETag -> version, for every version an origin has reached+_VPC_ORIGIN_LOCATION = "https://cloudfront.amazonaws.com/2020-05-31/vpc-origin/"+_VPC_ORIGIN_MAX_ITEMS = 100+_VPC_ORIGIN_NOT_FOUND = "The specified vpc origin does not exist"+_VPC_ORIGIN_BAD_IF_MATCH = "The If-Match version is missing or not valid for the resource."+_VPC_ORIGIN_STALE_IF_MATCH = "The request failed because it didn't meet the preconditions in one or more request-header fields."+_VPC_ORIGIN_NAME_TAKEN = "Another vpc origin with the same name already exists within the aws account."+_VPC_ORIGIN_IN_USE = ("The specified VPC origin is currently associated with one or more distributions. Please "+ "disassociate the VPC origin from all distributions before updating or deleting")+++def _vpc_origin_etag(version):+ """AWS's ETag follows the origin's version, so origins at the same version share+ it. The version counts every change: a create, update or delete, and the end of+ the deployment that follows it. The value is a uuid5 of the version, like+ ``_managed_etag`` (real AWS ETags are opaque)."""+ etag = str(uuid.uuid5(uuid.NAMESPACE_URL, f"ministack-cloudfront-vpc-origin/version/{version}"))+ _vpc_origin_etags_issued.setdefault(etag, version)+ return etag+++def _vpc_origin_validation_error(problems):+ count = len(problems)+ noun = "error" if count == 1 else "errors"+ return _error("MalformedXML", f"{count} validation {noun} detected: " + "; ".join(problems), 400)+++def _vpc_origin_null(path):+ return f"Value null at '{path}' failed to satisfy constraint: Member must not be null"+++def _vpc_origin_int(el, tag):+ """(value, error) for an integer member; (None, None) when it is absent."""+ child = _find(el, tag) if el is not None else None+ if child is None:+ return None, None+ raw = child.text or ""+ if not raw:+ return None, _error("MalformedInput", "missing value for decimal type", 400)+ if not _VPC_ORIGIN_INTEGER_RE.match(raw) or not -2**31 <= int(raw) < 2**31:+ return None, _error("MalformedInput", None, 400)+ return int(raw), None+++def _vpc_origin_body(body, root_tag):+ """(element, error) for a request body. An empty body has no element."""+ if not body:+ return None, None+ el = _parse_body(body)+ if el is None:+ return None, _error("MalformedInput", "Could not parse XML", 400)+ if _local_tag_name(el) != root_tag:+ return None, _error("MalformedInput", f"{_local_tag_name(el)} is not valid, expected {root_tag}", 400)+ return el, None+++def _parse_vpc_origin_endpoint_config(cfg_el, path="vpcOriginEndpointConfig"):+ """(fields, problems, error) for a VpcOriginEndpointConfig element.++ An integer that doesn't parse is an error at once (MalformedInput). The null and+ enum problems come back as a list, in AWS's member order, so Update can add its+ own ``ifMatch`` problem to the same MalformedXML message."""+ if cfg_el is None:+ return None, [_vpc_origin_null(path)], None+ http_port, err = _vpc_origin_int(cfg_el, "HTTPPort")+ if err:+ return None, [], err+ https_port, err = _vpc_origin_int(cfg_el, "HTTPSPort")+ if err:+ return None, [], err+ ssl_el = _find(cfg_el, "OriginSslProtocols")+ quantity, err = _vpc_origin_int(ssl_el, "Quantity")+ if err:+ return None, [], err+ name_el, arn_el, policy_el = (_find(cfg_el, t) for t in ("Name", "Arn", "OriginProtocolPolicy"))+ # AWS lists the problems in this member order.+ problems = []+ if http_port is None:+ problems.append(_vpc_origin_null(f"{path}.hTTPPort"))+ protocols = None+ if ssl_el is not None:+ items_el = _find(ssl_el, "Items")+ if quantity is None:+ problems.append(_vpc_origin_null(f"{path}.originSslProtocols.quantity"))+ if items_el is None:+ problems.append(_vpc_origin_null(f"{path}.originSslProtocols.items"))+ else:+ protocols = [i.text or "" for i in items_el if _local_tag_name(i) == "SslProtocol"]+ if any(p not in _VPC_ORIGIN_SSL_PROTOCOLS for p in protocols):+ problems.append(+ f"Value '[{', '.join(protocols)}]' at '{path}.originSslProtocols.items' failed to satisfy "+ "constraint: Member must satisfy constraint: [Member must satisfy enum value set: "+ f"[{', '.join(_VPC_ORIGIN_SSL_PROTOCOLS)}]]")+ if name_el is None:+ problems.append(_vpc_origin_null(f"{path}.name"))+ policy = (policy_el.text or "") if policy_el is not None else None+ if policy is None:+ problems.append(_vpc_origin_null(f"{path}.originProtocolPolicy"))+ elif policy not in _VPC_ORIGIN_POLICIES:+ problems.append(f"Value '{policy}' at '{path}.originProtocolPolicy' failed to satisfy constraint: "+ f"Member must satisfy enum value set: [{', '.join(_VPC_ORIGIN_POLICIES)}]")+ if https_port is None:+ problems.append(_vpc_origin_null(f"{path}.hTTPSPort"))+ if arn_el is None:+ problems.append(_vpc_origin_null(f"{path}.arn"))+ ip_el = _find(cfg_el, "IpAddressType")+ ip_type = (ip_el.text or "") if ip_el is not None else "ipv4"+ if ip_type not in _VPC_ORIGIN_IP_ADDRESS_TYPES:+ problems.append(f"Value '{ip_type}' at '{path}.ipAddressType' failed to satisfy constraint: "+ f"Member must satisfy enum value set: [{', '.join(_VPC_ORIGIN_IP_ADDRESS_TYPES)}]")+ fields = {+ "Name": (name_el.text or "") if name_el is not None else "",+ "Arn": (arn_el.text or "") if arn_el is not None else "",+ "HTTPPort": http_port,+ "HTTPSPort": https_port,+ "OriginProtocolPolicy": policy,+ "Quantity": quantity,+ "OriginSslProtocols": protocols,+ "IpAddressType": ip_type,+ }+ return fields, problems, None+++def _vpc_origin_region_known(region):+ """AWS refuses a region it doesn't have (xx-fake-1) as an invalid format."""+ from ministack.services import ec2++ return any(name == region for name, _ in ec2._AWS_REGIONS)+++def _vpc_origin_endpoint_error(arn):+ try:+ spec = parse_arn(arn)+ except ArnParseError:+ spec = None+ pattern = _VPC_ORIGIN_ENDPOINT_RESOURCE_RE.get(spec.service) if spec else None+ if (not pattern or spec.partition != "aws" or not _vpc_origin_region_known(spec.region)+ or not spec.account_id or not pattern.match(spec.resource)):+ return _error("InvalidArgument", "The parameter VpcOriginEndpointConfig Arn Invalid Format.", 400)+ if spec.account_id != get_account_id():+ return _error("InvalidArgument", "The parameter VpcOriginEndpointConfig Arn contains a mismatched AWS account.",+ 400)+ return _vpc_origin_endpoint_missing(spec, arn)+++def _vpc_origin_endpoint_missing(spec, arn):+ """The load balancer or instance must exist in the ARN's account and region."""+ if spec.service == "elasticloadbalancing":+ from ministack.services import alb++ if alb._lbs.contains_scoped(spec.account_id, spec.region, arn):+ return None+ return _error("InvalidArgument", "The parameter VpcOriginEndpointConfig Arn LoadBalancerNotFound.", 400)+ from ministack.services import ec2++ instance_id = spec.resource.split("/", 1)[1]+ if ec2._instances.contains_scoped(spec.account_id, spec.region, instance_id):+ return None+ # AWS answers NotFound for a short (8-character) id and Malformed for a long one.+ reason = "InvalidInstanceID.NotFound" if len(instance_id) == len("i-12345678") else "InvalidInstanceID.Malformed"+ return _error("InvalidArgument", f"The parameter VpcOriginEndpointConfig Arn {reason}.", 400)+++def _check_vpc_origin_endpoint_config(fields):+ """(config, error) for the checks AWS makes after the schema and the If-Match:+ the ports, the name, the protocol list, then the endpoint ARN."""+ if not all(p in (80, 443) or 1024 <= p <= 65535 for p in (fields["HTTPPort"], fields["HTTPSPort"])):+ return None, _error("InvalidArgument", "The parameter origin port is not within allowed range.", 400)+ name = fields["Name"]+ if not name:+ return None, _error("InvalidArgument", "The parameter VPC Origin Name is too small or empty.", 400)+ if len(name) > _VPC_ORIGIN_NAME_MAX:+ return None, _error("InvalidArgument", "The parameter VPC Origin Name is too big.", 400)+ if not _VPC_ORIGIN_NAME_RE.match(name):+ return None, _error("InvalidArgument",+ "The parameter Name contains characters other than alphanumericals, dashes, and underscores.",+ 400)+ protocols, quantity = fields["OriginSslProtocols"], fields["Quantity"]+ if protocols is None:+ protocols = list(_VPC_ORIGIN_DEFAULT_SSL_PROTOCOLS)+ elif quantity != len(protocols):+ return None, _error("InconsistentQuantities",+ f"The specified quantity of OriginSslProtocols ({quantity}) does not match the actual "+ f"quantity supplied ({len(protocols)}).", 400)+ elif not protocols:+ return None, _error("InvalidArgument",+ "The parameter OriginSslProtocols is not valid! Should be one or more from SSLv3, TLSv1, "+ "TLSv1.1, and TLSv1.2.", 400)+ err = _vpc_origin_endpoint_error(fields["Arn"])+ if err:+ return None, err+ # Stored once each, in the order of the enum.+ protocols = [p for p in _VPC_ORIGIN_SSL_PROTOCOLS if p in protocols]+ return {+ "Name": name,+ "Arn": fields["Arn"],+ "HTTPPort": fields["HTTPPort"],+ "HTTPSPort": fields["HTTPSPort"],+ "OriginProtocolPolicy": fields["OriginProtocolPolicy"],+ "OriginSslProtocols": protocols,+ "IpAddressType": fields["IpAddressType"],+ }, None+++def _vpc_origin_name_taken(name, exclude_id=None):+ return any(vo["Id"] != exclude_id and vo["VpcOriginEndpointConfig"]["Name"] == name+ for vo in _vpc_origins.values())+++def _build_vpc_origin_xml(root, vo):+ SubElement(root, "Id").text = vo["Id"]+ SubElement(root, "Arn").text = vo["Arn"]+ SubElement(root, "AccountId").text = vo["AccountId"]+ SubElement(root, "Status").text = vo["Status"]+ SubElement(root, "CreatedTime").text = vo["CreatedTime"]+ SubElement(root, "LastModifiedTime").text = vo["LastModifiedTime"]+ cfg = vo["VpcOriginEndpointConfig"]+ cfg_el = SubElement(root, "VpcOriginEndpointConfig")+ SubElement(cfg_el, "Name").text = cfg["Name"]+ SubElement(cfg_el, "Arn").text = cfg["Arn"]+ SubElement(cfg_el, "HTTPPort").text = str(cfg["HTTPPort"])+ SubElement(cfg_el, "HTTPSPort").text = str(cfg["HTTPSPort"])+ SubElement(cfg_el, "OriginProtocolPolicy").text = cfg["OriginProtocolPolicy"]+ ssl_el = SubElement(cfg_el, "OriginSslProtocols")+ SubElement(ssl_el, "Quantity").text = str(len(cfg["OriginSslProtocols"]))+ items_el = SubElement(ssl_el, "Items")+ for proto in cfg["OriginSslProtocols"]:+ SubElement(items_el, "SslProtocol").text = proto+ SubElement(cfg_el, "IpAddressType").text = cfg.get("IpAddressType", "ipv4")+++def _vpc_origin_response(vo, status=200, deploying=False):+ """The origin as stored, or, for a create, update or delete, as AWS answers it:+ Deploying, at the version before its deployment finishes."""+ version = vo["Version"] - 1 if deploying else vo["Version"]+ view = dict(vo, Status="Deploying") if deploying else vo+ return _xml_response("VpcOrigin", lambda root: _build_vpc_origin_xml(root, view), status=status,+ extra_headers={"ETag": _vpc_origin_etag(version)})+++def _create_vpc_origin(body):+ el, err = _vpc_origin_body(body, "CreateVpcOriginRequest")+ if err:+ return err+ fields, problems, err = _parse_vpc_origin_endpoint_config(+ _find(el, "VpcOriginEndpointConfig") if el is not None else None)+ if err:+ return err+ if problems:+ return _vpc_origin_validation_error(problems)+ cfg, err = _check_vpc_origin_endpoint_config(fields)+ if err:+ return err+ if _vpc_origin_name_taken(cfg["Name"]):+ return _error("EntityAlreadyExists", _VPC_ORIGIN_NAME_TAKEN, 409)+ vo_id = "vo_" + "".join(random.choices(_KSUID_CHARS, k=22))+ now = _now_iso()+ vo = {+ "Id": vo_id,+ "Arn": f"arn:aws:cloudfront::{get_account_id()}:vpcorigin/{vo_id}",+ "AccountId": get_account_id(),+ "Status": "Deployed",+ "CreatedTime": now,+ "LastModifiedTime": now,+ "VpcOriginEndpointConfig": cfg,+ "Version": 2,+ }+ _vpc_origins[vo_id] = vo+ _ingest_distribution_tags_from_xml(vo["Arn"], _find(el, "Tags"))+ status, headers, payload = _vpc_origin_response(vo, status=202, deploying=True)+ headers["Location"] = _VPC_ORIGIN_LOCATION + vo_id+ return status, headers, payload+++def _vpc_origin_lookup(vo_id):+ vo = _vpc_origins.get(vo_id)+ if not vo:+ return None, _error("EntityNotFound", _VPC_ORIGIN_NOT_FOUND, 404)+ return vo, None+++def _vpc_origin_bad_if_match(if_match):+ """An If-Match that is no version's ETag; checked before the origin is looked up.+ AWS refuses a well-formed ETag it never issued, and accepts an issued one on any id."""+ if if_match not in _vpc_origin_etags_issued:+ return _error("InvalidIfMatchVersion", _VPC_ORIGIN_BAD_IF_MATCH, 400)+ return None+++def _vpc_origin_current(vo_id, if_match):+ """(record, error): the origin, then an If-Match that isn't its current ETag."""+ vo, err = _vpc_origin_lookup(vo_id)+ if err:+ return None, err+ if if_match != _vpc_origin_etag(vo["Version"]):+ return None, _error("PreconditionFailed", _VPC_ORIGIN_STALE_IF_MATCH, 412)+ return vo, None+++def _get_vpc_origin(vo_id):+ if not _VPC_ORIGIN_ID_FORMAT_RE.match(vo_id):+ return _error("InvalidArgument", "Id format is invalid", 400)+ vo, err = _vpc_origin_lookup(vo_id)+ if err:+ return err+ return _vpc_origin_response(vo)+++def _update_vpc_origin(vo_id, headers, body):+ # Errors reading the body come before the id format.+ el, err = _vpc_origin_body(body, "VpcOriginEndpointConfig")+ if err:+ return err+ fields, problems, err = _parse_vpc_origin_endpoint_config(el)+ if err:+ return err+ if not _VPC_ORIGIN_ID_FORMAT_RE.match(vo_id):+ return _error("InvalidArgument", "Id format is invalid", 400)+ if_match = headers.get("if-match")+ if if_match is None:+ problems.append(_vpc_origin_null("ifMatch"))+ if problems:+ return _vpc_origin_validation_error(problems)+ err = _vpc_origin_bad_if_match(if_match)+ if err:+ return err+ cfg, err = _check_vpc_origin_endpoint_config(fields)+ if err:+ return err+ vo, err = _vpc_origin_current(vo_id, if_match)+ if err:+ return err+ if _vpc_origin_in_use(vo_id):+ if cfg != vo["VpcOriginEndpointConfig"]:+ return _error("CannotUpdateEntityWhileInUse", _VPC_ORIGIN_IN_USE, 409)+ # An unchanged config is accepted without a new version.+ return _vpc_origin_response(vo, status=202)+ if _vpc_origin_name_taken(cfg["Name"], exclude_id=vo_id):+ return _error("EntityAlreadyExists", _VPC_ORIGIN_NAME_TAKEN, 409)+ vo["VpcOriginEndpointConfig"] = cfg+ vo["LastModifiedTime"] = _now_iso()+ vo["Version"] += 2+ return _vpc_origin_response(vo, status=202, deploying=True)+++def _vpc_origin_ids_in(dist):+ """VpcOriginId values named by a stored distribution's origins."""+ try:+ root = fromstring(dist.get("config_xml") or "")+ except Exception:+ return set()+ return {_text(vpc_cfg, "VpcOriginId") for vpc_cfg in _config_vpc_origin_configs(root)}+++def _vpc_origin_in_use(vo_id):+ return any(vo_id in _vpc_origin_ids_in(d) for d in _distributions.values())+++def _delete_vpc_origin(vo_id, headers):+ if not _VPC_ORIGIN_ID_FORMAT_RE.match(vo_id):+ return _error("InvalidArgument", "Id format is invalid", 400)+ if_match = headers.get("if-match")+ if if_match is None:+ return _vpc_origin_validation_error([_vpc_origin_null("ifMatch")])+ err = _vpc_origin_bad_if_match(if_match)+ if err:+ return err+ vo, err = _vpc_origin_current(vo_id, if_match)+ if err:+ return err+ if _vpc_origin_in_use(vo_id):+ return _error("CannotDeleteEntityWhileInUse", _VPC_ORIGIN_IN_USE, 409)+ del _vpc_origins[vo_id]+ _tags.pop(vo["Arn"], None)+ gone = dict(vo, LastModifiedTime=_now_iso(), Version=vo["Version"] + 2)+ return _vpc_origin_response(gone, status=202, deploying=True)+++def _list_vpc_origins(query_params):+ max_items_raw = _qval(query_params, "MaxItems", "")+ marker = _qval(query_params, "Marker", "")+ if max_items_raw:+ if not _VPC_ORIGIN_INTEGER_RE.match(max_items_raw) or not 0 <= int(max_items_raw) < 2**31:+ return _error("InvalidArgument", "MaxItems must be a non-zero positive integer.", 400)+ max_items = min(int(max_items_raw), _VPC_ORIGIN_MAX_ITEMS)+ else:+ max_items = _VPC_ORIGIN_MAX_ITEMS+ items = sorted(_vpc_origins.values(), key=lambda vo: vo["Id"])+ if marker:+ ids = [vo["Id"] for vo in items]+ if marker not in ids:+ return _error("EntityNotFound", "The request contains an invalid marker.", 404)+ items = items[ids.index(marker) + 1:]+ page = items[:max_items]+ # NextMarker is the last id on a page that leaves items behind; Marker is exclusive.+ more = bool(page) and len(items) > len(page)++ def build(root):+ if more:+ SubElement(root, "NextMarker").text = page[-1]["Id"]+ SubElement(root, "MaxItems").text = str(max_items)+ SubElement(root, "Quantity").text = str(len(page))+ items_el = SubElement(root, "Items")+ for vo in page:+ summary = SubElement(items_el, "VpcOriginSummary")+ SubElement(summary, "Id").text = vo["Id"]+ SubElement(summary, "Name").text = vo["VpcOriginEndpointConfig"]["Name"]+ SubElement(summary, "Status").text = vo["Status"]+ SubElement(summary, "CreatedTime").text = vo["CreatedTime"]+ SubElement(summary, "LastModifiedTime").text = vo["LastModifiedTime"]+ SubElement(summary, "Arn").text = vo["Arn"]+ SubElement(summary, "AccountId").text = vo["AccountId"]+ SubElement(summary, "OriginEndpointArn").text = vo["VpcOriginEndpointConfig"]["Arn"]+ SubElement(summary, "IpAddressType").text = vo["VpcOriginEndpointConfig"].get("IpAddressType", "ipv4")++ return _xml_response("VpcOriginList", build)++# ---------------------------------------------------------------------------# OAC handlers# ---------------------------------------------------------------------------diff --git a/tests/test_cloudfront.py b/tests/test_cloudfront.pyindex 3a790286..83fc2845 100644--- a/tests/test_cloudfront.py+++ b/tests/test_cloudfront.py@@ -10,6 +10,7 @@ import uuid as _uuid_modimport pytestfrom botocore.exceptions import ClientError+from conftest import make_clientENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")@@ -1985,15 +1986,6 @@ def test_cloudfront_list_streaming_distributions_empty(cloudfront):assert lst.get("Items", []) == []-def test_cloudfront_list_vpc_origins_empty(cloudfront):- resp = cloudfront.list_vpc_origins()- lst = resp["VpcOriginList"]- assert lst["MaxItems"] == 100- assert lst["IsTruncated"] is False- assert lst["Quantity"] == 0- assert lst.get("Items", []) == []--def test_cloudfront_list_realtime_log_configs_empty(cloudfront):resp = cloudfront.list_realtime_log_configs()lst = resp["RealtimeLogConfigs"]@@ -3097,3 +3089,1111 @@ def test_cf_distribution_webacl_associate_disassociate(cloudfront):with pytest.raises(ClientError) as exc:cloudfront.associate_distribution_web_acl(Id="E0000000000000", WebACLArn=acl_arn, IfMatch="x")assert exc.value.response["Error"]["Code"] == "EntityNotFound"+++# ---------------------------------------------------------------------------+# VPC origins+#+# Every expectation below was captured against AWS (us-east-1, 2026-10-20/21,+# boto3 1.43.106) for ministackorg/ministack#2312. Docstrings name the capture:+# "V <claim>" is captures/cloudfront-vpc-origins.json, "R1 <key>/<step>" is+# captures/2312-round1.json, "R2 <key>/<step>" captures/2312-round2.json, "R3" captures/2312-round3.json+# "R3b" captures/2312-round3b.json, "R4" captures/2312-round4-wrong-root.json, "R5"+# captures/2312-round5.json and "R6" captures/2312-round6-edges.json.+# ---------------------------------------------------------------------------++_VO_ACCOUNT = "000000000000"+_VO_NS = "http://cloudfront.amazonaws.com/doc/2020-05-31/"+_VO_STALE = "The request failed because it didn't meet the preconditions in one or more request-header fields."+_VO_BAD_IF_MATCH = "The If-Match version is missing or not valid for the resource."+_VO_NOT_FOUND = "The specified vpc origin does not exist"+_VO_NO_RESOURCE = "The specified resource doesn't exist. Update your request and try again."+++_vo_endpoints = {}+++def _vo_endpoint(kind="alb", index=0):+ """A real load balancer or instance in MiniStack, created once per worker; AWS checks that the+ endpoint exists (R1 V-arn/nlb-missing, alb-other-region, ec2-short-id; V C35)."""+ key = (kind, index)+ if key not in _vo_endpoints:+ if kind == "instance":+ ec2 = make_client("ec2")+ instance = ec2.run_instances(ImageId="ami-00000000", MinCount=1, MaxCount=1, InstanceType="t3.nano")+ instance_id = instance["Instances"][0]["InstanceId"]+ _vo_endpoints[key] = f"arn:aws:ec2:us-east-1:{_VO_ACCOUNT}:instance/{instance_id}"+ else:+ lb = make_client("elbv2").create_load_balancer(+ Name=f"vo-{kind}-{index}-{_uuid_mod.uuid4().hex[:8]}", Scheme="internal",+ Type="network" if kind == "nlb" else "application")+ _vo_endpoints[key] = lb["LoadBalancers"][0]["LoadBalancerArn"]+ return _vo_endpoints[key]+++def _vo_cfg(**overrides):+ cfg = {"Name": f"vo-{_uuid_mod.uuid4().hex[:12]}", "Arn": _vo_endpoint(), "HTTPPort": 80, "HTTPSPort": 443,+ "OriginProtocolPolicy": "https-only", "OriginSslProtocols": {"Quantity": 1, "Items": ["TLSv1.2"]}}+ cfg.update(overrides)+ return cfg+++def _vo_delete(cloudfront, vo_id):+ try:+ cloudfront.delete_vpc_origin(Id=vo_id, IfMatch=cloudfront.get_vpc_origin(Id=vo_id)["ETag"])+ except ClientError:+ pass+++def vpc_origin(cloudfront):+ created = cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg())+ try:+ yield created+ finally:+ _vo_delete(cloudfront, created["VpcOrigin"]["Id"])+++def _vo_error(exc_info):+ resp = exc_info.value.response+ return resp["ResponseMetadata"]["HTTPStatusCode"], resp["Error"]["Code"], resp["Error"].get("Message")+++def _vo_raw(method, path, body=None, headers=None):+ """(status, headers, body) of an unsigned request; used where botocore refuses the input."""+ data = body.encode() if isinstance(body, str) else body+ req = urllib.request.Request(f"{ENDPOINT}{path}", data=data, method=method, headers=headers or {})+ try:+ with urllib.request.urlopen(req, timeout=10) as resp:+ return resp.status, dict(resp.headers), resp.read().decode()+ except urllib.error.HTTPError as e:+ return e.code, dict(e.headers), e.read().decode()+++def _vo_raw_error(method, path, body=None, headers=None):+ status, _, text = _vo_raw(method, path, body, headers)+ code = re.search(r"<Code>([^<]*)</Code>", text)+ message = re.search(r"<Message>([^<]*)</Message>", text)+ return status, code.group(1) if code else None, message.group(1) if message else None+++def _vo_cfg_xml(cfg, omit=(), http=None, https=None, ssl=None):+ parts = []+ for tag, value in (("Name", cfg["Name"]), ("Arn", cfg["Arn"]),+ ("HTTPPort", cfg["HTTPPort"] if http is None else http),+ ("HTTPSPort", cfg["HTTPSPort"] if https is None else https),+ ("OriginProtocolPolicy", cfg["OriginProtocolPolicy"])):+ if tag not in omit:+ parts.append(f"<{tag}>{value}</{tag}>")+ if ssl is not None:+ parts.append(ssl)+ return "".join(parts)+++def _vo_create_xml(inner):+ return (f'<CreateVpcOriginRequest xmlns="{_VO_NS}"><VpcOriginEndpointConfig>{inner}'+ "</VpcOriginEndpointConfig></CreateVpcOriginRequest>")+++def test_cloudfront_vpc_origin_create_answers_deploying(cloudfront):+ """V C1, C2, C4, C5; R1 U-create/create-A-default-ssl: 202, an absolute Location, Deploying,+ CreatedTime == LastModifiedTime, and TLSv1/TLSv1.1/TLSv1.2 when OriginSslProtocols is omitted."""+ cfg = _vo_cfg()+ cfg.pop("OriginSslProtocols")+ created = cloudfront.create_vpc_origin(VpcOriginEndpointConfig=cfg)+ vo = created["VpcOrigin"]+ try:+ assert created["ResponseMetadata"]["HTTPStatusCode"] == 202+ assert created["Location"] == f"https://cloudfront.amazonaws.com/2020-05-31/vpc-origin/{vo['Id']}"+ assert re.fullmatch(r"vo_[A-Za-z0-9]{22}", vo["Id"])+ assert vo["Arn"] == f"arn:aws:cloudfront::{_VO_ACCOUNT}:vpcorigin/{vo['Id']}"+ assert vo["AccountId"] == _VO_ACCOUNT+ assert vo["Status"] == "Deploying"+ assert vo["CreatedTime"] == vo["LastModifiedTime"]+ assert vo["VpcOriginEndpointConfig"] == {**cfg, "OriginSslProtocols": {+ "Quantity": 3, "Items": ["TLSv1", "TLSv1.1", "TLSv1.2"]}}+ finally:+ _vo_delete(cloudfront, vo["Id"])+++def test_cloudfront_vpc_origin_get_after_create_is_deployed_with_next_etag(cloudfront, vpc_origin):+ """R1 U6/transitions-*: once deployed, Get answers Deployed with a new ETag, so the create's ETag+ is stale: R3b U13/update-B-stale-etag-in-use (412 for B's create ETag once deployed). V C7: an explicit+ OriginSslProtocols round-trips."""+ vo_id = vpc_origin["VpcOrigin"]["Id"]+ got = cloudfront.get_vpc_origin(Id=vo_id)+ assert got["VpcOrigin"]["Status"] == "Deployed"+ assert got["ETag"] != vpc_origin["ETag"]+ assert got["VpcOrigin"]["VpcOriginEndpointConfig"]["OriginSslProtocols"] == {"Quantity": 1, "Items": ["TLSv1.2"]}+ with pytest.raises(ClientError) as exc:+ cloudfront.update_vpc_origin(Id=vo_id, IfMatch=vpc_origin["ETag"],+ VpcOriginEndpointConfig=got["VpcOrigin"]["VpcOriginEndpointConfig"])+ assert _vo_error(exc) == (412, "PreconditionFailed", _VO_STALE)+++def test_cloudfront_vpc_origin_responses_carry_ip_address_type(vpc_origin):+ """R1 U-create/create-A-default-ssl and U11/page-size-1-page-1 (raw bodies): AWS sends+ <IpAddressType>ipv4</IpAddressType> in the config and in list summaries."""+ vo_id = vpc_origin["VpcOrigin"]["Id"]+ _, _, text = _vo_raw("GET", f"/2020-05-31/vpc-origin/{vo_id}")+ assert "<OriginSslProtocols><Quantity>1</Quantity><Items><SslProtocol>TLSv1.2</SslProtocol></Items>" \+ "</OriginSslProtocols><IpAddressType>ipv4</IpAddressType></VpcOriginEndpointConfig>" in text+ _, _, text = _vo_raw("GET", "/2020-05-31/vpc-origin")+ assert "</OriginEndpointArn><IpAddressType>ipv4</IpAddressType></VpcOriginSummary>" in text+++def test_cloudfront_vpc_origin_tags(cloudfront):+ """V C6; R1 U12: create-time tags are kept, TagResource and UntagResource answer 204 (also for a key+ that isn't set), a tag is overwritten in place, and ListTagsForResource sorts by key."""+ created = cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg(), Tags={"Items": [+ {"Key": "team", "Value": "edge"}, {"Key": "Owner", "Value": "me"}]})+ arn = created["VpcOrigin"]["Arn"]+ try:+ tagged = cloudfront.tag_resource(Resource=arn, Tags={"Items": [{"Key": "a", "Value": "1"}, {"Key": "b", "Value": "2"}]})+ assert tagged["ResponseMetadata"]["HTTPStatusCode"] == 204+ untagged = cloudfront.untag_resource(Resource=arn, TagKeys={"Items": ["a", "zz"]})+ assert untagged["ResponseMetadata"]["HTTPStatusCode"] == 204+ cloudfront.tag_resource(Resource=arn, Tags={"Items": [{"Key": "b", "Value": "3"}]})+ assert cloudfront.list_tags_for_resource(Resource=arn)["Tags"]["Items"] == [+ {"Key": "Owner", "Value": "me"}, {"Key": "b", "Value": "3"}, {"Key": "team", "Value": "edge"}]+ finally:+ _vo_delete(cloudfront, created["VpcOrigin"]["Id"])+++def test_cloudfront_vpc_origin_tags_unknown_arn(cloudfront):+ """V C45: Tag, Untag and ListTags on an unknown vpcorigin ARN answer 404 NoSuchResource."""+ arn = f"arn:aws:cloudfront::{_VO_ACCOUNT}:vpcorigin/vo_Y769dEbaneau0o63mXNjrY"+ for call in (lambda: cloudfront.tag_resource(Resource=arn, Tags={"Items": [{"Key": "a", "Value": "1"}]}),+ lambda: cloudfront.untag_resource(Resource=arn, TagKeys={"Items": ["a"]}),+ lambda: cloudfront.list_tags_for_resource(Resource=arn)):+ with pytest.raises(ClientError) as exc:+ call()+ assert _vo_error(exc) == (404, "NoSuchResource", _VO_NO_RESOURCE)+++def test_cloudfront_vpc_origin_names_are_unique_endpoints_are_not(cloudfront, vpc_origin):+ """R1 U8/create-identical-to-A: a second origin with the same name answers 409.+ R1 U8/create-on-endpoint-of-A: a second origin on the same endpoint is accepted."""+ cfg = vpc_origin["VpcOrigin"]["VpcOriginEndpointConfig"]+ with pytest.raises(ClientError) as exc:+ cloudfront.create_vpc_origin(VpcOriginEndpointConfig={**cfg, "Arn": _vo_endpoint("alb", 1)})+ assert _vo_error(exc) == (409, "EntityAlreadyExists",+ "Another vpc origin with the same name already exists within the aws account.")+ other = cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg(Arn=cfg["Arn"]))+ try:+ assert other["ResponseMetadata"]["HTTPStatusCode"] == 202+ finally:+ _vo_delete(cloudfront, other["VpcOrigin"]["Id"])+++def test_cloudfront_vpc_origin_update(cloudfront, vpc_origin):+ """R1 U4/update-A-https-8443 and get-A-after-update: 202, Deploying, the change applied, a new ETag+ and LastModifiedTime; the deployed origin then has another ETag (R1 U4/transitions-A-until-Deployed),+ and the ETag from before the update answers 412 on Update and Delete (R1 U1/update-A-old-etag-deployed,+ delete-A-old-etag-deployed)."""+ vo_id = vpc_origin["VpcOrigin"]["Id"]+ before = cloudfront.get_vpc_origin(Id=vo_id)+ cfg = before["VpcOrigin"]["VpcOriginEndpointConfig"]+ time.sleep(0.01)+ updated = cloudfront.update_vpc_origin(Id=vo_id, IfMatch=before["ETag"],+ VpcOriginEndpointConfig={**cfg, "HTTPSPort": 8443})+ assert updated["ResponseMetadata"]["HTTPStatusCode"] == 202+ assert updated["VpcOrigin"]["Status"] == "Deploying"+ assert updated["VpcOrigin"]["VpcOriginEndpointConfig"]["HTTPSPort"] == 8443+ assert updated["ETag"] != before["ETag"]+ after = cloudfront.get_vpc_origin(Id=vo_id)+ assert after["VpcOrigin"]["Status"] == "Deployed"+ assert after["VpcOrigin"]["VpcOriginEndpointConfig"]["HTTPSPort"] == 8443+ assert after["VpcOrigin"]["CreatedTime"] == before["VpcOrigin"]["CreatedTime"]+ assert after["ETag"] not in (before["ETag"], updated["ETag"])+ for stale in (before["ETag"],):+ with pytest.raises(ClientError) as exc:+ cloudfront.update_vpc_origin(Id=vo_id, IfMatch=stale, VpcOriginEndpointConfig=cfg)+ assert _vo_error(exc) == (412, "PreconditionFailed", _VO_STALE)+ with pytest.raises(ClientError) as exc:+ cloudfront.delete_vpc_origin(Id=vo_id, IfMatch=stale)+ assert _vo_error(exc) == (412, "PreconditionFailed", _VO_STALE)+++def test_cloudfront_vpc_origin_update_unchanged_and_onto_another_endpoint(cloudfront, vpc_origin):+ """R1 U5/update-D-deployed-unchanged: an update that changes nothing is accepted (202).+ R1 U8/update-dupA-onto-endpoint-of-B: so is moving onto an endpoint another origin uses."""+ vo_id = vpc_origin["VpcOrigin"]["Id"]+ got = cloudfront.get_vpc_origin(Id=vo_id)+ cfg = got["VpcOrigin"]["VpcOriginEndpointConfig"]+ same = cloudfront.update_vpc_origin(Id=vo_id, IfMatch=got["ETag"], VpcOriginEndpointConfig=cfg)+ assert same["ResponseMetadata"]["HTTPStatusCode"] == 202+ other = cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg(Arn=_vo_endpoint("alb", 1)))+ try:+ moved = cloudfront.update_vpc_origin(Id=vo_id, IfMatch=cloudfront.get_vpc_origin(Id=vo_id)["ETag"],+ VpcOriginEndpointConfig={**cfg, "Arn": other["VpcOrigin"]["VpcOriginEndpointConfig"]["Arn"]})+ assert moved["ResponseMetadata"]["HTTPStatusCode"] == 202+ finally:+ _vo_delete(cloudfront, other["VpcOrigin"]["Id"])+++def test_cloudfront_vpc_origin_update_and_delete_id_and_if_match_errors(cloudfront, vpc_origin):+ """V C8, C9, C10: a malformed id answers 400 "Id format is invalid" before anything else.+ R1 U2, U1: If-Match "x" or a made-up ETag answers 400 InvalidIfMatchVersion.+ R1 U3/update-unknown-real-etag, delete-unknown-real-etag (with the create ETag) and R1 U10/delete-C-after-gone+ (with the deployed ETag): a real ETag on an unknown id is 404. Update with the deployed ETag on an unknown id+ isn't captured on its own (U-8)."""+ cfg = vpc_origin["VpcOrigin"]["VpcOriginEndpointConfig"]+ etag = cloudfront.get_vpc_origin(Id=vpc_origin["VpcOrigin"]["Id"])["ETag"]+ vo_id = vpc_origin["VpcOrigin"]["Id"]+ unknown = "vo_Y769dEbaneau0o63mXNjrY"+ cases = [+ ("vo_doesnotexist", "x", (400, "InvalidArgument", "Id format is invalid")),+ (vo_id, "x", (400, "InvalidIfMatchVersion", _VO_BAD_IF_MATCH)),+ (vo_id, "E1ABCDEFGHIJKL", (400, "InvalidIfMatchVersion", _VO_BAD_IF_MATCH)),+ (unknown, "x", (400, "InvalidIfMatchVersion", _VO_BAD_IF_MATCH)),+ (unknown, etag, (404, "EntityNotFound", _VO_NOT_FOUND)),+ ]+ for target, if_match, expected in cases:+ with pytest.raises(ClientError) as exc:+ cloudfront.update_vpc_origin(Id=target, IfMatch=if_match, VpcOriginEndpointConfig=cfg)+ assert _vo_error(exc) == expected+ with pytest.raises(ClientError) as exc:+ cloudfront.delete_vpc_origin(Id=target, IfMatch=if_match)+ assert _vo_error(exc) == expected+ assert cloudfront.get_vpc_origin(Id=vo_id)["ETag"] == etag # R1 U15: failed calls change nothing+++def test_cloudfront_vpc_origin_missing_if_match(cloudfront, vpc_origin):+ """R1 U2/update-A-no-if-match-valid-body, delete-A-no-if-match: no If-Match is a MalformedXML null+ error. R1 U2/update-A-no-if-match-empty-config and U3/update-A-no-if-match-bad-policy: it joins the+ body's own problems, last."""+ vo_id = vpc_origin["VpcOrigin"]["Id"]+ cfg = vpc_origin["VpcOrigin"]["VpcOriginEndpointConfig"]+ path = f"/2020-05-31/vpc-origin/{vo_id}"+ null_if_match = "Value null at 'ifMatch' failed to satisfy constraint: Member must not be null"+ body = f'<VpcOriginEndpointConfig xmlns="{_VO_NS}">{_vo_cfg_xml(cfg)}</VpcOriginEndpointConfig>'+ assert _vo_raw_error("PUT", path, body) == (400, "MalformedXML", f"1 validation error detected: {null_if_match}")+ assert _vo_raw_error("DELETE", path) == (400, "MalformedXML", f"1 validation error detected: {null_if_match}")+ nulls = "; ".join(f"Value null at 'vpcOriginEndpointConfig.{m}' failed to satisfy constraint: Member must not be null"+ for m in ("hTTPPort", "name", "originProtocolPolicy", "hTTPSPort", "arn"))+ assert _vo_raw_error("PUT", path, f'<VpcOriginEndpointConfig xmlns="{_VO_NS}"></VpcOriginEndpointConfig>') == (+ 400, "MalformedXML", f"6 validation errors detected: {nulls}; {null_if_match}")+ bad = body.replace("<OriginProtocolPolicy>https-only<", "<OriginProtocolPolicy>redirect-to-https<")+ assert _vo_raw_error("PUT", path, bad) == (+ 400, "MalformedXML",+ "2 validation errors detected: Value 'redirect-to-https' at 'vpcOriginEndpointConfig.originProtocolPolicy' "+ "failed to satisfy constraint: Member must satisfy enum value set: [https-only, http-only, match-viewer]; "+ f"{null_if_match}")+++def test_cloudfront_vpc_origin_update_check_order(cloudfront, vpc_origin):+ """R1 U3/update-A-fake-etag-bad-policy: schema problems come before a bad If-Match;+ U3/update-A-fake-etag-not-xml: so does a body that isn't XML; U3/update-A-fake-etag-port0: a bad If-Match+ comes before the range checks; U9/update-A-current-etag-*: with a good If-Match they apply as on Create."""+ vo_id = vpc_origin["VpcOrigin"]["Id"]+ cfg = vpc_origin["VpcOrigin"]["VpcOriginEndpointConfig"]+ etag = cloudfront.get_vpc_origin(Id=vo_id)["ETag"]+ fake = "E1ABCDEFGHIJKL"+ with pytest.raises(ClientError) as exc:+ cloudfront.update_vpc_origin(Id=vo_id, IfMatch=fake, VpcOriginEndpointConfig={**cfg, "OriginProtocolPolicy": "redirect-to-https"})+ assert _vo_error(exc)[:2] == (400, "MalformedXML")+ path = f"/2020-05-31/vpc-origin/{vo_id}"+ assert _vo_raw_error("PUT", path, "this is not xml", {"If-Match": fake}) == (400, "MalformedInput", "Could not parse XML")+ assert _vo_raw_error("PUT", path, f'<SomethingElse xmlns="{_VO_NS}"><Name>x</Name></SomethingElse>', {"If-Match": etag}) == (+ 400, "MalformedInput", "SomethingElse is not valid, expected VpcOriginEndpointConfig") # R4 U-1/update-unknown-id-wrong-root+ with pytest.raises(ClientError) as exc:+ cloudfront.update_vpc_origin(Id=vo_id, IfMatch=fake, VpcOriginEndpointConfig={**cfg, "HTTPPort": 0})+ assert _vo_error(exc) == (400, "InvalidIfMatchVersion", _VO_BAD_IF_MATCH)+ for overrides, expected in (+ ({"HTTPPort": 0}, (400, "InvalidArgument", "The parameter origin port is not within allowed range.")),+ ({"OriginSslProtocols": {"Quantity": 2, "Items": ["TLSv1.2"]}}, (+ 400, "InconsistentQuantities",+ "The specified quantity of OriginSslProtocols (2) does not match the actual quantity supplied (1).")),+ ({"Arn": "arn:aws:s3:::bucket"}, (400, "InvalidArgument", "The parameter VpcOriginEndpointConfig Arn Invalid Format.")),+ ):+ with pytest.raises(ClientError) as exc:+ cloudfront.update_vpc_origin(Id=vo_id, IfMatch=etag, VpcOriginEndpointConfig={**cfg, **overrides})+ assert _vo_error(exc) == expected+ assert cloudfront.get_vpc_origin(Id=vo_id)["ETag"] == etag+++def test_cloudfront_vpc_origin_delete(cloudfront):+ """R1 U10/delete-C: 202 with Status Deploying, a new ETag and LastModifiedTime. AWS then keeps the origin+ for minutes (get-C-immediately); MiniStack removes it at once, so Get answers 404 EntityNotFound, its+ tags 404 NoSuchResource and a second delete 404 (R1 U10/get-C-after-gone, list-tags-C-after-gone,+ delete-C-after-gone)."""+ created = cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg(), Tags={"Items": [{"Key": "k", "Value": "v"}]})+ vo_id, arn = created["VpcOrigin"]["Id"], created["VpcOrigin"]["Arn"]+ etag = cloudfront.get_vpc_origin(Id=vo_id)["ETag"]+ deleted = cloudfront.delete_vpc_origin(Id=vo_id, IfMatch=etag)+ assert deleted["ResponseMetadata"]["HTTPStatusCode"] == 202+ assert deleted["VpcOrigin"]["Status"] == "Deploying"+ assert deleted["ETag"] not in (etag, created["ETag"])+ with pytest.raises(ClientError) as exc:+ cloudfront.get_vpc_origin(Id=vo_id)+ assert _vo_error(exc) == (404, "EntityNotFound", _VO_NOT_FOUND)+ with pytest.raises(ClientError) as exc:+ cloudfront.list_tags_for_resource(Resource=arn)+ assert _vo_error(exc) == (404, "NoSuchResource", _VO_NO_RESOURCE)+ with pytest.raises(ClientError) as exc:+ cloudfront.delete_vpc_origin(Id=vo_id, IfMatch=etag)+ assert _vo_error(exc) == (404, "EntityNotFound", _VO_NOT_FOUND)+ assert vo_id not in [s["Id"] for s in cloudfront.list_vpc_origins()["VpcOriginList"]["Items"]]++[email protected]("vo_id,status", [+ ("vo_Y769dEbaneau0o63mXNjrY", 404), # R1 U18/get-control-random-22+ ("xy_Y769dEbaneau0o63mXNjrY", 404), # R1 U18/get-other-prefix+ ("vo_ptyvchyzihjtoldriibswp", 404), # R1 U18/get-lower-only+ ("vo_8792471471766075046691", 404), # R1 U18/get-digits-only+ ("vo_doesnotexist", 400), # V C8/test-id+ ("vo_Y769dEbaneau0o63mXNjr", 400), # R1 U18/get-len21+ ("vo_Y769dEbaneau0o63mXNjrYY", 400), # R1 U18/get-len23+ ("vo_Y769dEbane-au0o63mXNjr", 400), # R1 U18/get-dash+ ("vo_Y769dEbane_au0o63mXNjr", 400), # R1 U18/get-underscore+ ("VO_Y769dEbaneau0o63mXNjrY", 400), # R1 U18/get-upper-prefix+ ("voY769dEbaneau0o63mXNjrYab", 400), # R1 U18/get-no-prefix-25+ ("vo_a", 400), # R1 U18/get-len1+ ("vo_Y769dEbaneau0o63mXNjr.", 400), # R1 U18/get-dot+ ("v_Y769dEbaneau0o63mXNjrY", 404), # R2 U18/get-v-prefix+ ("abcd_Y769dEbaneau0o63mXNjrY", 404), # R2 U18/get-four-letter-prefix+ ("x1_Y769dEbaneau0o63mXNjrY", 400), # R2 U18/get-letter-digit-prefix+ ("vo-Y769dEbaneau0o63mXNjrY", 400), # R2 U18/get-dash-separator+ ("_Y769dEbaneau0o63mXNjrY", 400), # R2 U18/get-underscore-only-prefix+ ("Vo_Y769dEbaneau0o63mXNjrY", 400), # R2 U18/get-mixed-prefix+ ("12_Y769dEbaneau0o63mXNjrY", 400), # R2 U18/get-digits-prefix+ ("dt_Y769dEbaneau0o63mXNjrYabcde", 400), # R2 U18/get-tenant-like-27+], ids=lambda v: str(v))+def test_cloudfront_vpc_origin_get_id_format(cloudfront, vo_id, status):+ """R1 U18, R2 U18 and V C8: an id that isn't lower-case letters, '_' and 22 letters or digits answers+ 400 "Id format is invalid"; a well-formed unknown id answers 404."""+ with pytest.raises(ClientError) as exc:+ cloudfront.get_vpc_origin(Id=vo_id)+ expected = (404, "EntityNotFound", _VO_NOT_FOUND) if status == 404 else (400, "InvalidArgument", "Id format is invalid")+ assert _vo_error(exc) == expected+++_VO_POLICY_ENUM = "Member must satisfy enum value set: [https-only, http-only, match-viewer]"+_VO_SSL_ENUM = "Member must satisfy constraint: [Member must satisfy enum value set: [SSLv3, TLSv1, TLSv1.1, TLSv1.2]]"+_VO_PORT_RANGE = (400, "InvalidArgument", "The parameter origin port is not within allowed range.")+_VO_BAD_ARN = (400, "InvalidArgument", "The parameter VpcOriginEndpointConfig Arn Invalid Format.")+_VO_OTHER_ACCOUNT = (400, "InvalidArgument", "The parameter VpcOriginEndpointConfig Arn contains a mismatched AWS account.")+_VO_QTY_2_1 = (400, "InconsistentQuantities",+ "The specified quantity of OriginSslProtocols (2) does not match the actual quantity supplied (1).")+_VO_NO_PROTOCOLS = (400, "InvalidArgument",+ "The parameter OriginSslProtocols is not valid! Should be one or more from SSLv3, TLSv1, TLSv1.1, and TLSv1.2.")+_VO_TLS13 = ("Value '[TLSv1.3]' at 'vpcOriginEndpointConfig.originSslProtocols.items' failed to satisfy constraint: "+ + _VO_SSL_ENUM)+_VO_REDIRECT = ("Value 'redirect-to-https' at 'vpcOriginEndpointConfig.originProtocolPolicy' failed to satisfy "+ "constraint: " + _VO_POLICY_ENUM)++[email protected]("overrides,expected", [+ ({"OriginProtocolPolicy": "redirect-to-https"}, (400, "MalformedXML", f"1 validation error detected: {_VO_REDIRECT}")), # V C20+ ({"OriginSslProtocols": {"Quantity": 1, "Items": ["TLSv1.3"]}}, (400, "MalformedXML", f"1 validation error detected: {_VO_TLS13}")), # V C24+ ({"OriginProtocolPolicy": "redirect-to-https", "OriginSslProtocols": {"Quantity": 1, "Items": ["TLSv1.3"]}},+ (400, "MalformedXML", f"2 validation errors detected: {_VO_TLS13}; {_VO_REDIRECT}")), # R1 V-order/policy+tls13+ ({"OriginSslProtocols": {"Quantity": 2, "Items": ["TLSv1.3", "TLSv1.1"]}}, (+ 400, "MalformedXML", "1 validation error detected: Value '[TLSv1.3, TLSv1.1]' at "+ "'vpcOriginEndpointConfig.originSslProtocols.items' failed to satisfy constraint: " + _VO_SSL_ENUM)), # R1 V-order/tls13+tls11+ ({"OriginSslProtocols": {"Quantity": 2, "Items": ["TLSv1.3"]}}, (400, "MalformedXML", f"1 validation error detected: {_VO_TLS13}")), # R1 V-order/tls13+qty-mismatch+ ({"HTTPPort": 0}, _VO_PORT_RANGE), # V C21/zero+ ({"HTTPPort": -1}, _VO_PORT_RANGE), # V C21/minus-1+ ({"HTTPPort": 65536}, _VO_PORT_RANGE), # V C21/65536+ ({"HTTPSPort": 0}, _VO_PORT_RANGE), # V C22/zero+ ({"HTTPSPort": 70000}, _VO_PORT_RANGE), # V C22/70000+ ({"HTTPPort": 1}, _VO_PORT_RANGE), # R2 V-port/http-1+ ({"HTTPPort": 79}, _VO_PORT_RANGE), # R2 V-port/http-79+ ({"HTTPPort": 81}, _VO_PORT_RANGE), # R2 V-port/http-81+ ({"HTTPPort": 1023}, _VO_PORT_RANGE), # R2 V-port/http-1023+ ({"HTTPSPort": 1}, _VO_PORT_RANGE), # R2 V-port/https-1+ ({"HTTPSPort": 444}, _VO_PORT_RANGE), # R2 V-port/https-444+ ({"HTTPSPort": 1023}, _VO_PORT_RANGE), # R2 V-port/https-1023+ ({"Name": "n" * 65, "HTTPPort": 0}, _VO_PORT_RANGE), # R2 V-name/name-too-long+port0+ ({"Name": "n" * 65, "OriginSslProtocols": {"Quantity": 2, "Items": ["TLSv1.2"]}},+ (400, "InvalidArgument", "The parameter VPC Origin Name is too big.")), # R2 V-name/name-too-long+qty-mismatch+ ({"Name": "n" * 65, "OriginSslProtocols": {"Quantity": 0, "Items": []}},+ (400, "InvalidArgument", "The parameter VPC Origin Name is too big.")), # R2 V-name/name-too-long+qty0+ ({"Name": "n" * 65, "Arn": "arn:aws:s3:::bucket"},+ (400, "InvalidArgument", "The parameter VPC Origin Name is too big.")), # R2 V-name/name-too-long+s3-arn+ ({"Name": "n" * 65, "OriginProtocolPolicy": "redirect-to-https"},+ (400, "MalformedXML", f"1 validation error detected: {_VO_REDIRECT}")), # R2 V-name/name-too-long+bad-policy+ ({"Name": ""}, (400, "InvalidArgument", "The parameter VPC Origin Name is too small or empty.")), # R2 V-name/name-empty-string+ ({"OriginSslProtocols": {"Quantity": 2, "Items": ["TLSv1.2"]}}, _VO_QTY_2_1), # V C25+ ({"OriginSslProtocols": {"Quantity": 0, "Items": []}}, _VO_NO_PROTOCOLS), # V C26/qty0-empty+ ({"Arn": "arn:aws:s3:::bucket"}, _VO_BAD_ARN), # V C23+ ({"Arn": f"arn:aws:elasticloadbalancing:us-east-1:{_VO_ACCOUNT}:targetgroup/tg/0123456789abcdef"}, _VO_BAD_ARN), # V C35/nonexistent-targetgroup+ ({"Arn": f"arn:aws:elasticloadbalancing:us-east-1:{_VO_ACCOUNT}:loadbalancer/gwy/example/0123456789abcdef"}, _VO_BAD_ARN), # R1 V-arn/gwy-lb+ ({"Arn": f"arn:aws:elasticloadbalancing:us-east-1:{_VO_ACCOUNT}:loadbalancer/example"}, _VO_BAD_ARN), # R1 V-arn/classic-elb+ ({"Arn": f"arn:aws:elasticloadbalancing:us-east-1:{_VO_ACCOUNT}:listener/app/example/0123456789abcdef/0123456789abcdef"}, _VO_BAD_ARN), # R1 V-arn/alb-listener+ ({"Arn": f"arn:aws-cn:elasticloadbalancing:us-east-1:{_VO_ACCOUNT}:loadbalancer/app/example/0123456789abcdef"}, _VO_BAD_ARN), # R1 V-arn/alb-other-partition+ ({"Arn": f"arn:aws:elasticloadbalancing::{_VO_ACCOUNT}:loadbalancer/app/example/0123456789abcdef"}, _VO_BAD_ARN), # R1 V-arn/alb-no-region+ ({"Arn": f"arn:aws:ec2:us-east-1:{_VO_ACCOUNT}:instance/xyz"}, _VO_BAD_ARN), # R1 V-arn/ec2-bad-id+ ({"Arn": f"arn:aws:ec2:us-east-1:{_VO_ACCOUNT}:vpc/vpc-0123456789abcdef0"}, _VO_BAD_ARN), # R1 V-arn/ec2-vpc+ ({"Arn": "internal-alb.example.com"}, _VO_BAD_ARN), # R1 V-arn/not-an-arn+ ({"Arn": f"arn:aws:lambda:us-east-1:{_VO_ACCOUNT}:function:example"}, _VO_BAD_ARN), # R1 V-arn/lambda+ ({"Arn": "arn:aws:elasticloadbalancing:us-east-1:111122223333:loadbalancer/app/vo-other/0123456789abcdef"}, _VO_OTHER_ACCOUNT), # V C35/test-style-alb-account-000000000000+ ({"Arn": "arn:aws:ec2:us-east-1:111122223333:instance/i-0123456789abcdef0"}, _VO_OTHER_ACCOUNT), # R1 V-arn/ec2-other-account+ ({"Name": "n" * 65}, (400, "InvalidArgument", "The parameter VPC Origin Name is too big.")), # R1 V-name/name-65+ ({"Name": "has space"}, (400, "InvalidArgument",+ "The parameter Name contains characters other than alphanumericals, dashes, and underscores.")), # R1 V-name/name-space+ ({"Name": "a/b"}, (400, "InvalidArgument",+ "The parameter Name contains characters other than alphanumericals, dashes, and underscores.")), # R1 V-name/name-slash+ ({"HTTPPort": 0, "Arn": "arn:aws:s3:::bucket"}, _VO_PORT_RANGE), # R1 V-order/port0+s3-arn+ ({"HTTPPort": 0, "OriginSslProtocols": {"Quantity": 2, "Items": ["TLSv1.2"]}}, _VO_PORT_RANGE), # R1 V-order/port0+qty-mismatch+ ({"Arn": "arn:aws:s3:::bucket", "OriginSslProtocols": {"Quantity": 2, "Items": ["TLSv1.2"]}}, _VO_QTY_2_1), # R1 V-order/s3-arn+qty-mismatch+ ({"HTTPPort": 0, "OriginSslProtocols": {"Quantity": 0, "Items": []}}, _VO_PORT_RANGE), # R1 V-order/qty0+port0+ ({"Arn": "arn:aws:s3:::bucket", "OriginSslProtocols": {"Quantity": 0, "Items": []}}, _VO_NO_PROTOCOLS), # R1 V-order/qty0+s3-arn+ ({"Arn": "arn:aws:elasticloadbalancing:us-east-1:111122223333:loadbalancer/app/vo-other/0123456789abcdef", "HTTPPort": 0}, _VO_PORT_RANGE), # R1 V-order/other-account+port0+ ({"Arn": "arn:aws:elasticloadbalancing:us-east-1:111122223333:loadbalancer/app/vo-other/0123456789abcdef", "OriginSslProtocols": {"Quantity": 2, "Items": ["TLSv1.2"]}}, _VO_QTY_2_1), # R1 V-order/other-account+qty-mismatch+ ({"OriginProtocolPolicy": "redirect-to-https", "HTTPPort": 0}, (400, "MalformedXML", f"1 validation error detected: {_VO_REDIRECT}")), # R1 V-order/policy+port0+ ({"Arn": "arn:aws:s3:::bucket", "OriginSslProtocols": {"Quantity": 1, "Items": ["TLSv1.3"]}},+ (400, "MalformedXML", f"1 validation error detected: {_VO_TLS13}")), # R1 V-order/s3-arn+tls13+])+def test_cloudfront_vpc_origin_create_rejects(cloudfront, overrides, expected):+ """Create validation with AWS's codes and messages, and the order among them: schema problems+ (MalformedXML) first, then the ports (80, 443 or 1024 to 65535), the name, the protocol quantity and+ list, then the endpoint ARN's format and account. Each case names its capture."""+ with pytest.raises(ClientError) as exc:+ cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg(**overrides))+ assert _vo_error(exc) == expected+++_VO_TLS13_XML = ("<OriginSslProtocols><Quantity>1</Quantity><Items><SslProtocol>TLSv1.3</SslProtocol></Items>"+ "</OriginSslProtocols>")+++def _vo_null(member):+ return f"Value null at 'vpcOriginEndpointConfig{member}' failed to satisfy constraint: Member must not be null"++[email protected]("make_body,expected", [+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, http="eighty")), (400, "MalformedInput", None)), # V C27; R1 U20/http-eighty (no <Message>)+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, http="80.0")), (400, "MalformedInput", None)), # R1 U20/http-decimal+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, http=" 80 ")), (400, "MalformedInput", None)), # R1 U20/http-space+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, http="")), (400, "MalformedInput", "missing value for decimal type")), # R1 U20/http-empty+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, ssl="<OriginSslProtocols><Quantity>one</Quantity><Items>"+ "<SslProtocol>TLSv1.2</SslProtocol></Items></OriginSslProtocols>")),+ (400, "MalformedInput", None)), # V C31; R1 U20/qty-one+ (lambda c: "this is not xml", (400, "MalformedInput", "Could not parse XML")), # V C32; R1 U20/not-xml+ (lambda c: _vo_create_xml(_vo_cfg_xml(c)).replace("CreateVpcOriginRequest", "SomethingElse"),+ (400, "MalformedInput", "SomethingElse is not valid, expected CreateVpcOriginRequest")), # R1 U20/wrong-root+ (lambda c: "", (400, "MalformedXML", "1 validation error detected: Value null at 'vpcOriginEndpointConfig' "+ "failed to satisfy constraint: Member must not be null")), # R1 U20/empty-body+ (lambda c: f'<CreateVpcOriginRequest xmlns="{_VO_NS}"></CreateVpcOriginRequest>',+ (400, "MalformedXML", "1 validation error detected: Value null at 'vpcOriginEndpointConfig' "+ "failed to satisfy constraint: Member must not be null")), # V C29+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, omit=("HTTPPort",))), (400, "MalformedXML", f"1 validation error detected: {_vo_null('.hTTPPort')}")), # V C28/missing-http+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, omit=("HTTPSPort",))), (400, "MalformedXML", f"1 validation error detected: {_vo_null('.hTTPSPort')}")), # V C28/missing-https+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, omit=("Name",))), (400, "MalformedXML", f"1 validation error detected: {_vo_null('.name')}")), # V C30/missing-name+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, omit=("Arn",))), (400, "MalformedXML", f"1 validation error detected: {_vo_null('.arn')}")), # V C30/missing-arn+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, omit=("OriginProtocolPolicy",))),+ (400, "MalformedXML", f"1 validation error detected: {_vo_null('.originProtocolPolicy')}")), # V C33+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, omit=("Name", "Arn"))),+ (400, "MalformedXML", f"2 validation errors detected: {_vo_null('.name')}; {_vo_null('.arn')}")), # R1 V-order/raw-missing-name-and-arn+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, omit=("HTTPPort", "OriginProtocolPolicy"))),+ (400, "MalformedXML", f"2 validation errors detected: {_vo_null('.hTTPPort')}; {_vo_null('.originProtocolPolicy')}")), # R1 V-order/raw-missing-http-and-policy+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, omit=("Arn", "HTTPSPort"))),+ (400, "MalformedXML", f"2 validation errors detected: {_vo_null('.hTTPSPort')}; {_vo_null('.arn')}")), # R1 V-order/raw-missing-arn-and-https+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, omit=("HTTPPort",)).replace(">https-only<", ">redirect-to-https<")),+ (400, "MalformedXML", f"2 validation errors detected: {_vo_null('.hTTPPort')}; {_VO_REDIRECT}")), # R1 V-order/raw-missing-http-bad-policy+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, ssl="<OriginSslProtocols><Quantity>0</Quantity></OriginSslProtocols>")),+ (400, "MalformedXML", f"1 validation error detected: {_vo_null('.originSslProtocols.items')}")), # R1 U20/ssl-without-items+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, ssl="<OriginSslProtocols><Items><SslProtocol>TLSv1.2</SslProtocol>"+ "</Items></OriginSslProtocols>")),+ (400, "MalformedXML", f"1 validation error detected: {_vo_null('.originSslProtocols.quantity')}")), # R1 U20/ssl-without-quantity+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, ssl="<OriginSslProtocols><Quantity>0</Quantity><Items/></OriginSslProtocols>")),+ _VO_NO_PROTOCOLS), # V C26/raw-qty0-items-empty+ (lambda c: _vo_create_xml(_vo_cfg_xml(c).replace(f"<Name>{c['Name']}</Name>", "<Name></Name>")),+ (400, "InvalidArgument", "The parameter VPC Origin Name is too small or empty.")), # R1 V-name/raw-name-empty+ (lambda c: _vo_create_xml(""), (400, "MalformedXML", "5 validation errors detected: " + "; ".join(+ _vo_null(m) for m in (".hTTPPort", ".name", ".originProtocolPolicy", ".hTTPSPort", ".arn")))), # R2 V-order/raw-empty-config+ (lambda c: _vo_create_xml(_VO_TLS13_XML), (400, "MalformedXML", "6 validation errors detected: " + "; ".join(+ [_vo_null(".hTTPPort"), _VO_TLS13] + [_vo_null(m) for m in (".name", ".originProtocolPolicy", ".hTTPSPort", ".arn")]))), # R2 V-order/raw-only-bad-ssl+ (lambda c: _vo_create_xml(f"<Name>{c['Name']}</Name><Arn>{c['Arn']}</Arn>"+ f"<OriginProtocolPolicy>redirect-to-https</OriginProtocolPolicy>{_VO_TLS13_XML}"),+ (400, "MalformedXML", "4 validation errors detected: " + "; ".join(+ [_vo_null(".hTTPPort"), _VO_TLS13, _VO_REDIRECT, _vo_null(".hTTPSPort")]))), # R2 V-order/raw-name-arn-only-bad-policy-bad-ssl+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, omit=("Name",), ssl=_VO_TLS13_XML)),+ (400, "MalformedXML", f"2 validation errors detected: {_VO_TLS13}; {_vo_null('.name')}")), # R2 V-order/raw-all-but-name-bad-ssl+ (lambda c: _vo_create_xml("<OriginSslProtocols><Items><SslProtocol>TLSv1.3</SslProtocol></Items></OriginSslProtocols>"),+ (400, "MalformedXML", "7 validation errors detected: " + "; ".join(+ [_vo_null(".hTTPPort"), _vo_null(".originSslProtocols.quantity"), _VO_TLS13]+ + [_vo_null(m) for m in (".name", ".originProtocolPolicy", ".hTTPSPort", ".arn")]))), # R3 V-order/raw-items-without-quantity-bad-ssl-rest-null+ (lambda c: _vo_create_xml("<IpAddressType>bogus</IpAddressType>"), (400, "MalformedXML", "6 validation errors detected: " + "; ".join(+ [_vo_null(m) for m in (".hTTPPort", ".name", ".originProtocolPolicy", ".hTTPSPort", ".arn")]+ + ["Value 'bogus' at 'vpcOriginEndpointConfig.ipAddressType' failed to satisfy constraint: "+ "Member must satisfy enum value set: [ipv4, dualstack]"]))), # R3 V-order/raw-bad-ip-address-type-rest-null+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, http="eighty", omit=("Name",))), (400, "MalformedInput", None)), # R3 V-order/raw-eighty-missing-name+ (lambda c: _vo_create_xml(_vo_cfg_xml(c, http="eighty").replace(">https-only<", ">nope<")),+ (400, "MalformedInput", None)), # R3 V-order/raw-eighty-bad-policy+ (lambda c: _vo_create_xml(_vo_cfg_xml(c) + "<IpAddressType>ipv6</IpAddressType>"),+ (400, "MalformedXML", "1 validation error detected: Value 'ipv6' at 'vpcOriginEndpointConfig.ipAddressType' "+ "failed to satisfy constraint: Member must satisfy enum value set: [ipv4, dualstack]")), # R2 V-ip/ip-address-type-ipv6+ (lambda c: _vo_create_xml(_vo_cfg_xml(c) + "<IpAddressType></IpAddressType>"),+ (400, "MalformedXML", "1 validation error detected: Value '' at 'vpcOriginEndpointConfig.ipAddressType' "+ "failed to satisfy constraint: Member must satisfy enum value set: [ipv4, dualstack]")), # R2 V-ip/ip-address-type-empty+])+def test_cloudfront_vpc_origin_create_rejects_raw_xml(make_body, expected):+ """Inputs botocore would refuse, sent as raw XML. Each case names its capture."""+ assert _vo_raw_error("POST", "/2020-05-31/vpc-origin", make_body(_vo_cfg())) == expected++[email protected]("arn,message", [+ (f"arn:aws:elasticloadbalancing:us-east-1:{_VO_ACCOUNT}:loadbalancer/app/example/0123456789abcdef",+ "The parameter VpcOriginEndpointConfig Arn LoadBalancerNotFound."), # V C35/nonexistent-alb-same-account+ (f"arn:aws:elasticloadbalancing:us-east-1:{_VO_ACCOUNT}:loadbalancer/net/example/0123456789abcdef",+ "The parameter VpcOriginEndpointConfig Arn LoadBalancerNotFound."), # R1 V-arn/nlb-missing+ (f"arn:aws:elasticloadbalancing:us-west-2:{_VO_ACCOUNT}:loadbalancer/app/example/0123456789abcdef",+ "The parameter VpcOriginEndpointConfig Arn LoadBalancerNotFound."), # R1 V-arn/alb-other-region+ (f"arn:aws:ec2:us-east-1:{_VO_ACCOUNT}:instance/i-12345678",+ "The parameter VpcOriginEndpointConfig Arn InvalidInstanceID.NotFound."), # R1 V-arn/ec2-short-id+ (f"arn:aws:ec2:us-east-1:{_VO_ACCOUNT}:instance/i-0123456789abcdef0",+ "The parameter VpcOriginEndpointConfig Arn InvalidInstanceID.Malformed."), # V C35/nonexistent-ec2-instance+ (f"arn:aws:ec2:us-west-2:{_VO_ACCOUNT}:instance/i-0123456789abcdef0",+ "The parameter VpcOriginEndpointConfig Arn InvalidInstanceID.Malformed."), # R1 V-arn/ec2-other-region+], ids=["alb", "nlb", "alb-other-region", "ec2-short-id", "ec2", "ec2-other-region"])+def test_cloudfront_vpc_origin_endpoint_must_exist(cloudfront, arn, message):+ """An endpoint ARN with the right format and account must name a load balancer or instance that exists,+ in the ARN's region."""+ with pytest.raises(ClientError) as exc:+ cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg(Arn=arn))+ assert _vo_error(exc) == (400, "InvalidArgument", message)++[email protected]("kind", ["alb", "nlb", "instance"])+def test_cloudfront_vpc_origin_accepts_existing_endpoints(cloudfront, kind):+ """R1 U-create/create-A (ALB), create-N (NLB), V C35/create-real-ec2-instance: an existing ALB, NLB or+ instance is accepted (202). MiniStack's ELBv2 names every load balancer's ARN `loadbalancer/app/...`, also+ for Type=network, so the NLB case uses that ARN; the `loadbalancer/net/` format itself is covered by+ R1 V-arn/nlb-missing in test_cloudfront_vpc_origin_endpoint_must_exist."""+ created = cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg(Arn=_vo_endpoint(kind)))+ try:+ assert created["ResponseMetadata"]["HTTPStatusCode"] == 202+ finally:+ _vo_delete(cloudfront, created["VpcOrigin"]["Id"])+++def test_cloudfront_vpc_origin_endpoint_checked_on_update(cloudfront, vpc_origin):+ """R1 U9/update-A-current-etag-missing-alb: Update checks the endpoint too."""+ got = cloudfront.get_vpc_origin(Id=vpc_origin["VpcOrigin"]["Id"])+ missing = f"arn:aws:elasticloadbalancing:us-east-1:{_VO_ACCOUNT}:loadbalancer/app/example/0123456789abcdef"+ with pytest.raises(ClientError) as exc:+ cloudfront.update_vpc_origin(Id=vpc_origin["VpcOrigin"]["Id"], IfMatch=got["ETag"], VpcOriginEndpointConfig={+ **got["VpcOrigin"]["VpcOriginEndpointConfig"], "Arn": missing})+ assert _vo_error(exc) == (400, "InvalidArgument", "The parameter VpcOriginEndpointConfig Arn LoadBalancerNotFound.")+++def test_cloudfront_vpc_origin_name_limits_accepted(cloudfront):+ """R1 V-name/name-64: a 64-character name is accepted; R1 U20/http-leading-zero: so is HTTPPort 080."""+ created = cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg(Name="n" * 52 + _uuid_mod.uuid4().hex[:12]))+ _vo_delete(cloudfront, created["VpcOrigin"]["Id"])+ cfg = _vo_cfg()+ status, _, text = _vo_raw("POST", "/2020-05-31/vpc-origin", _vo_create_xml(_vo_cfg_xml(cfg, http="080")))+ assert status == 202 and "<HTTPPort>80</HTTPPort>" in text+ _vo_delete(cloudfront, re.search(r"<Id>([^<]+)</Id>", text).group(1))+++def test_cloudfront_vpc_origin_list_pagination(cloudfront):+ """R1 U11/page-size-1-*, page-size-2-*, marker-is-A: sorted by id, NextMarker is the last id of a page+ that leaves items behind, Marker is exclusive, and the last page has no NextMarker. V C37, C38, C39+ and R1 V-list/max-items-zero (raw): no Marker or IsTruncated element, and an empty <Items/>."""+ ids = sorted(cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg())["VpcOrigin"]["Id"] for _ in range(3))+ try:+ listed = [s["Id"] for s in cloudfront.list_vpc_origins()["VpcOriginList"]["Items"]]+ assert listed == sorted(listed)+ seen, marker = [], None+ while True:+ kwargs = {"MaxItems": "1", **({"Marker": marker} if marker else {})}+ page = cloudfront.list_vpc_origins(**kwargs)["VpcOriginList"]+ assert set(page) <= {"NextMarker", "MaxItems", "Quantity", "Items"}+ assert page["MaxItems"] == 1 and page["Quantity"] == len(page["Items"]) == 1+ seen.append(page["Items"][0]["Id"])+ if "NextMarker" not in page:+ break+ assert page["NextMarker"] == page["Items"][0]["Id"]+ marker = page["NextMarker"]+ assert seen == listed+ after = cloudfront.list_vpc_origins(Marker=ids[0])["VpcOriginList"]["Items"]+ assert [s["Id"] for s in after] == [i for i in listed if i > ids[0]]+ status, _, text = _vo_raw("GET", "/2020-05-31/vpc-origin?MaxItems=0")+ assert status == 200+ assert re.search(r"<VpcOriginList[^>]*><MaxItems>0</MaxItems><Quantity>0</Quantity><Items\s*/></VpcOriginList>", text)+ finally:+ for vo_id in ids:+ _vo_delete(cloudfront, vo_id)+++def test_cloudfront_vpc_origin_list_summary(cloudfront, vpc_origin):+ """R1 U11 raw bodies: the summary fields and their values."""+ vo = cloudfront.get_vpc_origin(Id=vpc_origin["VpcOrigin"]["Id"])["VpcOrigin"]+ summary = next(s for s in cloudfront.list_vpc_origins()["VpcOriginList"]["Items"] if s["Id"] == vo["Id"])+ assert summary == {"Id": vo["Id"], "Name": vo["VpcOriginEndpointConfig"]["Name"], "Status": "Deployed",+ "CreatedTime": vo["CreatedTime"], "LastModifiedTime": vo["LastModifiedTime"], "Arn": vo["Arn"],+ "AccountId": _VO_ACCOUNT, "OriginEndpointArn": vo["VpcOriginEndpointConfig"]["Arn"]}++[email protected]("max_items,expected", [+ (None, 100), ("5", 5), ("1000", 100), ("101", 100), ("", 100),+], ids=["default", "5", "1000", "101", "empty"])+def test_cloudfront_vpc_origin_list_max_items(cloudfront, max_items, expected):+ """V C37/no-params, C38; R1 V-list/max-items-one-thousand, max-items-101, max-items-empty: the default+ is 100, and a larger value comes back as 100."""+ kwargs = {} if max_items is None else {"MaxItems": max_items}+ assert cloudfront.list_vpc_origins(**kwargs)["VpcOriginList"]["MaxItems"] == expected++[email protected]("params,expected", [+ ({"MaxItems": "abc"}, (400, "InvalidArgument", "MaxItems must be a non-zero positive integer.")), # V C40+ ({"MaxItems": "-1"}, (400, "InvalidArgument", "MaxItems must be a non-zero positive integer.")), # V C41+ ({"MaxItems": "1.5"}, (400, "InvalidArgument", "MaxItems must be a non-zero positive integer.")), # R1 V-list/max-items-decimal+ ({"Marker": "vo_doesnotexist"}, (404, "EntityNotFound", "The request contains an invalid marker.")), # V C42/unknown-marker+ ({"Marker": "vo_Y769dEbaneau0o63mXNjrY"}, (404, "EntityNotFound", "The request contains an invalid marker.")), # V C42/random-marker+], ids=["abc", "minus-1", "decimal", "bad-marker", "unknown-marker"])+def test_cloudfront_vpc_origin_list_rejects(cloudfront, params, expected):+ """V C40, C41, C42; R1 V-list/max-items-decimal."""+ with pytest.raises(ClientError) as exc:+ cloudfront.list_vpc_origins(**params)+ assert _vo_error(exc) == expected++[email protected]("overrides", [+ {"HTTPPort": 443}, {"HTTPPort": 1024}, {"HTTPPort": 65535}, # R2 V-port/http-443, http-1024, http-65535+ {"HTTPSPort": 80}, {"HTTPSPort": 1024}, {"HTTPSPort": 65535}, # R2 V-port/https-80, https-1024, https-65535+ {"OriginProtocolPolicy": "match-viewer",+ "OriginSslProtocols": {"Quantity": 4, "Items": ["SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"]}}, # R2 V-values/match-viewer-all-protocols+ {"OriginProtocolPolicy": "http-only", "OriginSslProtocols": {"Quantity": 1, "Items": ["SSLv3"]}}, # R2 V-values/http-only-sslv3+])+def test_cloudfront_vpc_origin_accepts_values(cloudfront, overrides):+ """R2 V-port, V-values: these ports, policies and protocols are accepted and echoed."""+ created = cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg(**overrides))+ try:+ cfg = created["VpcOrigin"]["VpcOriginEndpointConfig"]+ assert {k: cfg[k] for k in overrides} == overrides+ finally:+ _vo_delete(cloudfront, created["VpcOrigin"]["Id"])++[email protected]("items,stored", [+ (["TLSv1.2", "TLSv1.2"], ["TLSv1.2"]), # R2 V-name/duplicate-protocols+ (["TLSv1.2", "TLSv1"], ["TLSv1", "TLSv1.2"]), # R2 V-name/unordered-protocols+], ids=["duplicates", "unordered"])+def test_cloudfront_vpc_origin_protocols_stored_once_in_enum_order(cloudfront, items, stored):+ """R2 V-name/duplicate-protocols, unordered-protocols: Quantity is checked against the items sent, then+ each protocol is stored once, in the order SSLv3, TLSv1, TLSv1.1, TLSv1.2."""+ created = cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg(+ OriginSslProtocols={"Quantity": len(items), "Items": items}))+ try:+ assert created["VpcOrigin"]["VpcOriginEndpointConfig"]["OriginSslProtocols"] == {+ "Quantity": len(stored), "Items": stored}+ finally:+ _vo_delete(cloudfront, created["VpcOrigin"]["Id"])++[email protected]("ip_type", ["ipv4", "dualstack"])+def test_cloudfront_vpc_origin_ip_address_type(cloudfront, ip_type):+ """R2 V-ip/ip-address-type-ipv4, ip-address-type-dualstack (raw): IpAddressType is accepted and echoed.+ botocore 1.43 doesn't model the member, so the request is raw XML."""+ cfg = _vo_cfg()+ status, _, text = _vo_raw("POST", "/2020-05-31/vpc-origin",+ _vo_create_xml(_vo_cfg_xml(cfg) + f"<IpAddressType>{ip_type}</IpAddressType>"))+ vo_id = re.search(r"<Id>([^<]+)</Id>", text).group(1)+ try:+ assert status == 202 and f"<IpAddressType>{ip_type}</IpAddressType>" in text+ _, _, got = _vo_raw("GET", f"/2020-05-31/vpc-origin/{vo_id}")+ assert f"<IpAddressType>{ip_type}</IpAddressType>" in got+ finally:+ _vo_delete(cloudfront, vo_id)+++def test_cloudfront_vpc_origin_names_are_case_sensitive(cloudfront, vpc_origin):+ """R2 V-name/dup-name-other-case: the same name in another case is a different name."""+ name = vpc_origin["VpcOrigin"]["VpcOriginEndpointConfig"]["Name"]+ other = cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg(Name=name.upper()))+ _vo_delete(cloudfront, other["VpcOrigin"]["Id"])+ assert other["ResponseMetadata"]["HTTPStatusCode"] == 202++[email protected]("overrides,expected", [+ ({"HTTPPort": 0}, _VO_PORT_RANGE), # R2 V-name/dup-name+port0+ ({"OriginSslProtocols": {"Quantity": 2, "Items": ["TLSv1.2"]}}, _VO_QTY_2_1), # R2 V-name/dup-name+qty-mismatch+ ({"Arn": "arn:aws:s3:::bucket"}, _VO_BAD_ARN), # R2 V-name/dup-name+s3-arn+ ({"Arn": "arn:aws:elasticloadbalancing:us-east-1:111122223333:loadbalancer/app/vo-other/0123456789abcdef"},+ _VO_OTHER_ACCOUNT), # R2 V-name/dup-name+other-account+ ({"Arn": f"arn:aws:elasticloadbalancing:us-east-1:{_VO_ACCOUNT}:loadbalancer/app/example/0123456789abcdef"},+ (400, "InvalidArgument", "The parameter VpcOriginEndpointConfig Arn LoadBalancerNotFound.")), # R2 V-name/dup-name+missing-alb+])+def test_cloudfront_vpc_origin_name_taken_is_checked_last(cloudfront, vpc_origin, overrides, expected):+ """R2 V-name/dup-name+*: a reused name is reported only after every other check passes."""+ name = vpc_origin["VpcOrigin"]["VpcOriginEndpointConfig"]["Name"]+ with pytest.raises(ClientError) as exc:+ cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg(Name=name, **overrides))+ assert _vo_error(exc) == expected+++_VO_IN_USE = ("The specified VPC origin is currently associated with one or more distributions. Please "+ "disassociate the VPC origin from all distributions before updating or deleting")+++def _vo_distribution_config(vo_id, comment=""):+ return {+ "CallerReference": str(_uuid_mod.uuid4()), "Comment": comment, "Enabled": True,+ "Origins": {"Quantity": 1, "Items": [{"Id": "api", "DomainName": "api.internal.example.com",+ "VpcOriginConfig": {"VpcOriginId": vo_id}}]},+ "DefaultCacheBehavior": {"TargetOriginId": "api", "ViewerProtocolPolicy": "redirect-to-https",+ "CachePolicyId": "4135ea2d-6df8-44a3-9df3-4b5a84be39ad"},+ }+++def _vo_delete_distribution(cloudfront, dist_id):+ got = cloudfront.get_distribution_config(Id=dist_id)+ cfg = got["DistributionConfig"]+ etag = got["ETag"]+ if cfg["Enabled"]:+ etag = cloudfront.update_distribution(Id=dist_id, IfMatch=etag, DistributionConfig={**cfg, "Enabled": False})["ETag"]+ cloudfront.delete_distribution(Id=dist_id, IfMatch=etag)+++def test_cloudfront_vpc_origin_in_use_by_distribution(cloudfront, vpc_origin):+ """R2 U15/create-distribution-on-B-deploying, get-distribution-immediate: the distribution keeps+ VpcOriginConfig and AWS fills in OriginReadTimeout 30 and OriginKeepaliveTimeout 5.+ R2 U13/delete-B-while-distribution-in-progress, update-B-while-referenced: while it names the origin,+ Delete answers 409 CannotDeleteEntityWhileInUse and Update 409 CannotUpdateEntityWhileInUse.+ R3b U13: a stale ETag (412) and the range checks come first; in use comes before a reused name; an+ update that changes nothing is accepted."""+ vo_id = vpc_origin["VpcOrigin"]["Id"]+ created = cloudfront.create_distribution(DistributionConfig=_vo_distribution_config(vo_id))+ dist_id = created["Distribution"]["Id"]+ other = cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg())+ try:+ origin = cloudfront.get_distribution(Id=dist_id)["Distribution"]["DistributionConfig"]["Origins"]["Items"][0]+ assert origin["VpcOriginConfig"] == {"VpcOriginId": vo_id, "OriginReadTimeout": 30, "OriginKeepaliveTimeout": 5}+ got = cloudfront.get_vpc_origin(Id=vo_id)+ with pytest.raises(ClientError) as exc:+ cloudfront.delete_vpc_origin(Id=vo_id, IfMatch=got["ETag"])+ assert _vo_error(exc) == (409, "CannotDeleteEntityWhileInUse", _VO_IN_USE)+ with pytest.raises(ClientError) as exc:+ cloudfront.update_vpc_origin(Id=vo_id, IfMatch=got["ETag"],+ VpcOriginEndpointConfig={**got["VpcOrigin"]["VpcOriginEndpointConfig"], "HTTPSPort": 8443})+ assert _vo_error(exc) == (409, "CannotUpdateEntityWhileInUse", _VO_IN_USE)+ cfg = got["VpcOrigin"]["VpcOriginEndpointConfig"]+ for overrides, expected in (+ ({"HTTPPort": 0}, _VO_PORT_RANGE), # R3b U13/update-B-port0-in-use+ ({"Name": other["VpcOrigin"]["VpcOriginEndpointConfig"]["Name"]},+ (409, "CannotUpdateEntityWhileInUse", _VO_IN_USE)), # R3b U13/update-B-name-of-A-in-use+ ):+ with pytest.raises(ClientError) as exc:+ cloudfront.update_vpc_origin(Id=vo_id, IfMatch=got["ETag"], VpcOriginEndpointConfig={**cfg, **overrides})+ assert _vo_error(exc) == expected+ for call in (lambda: cloudfront.update_vpc_origin(Id=vo_id, IfMatch=vpc_origin["ETag"], VpcOriginEndpointConfig=cfg),+ lambda: cloudfront.delete_vpc_origin(Id=vo_id, IfMatch=vpc_origin["ETag"])):+ with pytest.raises(ClientError) as exc: # R3b U13/update-B-stale-etag-in-use, delete-B-stale-etag-in-use+ call()+ assert _vo_error(exc) == (412, "PreconditionFailed", _VO_STALE)+ same = cloudfront.update_vpc_origin(Id=vo_id, IfMatch=got["ETag"], VpcOriginEndpointConfig=cfg)+ # R3b U13/update-B-unchanged-in-use: 202 with the origin as stored, no new version.+ assert same["ResponseMetadata"]["HTTPStatusCode"] == 202+ assert same["ETag"] == got["ETag"]+ assert same["VpcOrigin"]["Status"] == "Deployed"+ assert same["VpcOrigin"]["LastModifiedTime"] == got["VpcOrigin"]["LastModifiedTime"]+ finally:+ _vo_delete_distribution(cloudfront, dist_id)+ _vo_delete(cloudfront, other["VpcOrigin"]["Id"])+++def test_cloudfront_vpc_origin_free_after_distribution_moves_off(cloudfront, vpc_origin):+ """R3b U13/update-distribution-off-B, delete-B-right-after-distribution-update: once the distribution+ no longer names the origin, the origin can be deleted at once."""+ vo_id = vpc_origin["VpcOrigin"]["Id"]+ created = cloudfront.create_distribution(DistributionConfig=_vo_distribution_config(vo_id))+ dist_id = created["Distribution"]["Id"]+ try:+ got = cloudfront.get_distribution_config(Id=dist_id)+ cfg = {**got["DistributionConfig"], "Enabled": False, "Origins": {"Quantity": 1, "Items": [{+ "Id": "api", "DomainName": "origin.example.com",+ "CustomOriginConfig": {"HTTPPort": 80, "HTTPSPort": 443, "OriginProtocolPolicy": "https-only",+ "OriginSslProtocols": {"Quantity": 1, "Items": ["TLSv1.2"]}}}]}}+ cloudfront.update_distribution(Id=dist_id, IfMatch=got["ETag"], DistributionConfig=cfg)+ deleted = cloudfront.delete_vpc_origin(Id=vo_id, IfMatch=cloudfront.get_vpc_origin(Id=vo_id)["ETag"])+ assert deleted["ResponseMetadata"]["HTTPStatusCode"] == 202+ finally:+ _vo_delete_distribution(cloudfront, dist_id)+++def test_cloudfront_vpc_origin_id_in_comment_is_not_a_reference(cloudfront, vpc_origin):+ """R2 U14/delete-A-id-only-in-comment: an origin named only in a distribution's Comment can be deleted."""+ vo_id = vpc_origin["VpcOrigin"]["Id"]+ other = cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg())+ created = cloudfront.create_distribution(DistributionConfig=_vo_distribution_config(+ other["VpcOrigin"]["Id"], comment=f"other origin {vo_id}"))+ try:+ deleted = cloudfront.delete_vpc_origin(Id=vo_id, IfMatch=cloudfront.get_vpc_origin(Id=vo_id)["ETag"])+ assert deleted["ResponseMetadata"]["HTTPStatusCode"] == 202+ finally:+ _vo_delete_distribution(cloudfront, created["Distribution"]["Id"])+ _vo_delete(cloudfront, other["VpcOrigin"]["Id"])++[email protected]("vo_id", ["vo_Y769dEbaneau0o63mXNjrY", "vo_doesnotexist"], ids=["unknown", "malformed"])+def test_cloudfront_distribution_rejects_unknown_vpc_origin(cloudfront, vo_id):+ """R2 U15/create-distribution-dunk, create-distribution-dbad: a VpcOriginId that names no origin+ answers 404 EntityNotFound."""+ with pytest.raises(ClientError) as exc:+ cloudfront.create_distribution(DistributionConfig=_vo_distribution_config(vo_id))+ assert _vo_error(exc) == (404, "EntityNotFound", _VO_NOT_FOUND)+++def test_cloudfront_vpc_origin_update_check_order_round2(cloudfront, vpc_origin):+ """R2 V-order/update-bad-id-no-if-match, update-bad-id-bad-policy: the id format comes before the schema+ problems. update-not-xml-no-if-match: a body that isn't XML comes before them too (and R5+ V-edge/update-bad-id-not-xml: before the id format). update-stale-etag-port0, update-unknown-id-real-etag-port0:+ the range checks come before the origin lookup and the 412. update-stale-etag-name-of-A: the 412 comes+ before a reused name. R2 V-name/update-C-name-of-A, update-C-name-too-long: names are checked on Update."""+ vo_id = vpc_origin["VpcOrigin"]["Id"]+ cfg = vpc_origin["VpcOrigin"]["VpcOriginEndpointConfig"]+ stale = vpc_origin["ETag"]+ current = cloudfront.get_vpc_origin(Id=vo_id)["ETag"]+ other = cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg())+ other_name = other["VpcOrigin"]["VpcOriginEndpointConfig"]["Name"]+ try:+ bad_policy = f'<VpcOriginEndpointConfig xmlns="{_VO_NS}">{_vo_cfg_xml({**cfg, "OriginProtocolPolicy": "nope"})}</VpcOriginEndpointConfig>'+ assert _vo_raw_error("PUT", "/2020-05-31/vpc-origin/vo_doesnotexist", bad_policy) == (+ 400, "InvalidArgument", "Id format is invalid")+ assert _vo_raw_error("PUT", f"/2020-05-31/vpc-origin/{vo_id}", "this is not xml") == (+ 400, "MalformedInput", "Could not parse XML")+ assert _vo_raw_error("DELETE", "/2020-05-31/vpc-origin/vo_doesnotexist") == (+ 400, "InvalidArgument", "Id format is invalid")+ cases = [+ (vo_id, stale, {"HTTPPort": 0}, _VO_PORT_RANGE),+ ("vo_Y769dEbaneau0o63mXNjrY", current, {"HTTPPort": 0}, _VO_PORT_RANGE),+ (vo_id, stale, {"Name": other_name}, (412, "PreconditionFailed", _VO_STALE)),+ (vo_id, current, {"Name": other_name}, (409, "EntityAlreadyExists",+ "Another vpc origin with the same name already exists within the aws account.")),+ (vo_id, current, {"Name": "n" * 65}, (400, "InvalidArgument", "The parameter VPC Origin Name is too big.")),+ ]+ for target, if_match, overrides, expected in cases:+ with pytest.raises(ClientError) as exc:+ cloudfront.update_vpc_origin(Id=target, IfMatch=if_match, VpcOriginEndpointConfig={**cfg, **overrides})+ assert _vo_error(exc) == expected+ finally:+ _vo_delete(cloudfront, other["VpcOrigin"]["Id"])++[email protected]_contract[email protected]("permission", ["none", "allow", "explicit-deny", "other-resource"])+def test_cloudfront_vpc_origin_permission_contract(auth_enabled, iam_user, vpc_origin, permission):+ """R2 U17/p2-get-A-try2 and p2-get-B: GetVpcOrigin is authorized on arn:aws:cloudfront::<account>:vpcorigin/<Id>;+ p1-get-A: without a matching allow it answers 403 AccessDenied."""+ vo_arn = vpc_origin["VpcOrigin"]["Arn"]+ statements = []+ if permission != "none":+ resource = vo_arn.rsplit("/", 1)[0] + "/vo_other" if permission == "other-resource" else vo_arn+ statements.append({"Effect": "Allow", "Action": "cloudfront:GetVpcOrigin", "Resource": resource})+ if permission == "explicit-deny":+ statements.append({"Effect": "Deny", "Action": "cloudfront:GetVpcOrigin", "Resource": vo_arn})+ policy = {"Version": "2012-10-17", "Statement": statements} if statements else None+ client = iam_user(policy=policy).client("cloudfront", region="us-east-1")+ if auth_enabled and permission != "allow":+ with pytest.raises(ClientError) as exc:+ client.get_vpc_origin(Id=vpc_origin["VpcOrigin"]["Id"])+ assert exc.value.response["Error"]["Code"] == "AccessDenied"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403+ else:+ assert client.get_vpc_origin(Id=vpc_origin["VpcOrigin"]["Id"])["VpcOrigin"]["Arn"] == vo_arn+++def test_cloudfront_update_distribution_rejects_unknown_vpc_origin(cloudfront, vpc_origin):+ """R3b U15/update-distribution-unknown-vpc-origin-id: UpdateDistribution naming no origin answers 404+ EntityNotFound."""+ created = cloudfront.create_distribution(DistributionConfig=_vo_distribution_config(vpc_origin["VpcOrigin"]["Id"]))+ dist_id = created["Distribution"]["Id"]+ try:+ got = cloudfront.get_distribution_config(Id=dist_id)+ cfg = copy.deepcopy(got["DistributionConfig"])+ cfg["Origins"]["Items"][0]["VpcOriginConfig"]["VpcOriginId"] = "vo_Y769dEbaneau0o63mXNjrY"+ with pytest.raises(ClientError) as exc:+ cloudfront.update_distribution(Id=dist_id, IfMatch=got["ETag"], DistributionConfig=cfg)+ assert _vo_error(exc) == (404, "EntityNotFound", _VO_NOT_FOUND)+ finally:+ _vo_delete_distribution(cloudfront, dist_id)+++def test_cloudfront_vpc_origin_etags_follow_the_version(cloudfront, vpc_origin):+ """R1 U6, U4, U7, U10 (headers): every origin has the same ETag at the same version, and the version moves on at+ the create, the end of its deployment, an update and the end of that deployment. MiniStack's values are uuid5s+ (as for the managed policies). R1 U3/delete-unknown-real-etag, U10/delete-C-after-gone: an issued ETag on an+ unknown id answers 404; R1 U1/update-A-fake-etag: a well-formed ETag that was never issued answers 400."""+ vo_id = vpc_origin["VpcOrigin"]["Id"]+ other = cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg())+ try:+ assert other["ETag"] == vpc_origin["ETag"]+ assert re.fullmatch(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", vpc_origin["ETag"])+ got = cloudfront.get_vpc_origin(Id=vo_id)+ assert got["ETag"] == cloudfront.get_vpc_origin(Id=other["VpcOrigin"]["Id"])["ETag"] != vpc_origin["ETag"]+ updated = cloudfront.update_vpc_origin(Id=vo_id, IfMatch=got["ETag"], VpcOriginEndpointConfig={+ **got["VpcOrigin"]["VpcOriginEndpointConfig"], "HTTPSPort": 8443})+ after = cloudfront.get_vpc_origin(Id=vo_id)["ETag"]+ assert len({vpc_origin["ETag"], got["ETag"], updated["ETag"], after}) == 4+ with pytest.raises(ClientError) as exc:+ cloudfront.delete_vpc_origin(Id="vo_Y769dEbaneau0o63mXNjrY", IfMatch=got["ETag"])+ assert _vo_error(exc) == (404, "EntityNotFound", _VO_NOT_FOUND)+ never_issued = str(_uuid_mod.uuid4())+ for call in (lambda: cloudfront.delete_vpc_origin(Id=vo_id, IfMatch=never_issued),+ lambda: cloudfront.update_vpc_origin(Id=vo_id, IfMatch=never_issued,+ VpcOriginEndpointConfig=got["VpcOrigin"]["VpcOriginEndpointConfig"])):+ with pytest.raises(ClientError) as exc:+ call()+ assert _vo_error(exc) == (400, "InvalidIfMatchVersion", _VO_BAD_IF_MATCH)+ finally:+ _vo_delete(cloudfront, other["VpcOrigin"]["Id"])++[email protected]("inner_kw,expected", [+ ({"https": ""}, (400, "MalformedInput", "missing value for decimal type")), # R5 V-edge/https-empty+ ({"ssl": "<OriginSslProtocols><Quantity></Quantity><Items><SslProtocol>TLSv1.2</SslProtocol></Items></OriginSslProtocols>"},+ (400, "MalformedInput", "missing value for decimal type")), # R5 V-edge/quantity-empty+ ({"http": "99999999999"}, (400, "MalformedInput", None)), # R5 V-edge/http-huge+ ({"policy": ""}, (400, "MalformedXML", "1 validation error detected: Value '' at 'vpcOriginEndpointConfig.originProtocolPolicy' "+ "failed to satisfy constraint: " + _VO_POLICY_ENUM)), # R5 V-edge/policy-empty+ ({"ssl": "<OriginSslProtocols><Quantity>1</Quantity><Items><SslProtocol></SslProtocol></Items></OriginSslProtocols>"},+ (400, "MalformedXML", "1 validation error detected: Value '[]' at 'vpcOriginEndpointConfig.originSslProtocols.items' "+ "failed to satisfy constraint: " + _VO_SSL_ENUM)), # R5 V-edge/ssl-protocol-empty+], ids=["https-empty", "quantity-empty", "http-huge", "policy-empty", "ssl-protocol-empty"])+def test_cloudfront_vpc_origin_create_rejects_raw_edges(inner_kw, expected):+ """R5 V-edge: empty integers, an integer outside the 32-bit range, and empty enum values."""+ cfg = _vo_cfg()+ policy = inner_kw.pop("policy", None)+ inner = _vo_cfg_xml(cfg, **inner_kw)+ if policy is not None:+ inner = inner.replace(">https-only<", f">{policy}<")+ assert _vo_raw_error("POST", "/2020-05-31/vpc-origin", _vo_create_xml(inner)) == expected++[email protected]("overrides,expected", [+ ({"Name": "", "HTTPPort": 0}, _VO_PORT_RANGE), # R5 V-edge/name-empty+port0+ ({"Name": "a b", "HTTPPort": 0}, _VO_PORT_RANGE), # R5 V-edge/name-bad-char+port0+ ({"Name": "a b", "OriginSslProtocols": {"Quantity": 2, "Items": ["TLSv1.2"]}}, (+ 400, "InvalidArgument", "The parameter Name contains characters other than alphanumericals, dashes, and underscores.")), # R5 V-edge/name-bad-char+qty-mismatch+ ({"Name": "", "OriginSslProtocols": {"Quantity": 2, "Items": ["TLSv1.2"]}},+ (400, "InvalidArgument", "The parameter VPC Origin Name is too small or empty.")), # R5 V-edge/name-empty+qty-mismatch+ ({"Name": "a b" + "n" * 63}, (400, "InvalidArgument", "The parameter VPC Origin Name is too big.")), # R5 V-edge/name-65-bad-char+ ({"Arn": "arn:aws:elasticloadbalancing:us-east-1::loadbalancer/app/example/0123456789abcdef"}, _VO_BAD_ARN), # R5 V-edge/arn-empty-account+ ({"Arn": f"arn:aws:elasticloadbalancing:xx-fake-1:{_VO_ACCOUNT}:loadbalancer/app/example/0123456789abcdef"}, _VO_BAD_ARN), # R5 V-edge/arn-fake-region+], ids=["name-empty+port0", "name-bad-char+port0", "name-bad-char+qty", "name-empty+qty", "name-65-bad-char",+ "arn-empty-account", "arn-fake-region"])+def test_cloudfront_vpc_origin_create_rejects_edges(cloudfront, overrides, expected):+ """R5 V-edge: the order inside the name checks (empty, too big, characters) and against the port and+ quantity checks; an ARN with no account or a region AWS doesn't have is an invalid format."""+ with pytest.raises(ClientError) as exc:+ cloudfront.create_vpc_origin(VpcOriginEndpointConfig=_vo_cfg(**overrides))+ assert _vo_error(exc) == expected+++def test_cloudfront_vpc_origin_plus_sign_integers(cloudfront):+ """R5 V-edge/http-plus-80: HTTPPort +80 is accepted as 80. V-edge/max-items-plus-5: MaxItems +5 is 5;+ max-items-space-5: ' 5' is refused; max-items-abc-bad-marker: the MaxItems error comes first."""+ status, _, text = _vo_raw("POST", "/2020-05-31/vpc-origin", _vo_create_xml(_vo_cfg_xml(_vo_cfg(), http="+80")))+ assert status == 202 and "<HTTPPort>80</HTTPPort>" in text+ _vo_delete(cloudfront, re.search(r"<Id>([^<]+)</Id>", text).group(1))+ assert cloudfront.list_vpc_origins(MaxItems="+5")["VpcOriginList"]["MaxItems"] == 5+ for params in ({"MaxItems": " 5"}, {"MaxItems": "abc", "Marker": "vo_doesnotexist"}):+ with pytest.raises(ClientError) as exc:+ cloudfront.list_vpc_origins(**params)+ assert _vo_error(exc) == (400, "InvalidArgument", "MaxItems must be a non-zero positive integer.")+++def test_cloudfront_vpc_origin_update_edges(cloudfront, vpc_origin):+ """R5 V-edge/update-empty-if-match, delete-empty-if-match: an empty If-Match is InvalidIfMatchVersion.+ update-empty-body: an empty body is a null vpcOriginEndpointConfig. update-bad-id-not-xml: the XML comes+ before the id format. update-eighty-no-if-match: a non-integer comes before the ifMatch null.+ update-A-omit-ssl, get-A-after-omit-ssl: an Update without OriginSslProtocols stores the default."""+ vo_id = vpc_origin["VpcOrigin"]["Id"]+ cfg = vpc_origin["VpcOrigin"]["VpcOriginEndpointConfig"]+ etag = cloudfront.get_vpc_origin(Id=vo_id)["ETag"]+ path = f"/2020-05-31/vpc-origin/{vo_id}"+ body = f'<VpcOriginEndpointConfig xmlns="{_VO_NS}">{_vo_cfg_xml(cfg)}</VpcOriginEndpointConfig>'+ assert _vo_raw_error("PUT", path, body, {"If-Match": ""}) == (400, "InvalidIfMatchVersion", _VO_BAD_IF_MATCH)+ assert _vo_raw_error("DELETE", path, None, {"If-Match": ""}) == (400, "InvalidIfMatchVersion", _VO_BAD_IF_MATCH)+ assert _vo_raw_error("PUT", path, "", {"If-Match": etag}) == (+ 400, "MalformedXML", "1 validation error detected: Value null at 'vpcOriginEndpointConfig' failed to satisfy "+ "constraint: Member must not be null")+ assert _vo_raw_error("PUT", "/2020-05-31/vpc-origin/vo_doesnotexist", "this is not xml", {"If-Match": etag}) == (+ 400, "MalformedInput", "Could not parse XML")+ eighty = f'<VpcOriginEndpointConfig xmlns="{_VO_NS}">{_vo_cfg_xml(cfg, http="eighty")}</VpcOriginEndpointConfig>'+ assert _vo_raw_error("PUT", path, eighty) == (400, "MalformedInput", None)+ no_ssl = {k: v for k, v in cfg.items() if k != "OriginSslProtocols"}+ updated = cloudfront.update_vpc_origin(Id=vo_id, IfMatch=etag, VpcOriginEndpointConfig=no_ssl)+ assert updated["VpcOrigin"]["VpcOriginEndpointConfig"]["OriginSslProtocols"] == {+ "Quantity": 3, "Items": ["TLSv1", "TLSv1.1", "TLSv1.2"]}+++def test_cloudfront_vpc_origin_in_use_normalized_and_omitted_protocols(cloudfront, vpc_origin):+ """R5 V-edge/update-C-in-use-duplicate-protocols: while in use, duplicated protocols are the same config+ (202, no new version). update-C-in-use-omit-ssl: leaving OriginSslProtocols out is a change (409)."""+ vo_id = vpc_origin["VpcOrigin"]["Id"]+ created = cloudfront.create_distribution(DistributionConfig=_vo_distribution_config(vo_id))+ try:+ got = cloudfront.get_vpc_origin(Id=vo_id)+ cfg = got["VpcOrigin"]["VpcOriginEndpointConfig"]+ same = cloudfront.update_vpc_origin(Id=vo_id, IfMatch=got["ETag"], VpcOriginEndpointConfig={+ **cfg, "OriginSslProtocols": {"Quantity": 2, "Items": ["TLSv1.2", "TLSv1.2"]}})+ assert same["ResponseMetadata"]["HTTPStatusCode"] == 202 and same["ETag"] == got["ETag"]+ with pytest.raises(ClientError) as exc:+ cloudfront.update_vpc_origin(Id=vo_id, IfMatch=got["ETag"],+ VpcOriginEndpointConfig={k: v for k, v in cfg.items() if k != "OriginSslProtocols"})+ assert _vo_error(exc) == (409, "CannotUpdateEntityWhileInUse", _VO_IN_USE)+ finally:+ _vo_delete_distribution(cloudfront, created["Distribution"]["Id"])+++def test_cloudfront_distribution_vpc_origin_timeouts_and_empty_id(cloudfront, vpc_origin):+ """R5 V-edge/create-distribution-read-timeout-only: a sent OriginReadTimeout is kept and+ OriginKeepaliveTimeout defaults to 5. create-distribution-empty-vpc-origin-id: an empty VpcOriginId answers+ 400 InvalidArgument."""+ cfg = _vo_distribution_config(vpc_origin["VpcOrigin"]["Id"])+ cfg["Origins"]["Items"][0]["VpcOriginConfig"]["OriginReadTimeout"] = 60+ created = cloudfront.create_distribution(DistributionConfig=cfg)+ try:+ origin = created["Distribution"]["DistributionConfig"]["Origins"]["Items"][0]+ assert origin["VpcOriginConfig"] == {"VpcOriginId": vpc_origin["VpcOrigin"]["Id"], "OriginReadTimeout": 60,+ "OriginKeepaliveTimeout": 5}+ finally:+ _vo_delete_distribution(cloudfront, created["Distribution"]["Id"])+ with pytest.raises(ClientError) as exc:+ cloudfront.create_distribution(DistributionConfig=_vo_distribution_config(""))+ assert _vo_error(exc) == (400, "InvalidArgument", "The parameter vpcOriginId must not be empty for VPC Origin.")+++def test_cloudfront_vpc_origin_update_deserialization_before_id(cloudfront, vpc_origin):+ """R6 V-edge2/bad-id-wrong-root, bad-id-eighty: a body that can't be read answers MalformedInput even for a+ malformed id. unknown-id-int-2147483647 / 2147483648 (and the negative pair): the integer range is 32-bit.+ unknown-id-mixed-empty-protocol: every item shows in the enum message, empty ones too."""+ cfg = vpc_origin["VpcOrigin"]["VpcOriginEndpointConfig"]+ etag = cloudfront.get_vpc_origin(Id=vpc_origin["VpcOrigin"]["Id"])["ETag"]++ def put(vid, inner, root="VpcOriginEndpointConfig"):+ return _vo_raw_error("PUT", f"/2020-05-31/vpc-origin/{vid}", f'<{root} xmlns="{_VO_NS}">{inner}</{root}>',+ {"If-Match": etag})++ assert put("vo_doesnotexist", _vo_cfg_xml(cfg), root="SomethingElse") == (+ 400, "MalformedInput", "SomethingElse is not valid, expected VpcOriginEndpointConfig")+ assert put("vo_doesnotexist", _vo_cfg_xml(cfg, http="eighty")) == (400, "MalformedInput", None)+ unknown = "vo_Y769dEbaneau0o63mXNjrY"+ for value, expected in (("2147483647", _VO_PORT_RANGE), ("2147483648", (400, "MalformedInput", None)),+ ("-2147483648", _VO_PORT_RANGE), ("-2147483649", (400, "MalformedInput", None))):+ assert put(unknown, _vo_cfg_xml(cfg, http=value)) == expected+ mixed = ("<OriginSslProtocols><Quantity>2</Quantity><Items><SslProtocol></SslProtocol><SslProtocol>TLSv1.2"+ "</SslProtocol></Items></OriginSslProtocols>")+ assert put(unknown, _vo_cfg_xml(cfg, ssl=mixed)) == (+ 400, "MalformedXML", "1 validation error detected: Value '[, TLSv1.2]' at "+ "'vpcOriginEndpointConfig.originSslProtocols.items' failed to satisfy constraint: " + _VO_SSL_ENUM)++[email protected]("max_items,expected", [+ ("99999999999", None), ("2147483648", None), ("-0", 0),+], ids=["huge", "2147483648", "minus-0"])+def test_cloudfront_vpc_origin_list_max_items_bounds(cloudfront, max_items, expected):+ """R6 V-edge2/list-max-items-huge, list-max-items-2147483648: past the 32-bit range MaxItems is refused;+ list-max-items-minus-0: -0 is 0."""+ if expected is None:+ with pytest.raises(ClientError) as exc:+ cloudfront.list_vpc_origins(MaxItems=max_items)+ assert _vo_error(exc) == (400, "InvalidArgument", "MaxItems must be a non-zero positive integer.")+ else:+ assert cloudfront.list_vpc_origins(MaxItems=max_items)["VpcOriginList"]["MaxItems"] == expecteddiff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex 2550c438..7a23a399 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -2269,6 +2269,17 @@ class TestResourceArn:from ministack.core.iam_actions import extract_resource_arnassert extract_resource_arn("cloudfront", "GET", "/2020-05-31/distribution/E123ABC", {}, b"", {}, "us-east-1", "123") == "arn:aws:cloudfront::123:distribution/E123ABC"+ def test_cloudfront_vpc_origin(self):+ from ministack.core.iam_actions import extract_iam_action, extract_resource_arn+ for method, action in (("GET", "GetVpcOrigin"), ("PUT", "UpdateVpcOrigin"), ("DELETE", "DeleteVpcOrigin")):+ assert extract_resource_arn("cloudfront", method, "/2020-05-31/vpc-origin/vo_abc", {}, b"", {},+ "us-east-1", "123") == "arn:aws:cloudfront::123:vpcorigin/vo_abc"+ assert extract_iam_action("cloudfront", method, "/2020-05-31/vpc-origin/vo_abc", {}, b"", {}) == f"cloudfront:{action}"+ # R2 U17/p1-create-on-A: CreateVpcOrigin authorizes on vpcorigin/*.+ assert extract_resource_arn("cloudfront", "POST", "/2020-05-31/vpc-origin", {}, b"", {},+ "us-east-1", "123") == "arn:aws:cloudfront::123:vpcorigin/*"+ assert extract_resource_arn("cloudfront", "GET", "/2020-05-31/vpc-origin", {}, b"", {}, "us-east-1", "123") == "*"+def test_route53_hostedzone(self):from ministack.core.iam_actions import extract_resource_arnassert extract_resource_arn("route53", "GET", "/2013-04-01/hostedzone/Z123", {}, b"", {}, "us-east-1", "123") == "arn:aws:route53:::hostedzone/Z123"diff --git a/tests/test_persistence.py b/tests/test_persistence.pyindex 053405fb..57bff697 100644--- a/tests/test_persistence.py+++ b/tests/test_persistence.py@@ -721,6 +721,29 @@ def test_s3_object_lambda_access_points_round_trip_without_pending_requests():_round_trip("s3", "s3", populate, observe)+def test_cloudfront_vpc_origins_round_trip_every_account():+ """CloudFront VPC origins are account-scoped; a restart keeps every account's."""+ def record(account, vo_id, version):+ return {"Id": vo_id, "Arn": f"arn:aws:cloudfront::{account}:vpcorigin/{vo_id}", "AccountId": account,+ "Status": "Deployed", "Version": version, "VpcOriginEndpointConfig": {"Name": "api"}}++ def populate(mod):+ mod._vpc_origins.set_scoped("111111111111", "us-east-1", "vo_a", record("111111111111", "vo_a", 4))+ mod._vpc_origins.set_scoped("222222222222", "us-east-1", "vo_b", record("222222222222", "vo_b", 6))+ # A deleted origin had reached version 8: its ETags must stay valid too (R1 U10/delete-C-after-gone).+ for version in range(1, 9):+ mod._vpc_origin_etag(version)++ def observe(mod):+ assert mod._vpc_origins.get_scoped("111111111111", "us-east-1", "vo_a")["AccountId"] == "111111111111"+ assert mod._vpc_origins.get_scoped("222222222222", "us-east-1", "vo_b")["Version"] == 6+ assert not mod._vpc_origins.contains_scoped("111111111111", "us-east-1", "vo_b")+ # Every version's ETag issued before the restart is valid again for If-Match.+ assert sorted(set(mod._vpc_origin_etags_issued.values())) == list(range(1, 9))++ _round_trip("cloudfront", "cloudfront", populate, observe)++def test_transcribe_round_trip():import time as _time