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): public keys and key groups (#1815)
Fábio André Ramos Rodrigues1d02f5c067fe
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bdc206aa..af246efe 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **Lambda — `ReservedConcurrentExecutions=0` disables the function** — a zero reservation was treated as unset, so the function ran unbounded instead of throttling every invoke with `TooManyRequestsException`. Zero now throttles across all executors, the Docker pool, and SQS event source mappings.### Added+- **CloudFront — public keys and key groups** — `CreatePublicKey`, `GetPublicKey`, `GetPublicKeyConfig`, `UpdatePublicKey`, `DeletePublicKey`, `ListPublicKeys`, `CreateKeyGroup`, `GetKeyGroup`, `GetKeyGroupConfig`, `UpdateKeyGroup`, `DeleteKeyGroup`, `ListKeyGroups`, so `aws_cloudfront_public_key` / `aws_cloudfront_key_group` (and Upbound's Terraform-based `provider-aws-cloudfront`) apply instead of hitting `NoSuchResource` on every create. Key groups validate their `Items` against real public keys, `DeletePublicKey` refuses a key still referenced by a key group, and `DeleteKeyGroup` refuses a group still referenced by a distribution's trusted key groups — both ETag/`If-Match` optimistic concurrency like the other CloudFront policy families.- **CloudFormation — AppConfig applications, environments, configuration profiles and deployment strategies update in place** — none of the four had an update handler, so any property change re-ran the create and the resource came back under a new id. The environments, configuration profiles and hosted configuration versions keyed by the old id were orphaned. Each type now updates in place what its resource reference lists as No interruption and replaces on the rest. Contributed by @iot-rocket.- **CloudFormation — AppSync GraphQL APIs and API keys update in place** — every property of `AWS::AppSync::GraphQLApi` is No interruption, but a change re-ran the create, which minted a new api id with empty key, data source, resolver and type stores, so a renamed API came back empty. The API now keeps its id and applies the change in place. It stores `AdditionalAuthenticationProviders`, `XrayEnabled`, `QueryDepthLimit`, `ResolverCountLimit`, `IntrospectionConfig`, `EnvironmentVariables`, `OwnerContact`, `LogConfig`, `UserPoolConfig`, `OpenIDConnectConfig`, `LambdaAuthorizerConfig`, `EnhancedMetricsConfig` and `MergedApiExecutionRoleArn` in AppSync's camelCase, and a removed member goes back to AppSync's default. A `Visibility` change fails with AWS's message. The API carries the stack-level tags, its id has `CreateGraphqlApi`'s 26 characters (eight made an ARN botocore refuses) and it answers the `REALTIME` endpoint. `AWS::AppSync::ApiKey` keeps its key on a `Description` or `Expires` change, and its record carries `description` and `createdAt`, as `CreateApiKey` writes them. Contributed by @iot-rocket.- **CloudFormation — Auto Scaling groups, scaling policies and scheduled actions update in place** — a change re-ran the create, which mints a new ARN from a uuid, and the group also lost its instances and its creation time. The three types now update in place. An `AutoScalingGroupName` or `InstanceId` change replaces the group, and a group tag change keeps tags added through `CreateOrUpdateTags`. As on AWS, `PolicyName` names a scaling policy at create and is ignored after that, and CloudFormation names a scheduled action itself, ignores `ScheduledActionName` and answers the generated name through `Ref` (it answered the ARN). `DescribeAutoScalingGroups` answers the launch template's name beside its id. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex fe813665..fd753eb9 100644--- a/README.md+++ b/README.md@@ -442,7 +442,7 @@ subnet = ec2.create_subnet(| **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateDocumentationPart, GetDocumentationPart, GetDocumentationParts, UpdateDocumentationPart, DeleteDocumentationPart, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags, CreateRequestValidator, GetRequestValidators, GetRequestValidator, UpdateRequestValidator, DeleteRequestValidator | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), non-proxy Lambda (AWS — the handler's output is the response body, mapping templates not modeled), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost` Host header, path-based `/_aws/execute-api/{apiId}/{stage}/{path}`, or legacy `/restapis/{apiId}/{stage}/_user_request_/{path}`; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; resource tree with `{param}` and `{proxy+}` path matching; routing is on the resource+method pair, so a request the matched resource does not serve falls through to a `{proxy+}` elsewhere in the tree (a methodless intermediate, a CORS-preflight-only node, or any undeclared verb), as it does on AWS; TOKEN and REQUEST Lambda authorizers on the data plane, with the returned IAM policy evaluated against each request's own method ARN and `authorizerResultTtlInSeconds` caching the policy per stage and identity source; JSON Patch for all PATCH operations; state persistence; pin `id` across runs with the `ms-custom-id` tag || **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, SetSubnets, SetIpAddressType, SetSecurityGroups, RegisterTargets, DeregisterTargets, DescribeTargetHealth, AddTags, RemoveTags, DescribeTags | Control plane + data plane; ALB→Lambda live traffic routing; `path-pattern`, `host-header`, `http-method`, `query-string`, `http-header` rule conditions; `forward`, `redirect`, `fixed-response`, `authenticate-oidc` actions; data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix || **KMS** | CreateKey, ReplicateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateMac, VerifyMac, GenerateDataKey, GenerateDataKeyWithoutPlaintext, GenerateDataKeyPair, GenerateDataKeyPairWithoutPlaintext, GenerateRandom, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, UpdateKeyDescription, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags, GetParametersForImport, ImportKeyMaterial, DeleteImportedKeyMaterial | 34 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; full Terraform `aws_kms_key` compatible; `cryptography` package included in Docker image |-| **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, CreateFunction, DeleteFunction, DescribeFunction, GetFunction, ListFunctions, PublishFunction, UpdateFunction, **KeyValueStore (mgmt)**: CreateKeyValueStore, DescribeKeyValueStore, ListKeyValueStores, UpdateKeyValueStore, DeleteKeyValueStore, **Policies**: CreateCachePolicy, GetCachePolicy, GetCachePolicyConfig, UpdateCachePolicy, DeleteCachePolicy, ListDistributionsByCachePolicyId, CreateOriginRequestPolicy, GetOriginRequestPolicy, GetOriginRequestPolicyConfig, UpdateOriginRequestPolicy, DeleteOriginRequestPolicy, ListDistributionsByOriginRequestPolicyId, CreateResponseHeadersPolicy, GetResponseHeadersPolicy, GetResponseHeadersPolicyConfig, UpdateResponseHeadersPolicy, DeleteResponseHeadersPolicy, ListDistributionsByResponseHeadersPolicyId, **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; **CloudFront Functions** are API stubs (in-memory code + DEVELOPMENT/LIVE ETags for Terraform `aws_cloudfront_function`) with `KeyValueStoreAssociations` round-tripped — no `TestFunction`, no viewer-request JS execution at the edge; `UpdateFunction` clears the emulated LIVE stage until `PublishFunction` runs again; **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) |+| **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, CreateFunction, DeleteFunction, DescribeFunction, GetFunction, ListFunctions, PublishFunction, UpdateFunction, **KeyValueStore (mgmt)**: CreateKeyValueStore, DescribeKeyValueStore, ListKeyValueStores, UpdateKeyValueStore, DeleteKeyValueStore, **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; **CloudFront Functions** are API stubs (in-memory code + DEVELOPMENT/LIVE ETags for Terraform `aws_cloudfront_function`) with `KeyValueStoreAssociations` round-tripped — no `TestFunction`, no viewer-request JS execution at the edge; `UpdateFunction` clears the emulated LIVE stage until `PublishFunction` runs again; **SaaS Manager** multi-tenant distributions: `DistributionConfig` round-trips `ConnectionMode` / `TenantConfig`, tenants require a `tenant-only` distribution, CNAMEs are unique across tenants and distribution aliases, a tenant without an explicit connection group lazily gets the account default group, and MiniStack collapses async workflows (tenants deploy, domains activate, DNS verifies, managed certificates issue immediately); key groups validate `Items` against real public keys, and deleting either while still referenced (`PublicKeyInUse` / `ResourceInUse`) is rejected || **CloudFront KeyValueStore (data plane)** | DescribeKeyValueStore, ListKeys, GetKey, PutKey, DeleteKey, UpdateKeys | Separate `cloudfront-keyvaluestore` SDK service (REST/JSON, signing name `cloudfront-keyvaluestore`); ETag-based optimistic concurrency on every mutating op; `UpdateKeys` is atomic (validates whole batch, rejects on first invalid entry); `ListKeys` paginates with opaque `NextToken` capped at 50 results per AWS spec; bridges to the management plane via the shared KVS ARN || **CloudTrail** | LookupEvents, CreateTrail, DeleteTrail, GetTrail, DescribeTrails, ListTrails, UpdateTrail, GetTrailStatus, StartLogging, StopLogging, PutEventSelectors, GetEventSelectors, AddTags, ListTags, RemoveTags | In-memory audit log; recording opt-in via `CLOUDTRAIL_RECORDING=1` (or runtime config endpoint); per-account ring buffer (`CLOUDTRAIL_MAX_EVENTS=10000`); `LookupEvents` supports all 8 AWS `LookupAttributes`; `IsLogging` flips on Start/StopLogging; `CreateTrail`/`UpdateTrail` persist `KmsKeyId` (normalized to a key ARN; omitted when unset) so `aws_cloudtrail` converges without drift || **Resource Groups** | CreateGroup, GetGroup, DeleteGroup, UpdateGroup, ListGroups, GetGroupQuery, UpdateGroupQuery, GetGroupConfiguration, PutGroupConfiguration, GroupResources, UngroupResources, ListGroupResources, ListGroupingStatuses, SearchResources, Tag, Untag, GetTags, GetAccountSettings, UpdateAccountSettings | 19 of 23 spec ops; tag-sync ops omitted (not exposed by AWS CLI / Terraform); `Group` accepts bare name or full ARN |diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.pyindex 575e96e8..80fd0fa6 100644--- a/ministack/services/cloudfront.py+++ b/ministack/services/cloudfront.py@@ -25,6 +25,10 @@ Supports:Response headers policies: CreateResponseHeadersPolicy, GetResponseHeadersPolicy,GetResponseHeadersPolicyConfig, UpdateResponseHeadersPolicy,DeleteResponseHeadersPolicy, ListDistributionsByResponseHeadersPolicyId+ Public keys: CreatePublicKey, GetPublicKey, GetPublicKeyConfig,+ UpdatePublicKey, DeletePublicKey, ListPublicKeys+ Key groups: CreateKeyGroup, GetKeyGroup, GetKeyGroupConfig,+ UpdateKeyGroup, DeleteKeyGroup, ListKeyGroupsTags: TagResource, UntagResource, ListTagsForResourceSaaS Manager (multi-tenant distributions):CreateConnectionGroup, GetConnectionGroup,@@ -99,6 +103,14 @@ _RHP_CFG_RE = re.compile(r"^/2020-05-31/response-headers-policy/([^/]+)/config$"_RHP_ID_RE = re.compile(r"^/2020-05-31/response-headers-policy/([^/]+)/?$")_DIST_BY_RHP_RE = re.compile(r"^/2020-05-31/distributionsByResponseHeadersPolicyId/([^/]+)/?$")+_PUBLIC_KEY_RE = re.compile(r"^/2020-05-31/public-key/?$")+_PUBLIC_KEY_CFG_RE = re.compile(r"^/2020-05-31/public-key/([^/]+)/config$")+_PUBLIC_KEY_ID_RE = re.compile(r"^/2020-05-31/public-key/([^/]+)/?$")++_KEY_GROUP_RE = re.compile(r"^/2020-05-31/key-group/?$")+_KEY_GROUP_CFG_RE = re.compile(r"^/2020-05-31/key-group/([^/]+)/config$")+_KEY_GROUP_ID_RE = re.compile(r"^/2020-05-31/key-group/([^/]+)/?$")+# SaaS Manager path regexes. Get* identifiers may be an ARN — the ASGI layer# hands us the percent-decoded path, so an ARN's embedded "/" lands in the# identifier segment. The identifier regexes are greedy and MUST be matched@@ -128,8 +140,6 @@ _DIST_BY_CONN_MODE_RE = re.compile(r"^/2020-05-31/distributionsByConnectionMode/# the payload member's locationName, MaxItems defaults to 100, an empty list# omits Items, and NextMarker is omitted when there is no next page.# ----------------------------------------------------------------------------_KEY_GROUP_LIST_RE = re.compile(r"^/2020-05-31/key-group/?$")-_PUBLIC_KEY_LIST_RE = re.compile(r"^/2020-05-31/public-key/?$")_FLE_LIST_RE = re.compile(r"^/2020-05-31/field-level-encryption/?$")_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/?$")@@ -152,6 +162,8 @@ _kvstores = AccountScopedDict() # Name -> KVS record_cache_policies = AccountScopedDict() # Id -> cache policy record_origin_request_policies = AccountScopedDict() # Id -> origin request policy record_response_headers_policies = AccountScopedDict() # Id -> response headers policy record+_public_keys = AccountScopedDict() # Id -> public key record+_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, ...]@@ -167,6 +179,8 @@ def reset():_cache_policies.clear()_origin_request_policies.clear()_response_headers_policies.clear()+ _public_keys.clear()+ _key_groups.clear()_connection_groups.clear()_distribution_tenants.clear()_tenant_invalidations.clear()@@ -184,6 +198,8 @@ def get_state():"cache_policies": _cache_policies,"origin_request_policies": _origin_request_policies,"response_headers_policies": _response_headers_policies,+ "public_keys": _public_keys,+ "key_groups": _key_groups,"connection_groups": _connection_groups,"distribution_tenants": _distribution_tenants,"tenant_invalidations": _tenant_invalidations,@@ -205,6 +221,8 @@ def _restore_state(data):_cache_policies.update(data.get("cache_policies", {}))_origin_request_policies.update(data.get("origin_request_policies", {}))_response_headers_policies.update(data.get("response_headers_policies", {}))+ _public_keys.update(data.get("public_keys", {}))+ _key_groups.update(data.get("key_groups", {}))_connection_groups.update(data.get("connection_groups", {}))_distribution_tenants.update(data.get("distribution_tenants", {}))_tenant_invalidations.update(data.get("tenant_invalidations", {}))@@ -226,6 +244,14 @@ def _inv_id() -> str:return "I" + "".join(random.choices(_ID_CHARS, k=13))+def _pk_id() -> str:+ return "K" + "".join(random.choices(_ID_CHARS, k=13))+++def _kg_id() -> str:+ return "K" + "".join(random.choices(_ID_CHARS, k=13))++# Real SaaS Manager resource IDs are dt_/cg_-prefixed KSUIDs (27 base62 chars)._KSUID_CHARS = string.ascii_letters + string.digits@@ -1613,6 +1639,307 @@ _RHP_SPEC = {}+# ---------------------------------------------------------------------------+# PublicKey — used by signed URLs/cookies and as KeyGroup members. Not built+# on the generic policy CRUD helpers above: PublicKey has no Name-uniqueness+# constraint worth enforcing (real AWS dedupes by CallerReference, which+# nothing here reads back), tracks CreatedTime rather than LastModifiedTime,+# and its "in use" check is against KeyGroups, not distributions.+# ---------------------------------------------------------------------------+++def _parse_public_key_config(el):+ caller_reference = _text(el, "CallerReference")+ name = _text(el, "Name")+ encoded_key = _text(el, "EncodedKey")+ if not caller_reference or not name or not encoded_key:+ return None, _error(+ "InvalidArgument", "CallerReference, Name, and EncodedKey are required.", 400+ )+ return {+ "CallerReference": caller_reference, "Name": name,+ "EncodedKey": encoded_key, "Comment": _text(el, "Comment"),+ }, None+++def _build_public_key_config_xml(parent, cfg):+ SubElement(parent, "CallerReference").text = cfg["CallerReference"]+ SubElement(parent, "Name").text = cfg["Name"]+ SubElement(parent, "EncodedKey").text = cfg["EncodedKey"]+ if cfg.get("Comment"):+ SubElement(parent, "Comment").text = cfg["Comment"]+++def _build_public_key_xml(parent, pk):+ SubElement(parent, "Id").text = pk["Id"]+ SubElement(parent, "CreatedTime").text = pk["CreatedTime"]+ cfg_el = SubElement(parent, "PublicKeyConfig")+ _build_public_key_config_xml(cfg_el, pk["Config"])+++def _public_keys_using(pk_id):+ return [kg.get("Id", "") for kg in _key_groups.values() if pk_id in kg["Config"].get("Items", [])]+++def _create_public_key(body):+ el = _parse_body(body)+ if el is None:+ return _error("MalformedXML", "The XML document is malformed.", 400)+ cfg, err = _parse_public_key_config(el)+ if err is not None:+ return err+ pk_id = _pk_id()+ etag = new_uuid()+ pk = {"Id": pk_id, "ETag": etag, "CreatedTime": _now_iso(), "Config": cfg}+ _public_keys[pk_id] = pk+ logger.info("CreatePublicKey id=%s name=%s", pk_id, cfg["Name"])+ return _xml_response(+ "PublicKey", lambda r: _build_public_key_xml(r, pk), status=201,+ extra_headers={"ETag": etag, "Location": f"/2020-05-31/public-key/{pk_id}"},+ )+++def _get_public_key(pk_id):+ pk = _public_keys.get(pk_id)+ if not pk:+ return _error("NoSuchPublicKey", "The public key does not exist.", 404)+ return _xml_response("PublicKey", lambda r: _build_public_key_xml(r, pk), extra_headers={"ETag": pk["ETag"]})+++def _get_public_key_config(pk_id):+ pk = _public_keys.get(pk_id)+ if not pk:+ return _error("NoSuchPublicKey", "The public key does not exist.", 404)+ return _xml_response(+ "PublicKeyConfig", lambda r: _build_public_key_config_xml(r, pk["Config"]),+ extra_headers={"ETag": pk["ETag"]},+ )+++def _update_public_key(pk_id, headers, body):+ pk = _public_keys.get(pk_id)+ if not pk:+ return _error("NoSuchPublicKey", "The public key does not exist.", 404)+ if_match = headers.get("if-match")+ if not if_match:+ return _error("InvalidIfMatchVersion", "The If-Match version is missing or not valid for the resource.", 400)+ if if_match != pk["ETag"]:+ return _error(+ "PreconditionFailed",+ "The precondition given in one or more of the request-header fields evaluated to false.",+ 412,+ )+ el = _parse_body(body)+ if el is None:+ return _error("MalformedXML", "The XML document is malformed.", 400)+ cfg, err = _parse_public_key_config(el)+ if err is not None:+ return err+ if cfg["EncodedKey"] != pk["Config"]["EncodedKey"]:+ return _error("CannotChangeImmutablePublicKeyFields", "The encoded key cannot be changed.", 400)+ new_etag = new_uuid()+ pk["Config"] = cfg+ pk["ETag"] = new_etag+ _public_keys[pk_id] = pk+ logger.info("UpdatePublicKey id=%s", pk_id)+ return _xml_response("PublicKey", lambda r: _build_public_key_xml(r, pk), extra_headers={"ETag": new_etag})+++def _delete_public_key(pk_id, headers):+ pk = _public_keys.get(pk_id)+ if not pk:+ return _error("NoSuchPublicKey", "The public key does not exist.", 404)+ if_match = headers.get("if-match")+ if not if_match:+ return _error("InvalidIfMatchVersion", "The If-Match version is missing or not valid for the resource.", 400)+ if if_match != pk["ETag"]:+ return _error(+ "PreconditionFailed",+ "The precondition given in one or more of the request-header fields evaluated to false.",+ 412,+ )+ if _public_keys_using(pk_id):+ return _error("PublicKeyInUse", "The public key is attached to one or more key groups.", 409)+ del _public_keys[pk_id]+ logger.info("DeletePublicKey id=%s", pk_id)+ return 204, {}, b""+++def _list_public_keys(query_params):+ max_items = _qval(query_params, "MaxItems", _DEFAULT_MAX_ITEMS) or _DEFAULT_MAX_ITEMS+ keys = list(_public_keys.values())++ def build(root):+ SubElement(root, "MaxItems").text = max_items+ SubElement(root, "Quantity").text = str(len(keys))+ if keys:+ items_el = SubElement(root, "Items")+ for pk in keys:+ summary = SubElement(items_el, "PublicKeySummary")+ SubElement(summary, "Id").text = pk["Id"]+ SubElement(summary, "Name").text = pk["Config"]["Name"]+ SubElement(summary, "CreatedTime").text = pk["CreatedTime"]+ SubElement(summary, "EncodedKey").text = pk["Config"]["EncodedKey"]+ if pk["Config"].get("Comment"):+ SubElement(summary, "Comment").text = pk["Config"]["Comment"]++ return _xml_response("PublicKeyList", build)+++# ---------------------------------------------------------------------------+# KeyGroup — a named list of PublicKey ids, referenced by a distribution's+# trusted key groups (signed URLs/cookies) and by cache behaviors' OAC-signed+# origin access. Bespoke rather than the generic policy CRUD helpers above:+# KeyGroupConfig's own Items list has no analogue there, and AWS's error+# codes for this family (NoSuchResource / ResourceInUse) differ from the+# Cache/OriginRequest/ResponseHeaders policy families' Name-specific ones.+# ---------------------------------------------------------------------------+++def _parse_key_group_config(el):+ name = _text(el, "Name")+ if not name:+ return None, _error("InvalidArgument", "The key group name is required.", 400)+ items_el = _find(el, "Items")+ items = []+ if items_el is not None:+ for child in items_el:+ local = child.tag.split("}")[-1] if "}" in child.tag else child.tag+ if local == "PublicKey":+ items.append(child.text or "")+ if not items:+ return None, _error("InvalidArgument", "A key group must contain at least one public key.", 400)+ for pk_id in items:+ if pk_id not in _public_keys:+ return None, _error("InvalidArgument", f"Public key {pk_id} does not exist.", 400)+ return {"Name": name, "Items": items, "Comment": _text(el, "Comment")}, None+++def _build_key_group_config_xml(parent, cfg):+ SubElement(parent, "Name").text = cfg["Name"]+ items_el = SubElement(parent, "Items")+ for pk_id in cfg["Items"]:+ SubElement(items_el, "PublicKey").text = pk_id+ if cfg.get("Comment"):+ SubElement(parent, "Comment").text = cfg["Comment"]+++def _build_key_group_xml(parent, kg):+ SubElement(parent, "Id").text = kg["Id"]+ SubElement(parent, "LastModifiedTime").text = kg["LastModifiedTime"]+ cfg_el = SubElement(parent, "KeyGroupConfig")+ _build_key_group_config_xml(cfg_el, kg["Config"])+++def _key_groups_using(kg_id):+ return [d.get("Id", "") for d in _distributions.values() if _value_contains(d, kg_id)]+++def _create_key_group(body):+ el = _parse_body(body)+ if el is None:+ return _error("MalformedXML", "The XML document is malformed.", 400)+ cfg, err = _parse_key_group_config(el)+ if err is not None:+ return err+ for existing in _key_groups.values():+ if existing["Config"]["Name"] == cfg["Name"]:+ return _error("KeyGroupAlreadyExists", "A key group with the same name already exists.", 409)+ kg_id = _kg_id()+ etag = new_uuid()+ kg = {"Id": kg_id, "ETag": etag, "LastModifiedTime": _now_iso(), "Config": cfg}+ _key_groups[kg_id] = kg+ logger.info("CreateKeyGroup id=%s name=%s", kg_id, cfg["Name"])+ return _xml_response(+ "KeyGroup", lambda r: _build_key_group_xml(r, kg), status=201,+ extra_headers={"ETag": etag, "Location": f"/2020-05-31/key-group/{kg_id}"},+ )+++def _get_key_group(kg_id):+ kg = _key_groups.get(kg_id)+ if not kg:+ return _error("NoSuchResource", "The key group does not exist.", 404)+ return _xml_response("KeyGroup", lambda r: _build_key_group_xml(r, kg), extra_headers={"ETag": kg["ETag"]})+++def _get_key_group_config(kg_id):+ kg = _key_groups.get(kg_id)+ if not kg:+ return _error("NoSuchResource", "The key group does not exist.", 404)+ return _xml_response(+ "KeyGroupConfig", lambda r: _build_key_group_config_xml(r, kg["Config"]),+ extra_headers={"ETag": kg["ETag"]},+ )+++def _update_key_group(kg_id, headers, body):+ kg = _key_groups.get(kg_id)+ if not kg:+ return _error("NoSuchResource", "The key group does not exist.", 404)+ if_match = headers.get("if-match")+ if not if_match:+ return _error("InvalidIfMatchVersion", "The If-Match version is missing or not valid for the resource.", 400)+ if if_match != kg["ETag"]:+ return _error(+ "PreconditionFailed",+ "The precondition given in one or more of the request-header fields evaluated to false.",+ 412,+ )+ el = _parse_body(body)+ if el is None:+ return _error("MalformedXML", "The XML document is malformed.", 400)+ cfg, err = _parse_key_group_config(el)+ if err is not None:+ return err+ for existing in _key_groups.values():+ if existing["Id"] != kg_id and existing["Config"]["Name"] == cfg["Name"]:+ return _error("KeyGroupAlreadyExists", "A key group with the same name already exists.", 409)+ new_etag = new_uuid()+ kg["Config"] = cfg+ kg["ETag"] = new_etag+ kg["LastModifiedTime"] = _now_iso()+ logger.info("UpdateKeyGroup id=%s", kg_id)+ return _xml_response("KeyGroup", lambda r: _build_key_group_xml(r, kg), extra_headers={"ETag": new_etag})+++def _delete_key_group(kg_id, headers):+ kg = _key_groups.get(kg_id)+ if not kg:+ return _error("NoSuchResource", "The key group does not exist.", 404)+ if_match = headers.get("if-match")+ if not if_match:+ return _error("InvalidIfMatchVersion", "The If-Match version is missing or not valid for the resource.", 400)+ if if_match != kg["ETag"]:+ return _error(+ "PreconditionFailed",+ "The precondition given in one or more of the request-header fields evaluated to false.",+ 412,+ )+ if _key_groups_using(kg_id):+ return _error("ResourceInUse", "The key group is attached to one or more distributions.", 409)+ del _key_groups[kg_id]+ logger.info("DeleteKeyGroup id=%s", kg_id)+ return 204, {}, b""+++def _list_key_groups(query_params):+ max_items = _qval(query_params, "MaxItems", _DEFAULT_MAX_ITEMS) or _DEFAULT_MAX_ITEMS+ groups = list(_key_groups.values())++ def build(root):+ SubElement(root, "MaxItems").text = max_items+ SubElement(root, "Quantity").text = str(len(groups))+ if groups:+ items_el = SubElement(root, "Items")+ for kg in groups:+ summary = SubElement(items_el, "KeyGroupSummary")+ kg_el = SubElement(summary, "KeyGroup")+ _build_key_group_xml(kg_el, kg)++ return _xml_response("KeyGroupList", build)++# ---------------------------------------------------------------------------# Read-only list handlers for resource families with no backing store.# Shapes verified against botocore cloudfront service-2.json (2020-05-31).@@ -1900,6 +2227,55 @@ async def handle_request(method, path, headers, body, query_params):if method == "GET":return _policy_list_distributions(_response_headers_policies, _RHP_SPEC, m.group(1))+ # Public key routes. Unlike every other CloudFront policy family, real+ # AWS puts UpdatePublicKey on the .../config path (PUT), not the bare+ # .../{Id} path -- verified against botocore's service-2.json.+ m = _PUBLIC_KEY_CFG_RE.match(path)+ if m:+ pk_id = m.group(1)+ if method == "GET":+ return _get_public_key_config(pk_id)+ if method == "PUT":+ return _update_public_key(pk_id, headers, body)++ m = _PUBLIC_KEY_RE.match(path)+ if m:+ if method == "POST":+ return _create_public_key(body)+ if method == "GET":+ return _list_public_keys(query_params)++ m = _PUBLIC_KEY_ID_RE.match(path)+ if m:+ pk_id = m.group(1)+ if method == "GET":+ return _get_public_key(pk_id)+ if method == "DELETE":+ return _delete_public_key(pk_id, headers)++ # Key group routes+ m = _KEY_GROUP_CFG_RE.match(path)+ if m:+ if method == "GET":+ return _get_key_group_config(m.group(1))++ m = _KEY_GROUP_RE.match(path)+ if m:+ if method == "POST":+ return _create_key_group(body)+ if method == "GET":+ return _list_key_groups(query_params)++ m = _KEY_GROUP_ID_RE.match(path)+ if m:+ kg_id = m.group(1)+ if method == "GET":+ return _get_key_group(kg_id)+ if method == "PUT":+ return _update_key_group(kg_id, headers, body)+ if method == "DELETE":+ return _delete_key_group(kg_id, headers)+# CloudFront Functions API (used by Terraform aws_cloudfront_function)m = _FUN_DESCRIBE_RE.match(path)if m:@@ -2055,14 +2431,6 @@ 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.- m = _KEY_GROUP_LIST_RE.match(path)- if m and method == "GET":- return _empty_marker_list(query_params, "KeyGroupList", with_marker=False)-- m = _PUBLIC_KEY_LIST_RE.match(path)- if m and method == "GET":- return _empty_marker_list(query_params, "PublicKeyList", with_marker=False)-m = _FLE_LIST_RE.match(path)if m and method == "GET":return _empty_marker_list(query_params, "FieldLevelEncryptionList", with_marker=False)diff --git a/tests/test_cloudfront.py b/tests/test_cloudfront.pyindex dd488c9d..fcb5b5ca 100644--- a/tests/test_cloudfront.py+++ b/tests/test_cloudfront.py@@ -1773,6 +1773,153 @@ def test_cloudfront_get_monitoring_subscription_errors(cloudfront):cloudfront.delete_distribution(Id=dist_id, IfMatch=upd["ETag"])+# ---------------------------------------------------------------------------+# Public keys and key groups (signed URLs/cookies, OAC key groups).+# ---------------------------------------------------------------------------++_DUMMY_ENCODED_KEY = (+ "-----BEGIN PUBLIC KEY-----\n"+ "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMdummykeydummykeydummykeydummy\n"+ "keydummykeydummykeydummykeydummykeydummykeydummykeydummyIDAQAB\n"+ "-----END PUBLIC KEY-----\n"+)+++def _public_key_config(name):+ return {+ "CallerReference": f"cr-{_uuid_mod.uuid4().hex[:8]}",+ "Name": name,+ "EncodedKey": _DUMMY_ENCODED_KEY,+ "Comment": "test public key",+ }+++def test_cloudfront_create_and_get_public_key(cloudfront):+ name = f"pk-{_uuid_mod.uuid4().hex[:8]}"+ create = cloudfront.create_public_key(PublicKeyConfig=_public_key_config(name))+ assert create["ETag"]+ pk = create["PublicKey"]+ pk_id = pk["Id"]+ assert pk_id+ assert "CreatedTime" in pk++ got = cloudfront.get_public_key(Id=pk_id)+ cfg = got["PublicKey"]["PublicKeyConfig"]+ assert got["ETag"] == create["ETag"]+ assert cfg["Name"] == name+ assert cfg["EncodedKey"] == _DUMMY_ENCODED_KEY++ cfg_only = cloudfront.get_public_key_config(Id=pk_id)+ assert cfg_only["ETag"] == create["ETag"]+ assert cfg_only["PublicKeyConfig"]["Name"] == name++ cloudfront.delete_public_key(Id=pk_id, IfMatch=got["ETag"])+ with pytest.raises(ClientError) as exc:+ cloudfront.get_public_key(Id=pk_id)+ assert exc.value.response["Error"]["Code"] == "NoSuchPublicKey"+++def test_cloudfront_update_public_key(cloudfront):+ name = f"pk-{_uuid_mod.uuid4().hex[:8]}"+ create = cloudfront.create_public_key(PublicKeyConfig=_public_key_config(name))+ pk_id = create["PublicKey"]["Id"]++ with pytest.raises(ClientError) as exc:+ cloudfront.update_public_key(PublicKeyConfig=_public_key_config(name), Id=pk_id)+ assert exc.value.response["Error"]["Code"] == "InvalidIfMatchVersion"++ updated_cfg = dict(create["PublicKey"]["PublicKeyConfig"], Comment="updated comment")+ upd = cloudfront.update_public_key(PublicKeyConfig=updated_cfg, Id=pk_id, IfMatch=create["ETag"])+ assert upd["ETag"] != create["ETag"]+ assert upd["PublicKey"]["PublicKeyConfig"]["Comment"] == "updated comment"++ cloudfront.delete_public_key(Id=pk_id, IfMatch=upd["ETag"])+++def test_cloudfront_list_public_keys_round_trip(cloudfront):+ baseline = cloudfront.list_public_keys()["PublicKeyList"]["Quantity"]++ name = f"pk-{_uuid_mod.uuid4().hex[:8]}"+ create = cloudfront.create_public_key(PublicKeyConfig=_public_key_config(name))+ pk_id = create["PublicKey"]["Id"]++ listed = cloudfront.list_public_keys()["PublicKeyList"]+ assert listed["Quantity"] == baseline + 1+ names = [s["Name"] for s in listed["Items"]]+ assert name in names++ cloudfront.delete_public_key(Id=pk_id, IfMatch=create["ETag"])+++def test_cloudfront_create_and_get_key_group(cloudfront):+ pk_name = f"pk-{_uuid_mod.uuid4().hex[:8]}"+ pk = cloudfront.create_public_key(PublicKeyConfig=_public_key_config(pk_name))+ pk_id = pk["PublicKey"]["Id"]++ kg_name = f"kg-{_uuid_mod.uuid4().hex[:8]}"+ create = cloudfront.create_key_group(+ KeyGroupConfig={"Name": kg_name, "Items": [pk_id], "Comment": "test key group"}+ )+ assert create["ETag"]+ kg = create["KeyGroup"]+ kg_id = kg["Id"]+ assert kg_id+ assert "LastModifiedTime" in kg++ got = cloudfront.get_key_group(Id=kg_id)+ cfg = got["KeyGroup"]["KeyGroupConfig"]+ assert got["ETag"] == create["ETag"]+ assert cfg["Name"] == kg_name+ assert cfg["Items"] == [pk_id]++ cfg_only = cloudfront.get_key_group_config(Id=kg_id)+ assert cfg_only["KeyGroupConfig"]["Items"] == [pk_id]++ cloudfront.delete_key_group(Id=kg_id, IfMatch=got["ETag"])+ with pytest.raises(ClientError) as exc:+ cloudfront.get_key_group(Id=kg_id)+ assert exc.value.response["Error"]["Code"] == "NoSuchResource"++ cloudfront.delete_public_key(Id=pk_id, IfMatch=pk["ETag"])+++def test_cloudfront_key_group_requires_existing_public_key(cloudfront):+ with pytest.raises(ClientError) as exc:+ cloudfront.create_key_group(KeyGroupConfig={"Name": f"kg-{_uuid_mod.uuid4().hex[:8]}", "Items": ["KDOESNOTEXIST"]})+ assert exc.value.response["Error"]["Code"] == "InvalidArgument"+++def test_cloudfront_key_group_duplicate_name_rejected(cloudfront):+ pk = cloudfront.create_public_key(PublicKeyConfig=_public_key_config(f"pk-{_uuid_mod.uuid4().hex[:8]}"))+ pk_id = pk["PublicKey"]["Id"]+ kg_name = f"kg-{_uuid_mod.uuid4().hex[:8]}"+ create = cloudfront.create_key_group(KeyGroupConfig={"Name": kg_name, "Items": [pk_id]})+ kg_id = create["KeyGroup"]["Id"]++ with pytest.raises(ClientError) as exc:+ cloudfront.create_key_group(KeyGroupConfig={"Name": kg_name, "Items": [pk_id]})+ assert exc.value.response["Error"]["Code"] == "KeyGroupAlreadyExists"++ cloudfront.delete_key_group(Id=kg_id, IfMatch=create["ETag"])+ cloudfront.delete_public_key(Id=pk_id, IfMatch=pk["ETag"])+++def test_cloudfront_delete_public_key_in_use_rejected(cloudfront):+ pk = cloudfront.create_public_key(PublicKeyConfig=_public_key_config(f"pk-{_uuid_mod.uuid4().hex[:8]}"))+ pk_id = pk["PublicKey"]["Id"]+ kg = cloudfront.create_key_group(+ KeyGroupConfig={"Name": f"kg-{_uuid_mod.uuid4().hex[:8]}", "Items": [pk_id]}+ )+ kg_id = kg["KeyGroup"]["Id"]++ with pytest.raises(ClientError) as exc:+ cloudfront.delete_public_key(Id=pk_id, IfMatch=pk["ETag"])+ assert exc.value.response["Error"]["Code"] == "PublicKeyInUse"++ cloudfront.delete_key_group(Id=kg_id, IfMatch=kg["ETag"])+ cloudfront.delete_public_key(Id=pk_id, IfMatch=pk["ETag"])++# ---------------------------------------------------------------------------# CloudFront SaaS Manager — connection groups, distribution tenants, managed# certificates, domain verification. Shapes verified against botocore