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(iot): add domain configurations and AWS::IoT::DomainConfiguration (#2040)
iot-rocketb55a94e7f5c4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7d3a02fc..f44988ff 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added+- **IoT — domain configurations** — `CreateDomainConfiguration`, `DescribeDomainConfiguration`, `ListDomainConfigurations`, `UpdateDomainConfiguration` and `DeleteDomainConfiguration`, and the CloudFormation type `AWS::IoT::DomainConfiguration`, were missing. The list now shows the `iot:Data-ATS` and `iot:CredentialProvider` configurations IoT owns (their `domainName` is the `DescribeEndpoint` address). A configuration without a server certificate is AWS-managed with a generated `-ats` host, one with an ACM certificate is customer-managed, and requests are validated with AWS's messages (TLS security policy, authentication type and protocol combinations, certificates, the IoT-owned entries). As on AWS, only a DISABLED configuration can be deleted (AWS's seven-day hold on an AWS-managed one is not enforced), and CloudFormation leaves a configuration DISABLED unless the template enables it, and disables it before deleting it. The broker does not serve a configured domain. Contributed by @iot-rocket.- **CloudFormation — enum properties are validated before provisioning** — a template value outside an enum of the resource schema was only refused by the resource's own create, after the resources before it existed. Such a value, literal or from a parameter, now fails the create before anything is provisioned, as AWS does: one stack `CREATE_FAILED` event "Validation failed with N error(s). ..." with `DetailedStatus` `VALIDATION_FAILED`, then `ROLLBACK_IN_PROGRESS` and `ROLLBACK_COMPLETE`, with no resource event. `DescribeStackEvents` returns `DetailedStatus`. `AWS::Signer::SigningProfile` `PlatformId` is the first property checked. Contributed by @iot-rocket.- **Signer — CloudFormation `AWS::Signer::SigningProfile` and `AWS::Signer::ProfilePermission`, profile permissions and `CancelSigningProfile`** — a template with either type was refused as an unrecognized resource type, and the profile permission API and `CancelSigningProfile` had no route. Both types now provision as AWS does: the profile's `Ref` is its ARN with `Arn`, `ProfileName`, `ProfileVersion` and `ProfileVersionArn` attributes, a generated name is `<LogicalId>_` plus 12 letters and digits, `Tags` (with the stack and `aws:cloudformation:` tags) update in place, a `PlatformId` or `SignatureValidityPeriod` change replaces the profile, a delete cancels it, and a `PlatformId` outside the schema's two values fails the resource with AWS's enum message; the permission's `Ref` is `<StatementId>|<ProfileName>`. `AddProfilePermission`, `ListProfilePermissions` and `RemoveProfilePermission` follow the revision id rules, error codes, 2000-byte policy limit and `policySizeBytes` measured on AWS, a canceled profile keeps its name and its permissions, `PutSigningProfile` refuses a name that is already taken, and `GetSigningProfile` reports the 135-month default validity period. Contributed by @iot-rocket.- **CloudFormation — `AWS::IoT::Thing`, `AWS::IoT::Certificate`, `AWS::IoT::ThingPrincipalAttachment` and `AWS::IoT::PolicyPrincipalAttachment`** — a template using any of them failed with `Unrecognized resource types`. They now provision onto the IoT registry as AWS does: `Ref` and `Fn::GetAtt` return AWS's values (`{name}|{principal}` for the attachments), `AttributePayload` and `Status` update in place, the create-only properties replace the resource, a certificate is deactivated before its delete, a thing or certificate that still has an attachment made outside the stack fails its delete with the service's message, and a `ThingName` that already exists fails the create instead of adopting the thing. A certificate comes from `CertificateSigningRequest`, from `CertificatePem` with `CACertificatePem`, or from `CertificatePem` alone in `SNI_ONLY` mode. Thing and certificate can be imported. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex b2ac7769..7af45142 100644--- a/README.md+++ b/README.md@@ -545,6 +545,7 @@ subnet = ec2.create_subnet(| `AWS::IoT::ThingPrincipalAttachment` | `{ThingName}\|{Principal}` | None || `AWS::IoT::PolicyPrincipalAttachment` | `{PolicyName}\|{Principal}` | None || `AWS::IoT::CACertificate` | Certificate id | Arn, Id |+| `AWS::IoT::DomainConfiguration` | Domain configuration name | Arn, DomainType, ServerCertificates || `AWS::IoT::ThingGroup` | Thing group id | Arn, Id || `AWS::ECR::Repository` | Repo name | Arn, RepositoryUri || `AWS::IAM::ManagedPolicy` | Policy ARN | — |diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 79acd180..d2cef75c 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -705,6 +705,7 @@ _CUSTOM_NAME_REPLACEMENT = {for p in ("ThingTypeDescription", "SearchableAttributes")),},+ "AWS::IoT::DomainConfiguration": {"name": "DomainConfigurationName"},# BackupVaultName is required, so every vault is custom-named. Measured on# an account: adding EncryptionKeyArn fails with the refusal sentence."AWS::Backup::BackupVault": {@@ -13458,6 +13459,79 @@ def _iot_ca_certificate_delete(physical_id, props):_iot._handle_ca_certificate("DELETE", f"/cacertificate/{physical_id}", b"", {})+# --- IoT DomainConfiguration ---+# Measured on an account: an omitted DomainConfigurationName is+# ``{LogicalId}-{suffix}`` (no stack name); a create that does not declare+# DomainConfigurationStatus leaves the configuration DISABLED; an update sends+# only the declared members, so a dropped one keeps its value; and the delete+# disables an ENABLED configuration before deleting it.++_IOT_DOMAIN_CONFIG_UPDATABLE = (+ "AuthorizerConfig", "DomainConfigurationStatus", "TlsConfig",+ "ServerCertificateConfig", "AuthenticationType", "ApplicationProtocol",+ "ClientCertificateConfig",+)+++def _iot_domain_configuration_attrs(name):+ rec = _iot._domain_configurations.get(name) or {}+ return {+ "Arn": rec.get("domainConfigurationArn", ""),+ "DomainType": rec.get("domainType", ""),+ "ServerCertificates": [+ {k[:1].upper() + k[1:]: v for k, v in cert.items()}+ for cert in rec.get("serverCertificates", [])+ ],+ }+++def _iot_domain_configuration_set(name, payload, verb):+ resp = _iot._update_domain_configuration(name, payload)+ if resp[0] >= 400:+ raise ValueError(f"AWS::IoT::DomainConfiguration {verb} failed: {resp[2]!r}")+++def _iot_domain_configuration_create(logical_id, props, stack_name):+ name = props.get("DomainConfigurationName")+ if not name:+ suffix = _physical_name(stack_name, logical_id)[-12:]+ name = f"{logical_id[:115]}-{suffix}"+ payload = _pascal_to_camel({+ k: v for k, v in props.items()+ if k not in ("DomainConfigurationName", "DomainConfigurationStatus", "Tags")+ })+ resp = _iot._create_domain_configuration(name, payload)+ if resp[0] >= 400:+ raise ValueError(f"AWS::IoT::DomainConfiguration create failed: {resp[2]!r}")+ if props.get("DomainConfigurationStatus") != "ENABLED":+ _iot_domain_configuration_set(name, {"domainConfigurationStatus": "DISABLED"}, "create")+ return name, _iot_domain_configuration_attrs(name)+++def _iot_domain_configuration_update(physical_id, old_props, new_props, stack_name):+ """Apply the declared updatable members in place; the create-only ones+ (name, DomainName, ServiceType, the certificate ARNs) replace the+ configuration before this runs."""+ payload = _pascal_to_camel({+ k: new_props[k] for k in _IOT_DOMAIN_CONFIG_UPDATABLE if k in new_props+ })+ if payload:+ _iot_domain_configuration_set(physical_id, payload, "update")+ return physical_id, _iot_domain_configuration_attrs(physical_id)+++def _iot_domain_configuration_delete(physical_id, props):+ rec = _iot._domain_configurations.get(physical_id)+ if rec is None:+ return+ if rec["domainConfigurationStatus"] == "ENABLED":+ _iot_domain_configuration_set(+ physical_id, {"domainConfigurationStatus": "DISABLED"}, "delete")+ resp = _iot._delete_domain_configuration(physical_id)+ if resp[0] >= 400:+ raise ValueError(f"Invalid request provided: {json.loads(resp[2])['message']}")++def _cognito_identity_pool_role_attachment_apply(props):"""Push Roles and RoleMappings onto the identity pool throughSetIdentityPoolRoles, which takes the whole configuration: a property the@@ -13783,6 +13857,10 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {"AWS::IoT::PolicyPrincipalAttachment": ("PolicyName", "Principal"),"AWS::IoT::ThingGroup": ("ThingGroupName", "ParentGroupName"),"AWS::IoT::ThingType": ("ThingTypeName",),+ "AWS::IoT::DomainConfiguration": (+ "DomainConfigurationName", "DomainName", "ServiceType",+ "ValidationCertificateArn", "ServerCertificateArns",+ ),"AWS::Backup::BackupVault": ("BackupVaultName", "EncryptionKeyArn"),"AWS::Location::Tracker": ("TrackerName", "KmsKeyId"),"AWS::S3::MultiRegionAccessPoint": ("Name", "PublicAccessBlockConfiguration", "Regions"),@@ -14732,6 +14810,11 @@ _RESOURCE_HANDLERS = {"delete": _iot_ca_certificate_delete,"import": _iot_ca_certificate_import,},+ "AWS::IoT::DomainConfiguration": {+ "create": _iot_domain_configuration_create,+ "update": _iot_domain_configuration_update,+ "delete": _iot_domain_configuration_delete,+ },"AWS::Cognito::IdentityPoolRoleAttachment": {"create": _cognito_identity_pool_role_attachment_create,"update": _cognito_identity_pool_role_attachment_update,diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex edcd0c8b..4e8e6532 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -44,6 +44,11 @@ Implements the JSON/REST APIs under ``iot.{region}.amazonaws.com``:``ListJobTemplates``, ``DeleteJobTemplate``; ``CreateJob`` with a``jobTemplateArn`` takes the template's document and configuration- ``DescribeEndpoint`` returning a per-account hostname+ - Domain configurations: ``CreateDomainConfiguration``,+ ``DescribeDomainConfiguration``, ``ListDomainConfigurations``,+ ``UpdateDomainConfiguration``, ``DeleteDomainConfiguration``, including+ the ``iot:Data-ATS`` / ``iot:CredentialProvider`` configurations IoT owns+ (control plane only: the broker does not serve a configured domain)This is the control plane — pure HTTP/JSON, no MQTT brokerdependency. The data plane (``iot_data.py``) is@@ -120,6 +125,8 @@ _shadows: AccountRegionScopedDict = AccountRegionScopedDict()_indexing_config: AccountRegionScopedDict = AccountRegionScopedDict()# Registry event configuration (UpdateEventConfigurations), one entry per account+region._event_config: AccountRegionScopedDict = AccountRegionScopedDict()+# Domain configurations (CreateDomainConfiguration & friends): name -> record+_domain_configurations: AccountRegionScopedDict = AccountRegionScopedDict()# CA-certificate registry (RegisterCACertificate & friends): caCertificateId -> record_ca_certificates: AccountRegionScopedDict = AccountRegionScopedDict()# JITR registration code — a single "code" key per account/region@@ -249,6 +256,7 @@ def get_state() -> dict:"shadows": copy.deepcopy(_shadows),"indexing_config": copy.deepcopy(_indexing_config),"event_config": copy.deepcopy(_event_config),+ "domain_configurations": copy.deepcopy(_domain_configurations),"ca_certificates": copy.deepcopy(_ca_certificates),"registration_codes": copy.deepcopy(_registration_codes),"provisioning_templates": copy.deepcopy(_provisioning_templates),@@ -286,6 +294,7 @@ def _restore_state(data: dict | None) -> None:_shadows.update(data.get("shadows", {}))_indexing_config.update(data.get("indexing_config", {}))_event_config.update(data.get("event_config", {}))+ _domain_configurations.update(data.get("domain_configurations", {}))_ca_certificates.update(data.get("ca_certificates", {}))_registration_codes.update(data.get("registration_codes", {}))_provisioning_templates.update(data.get("provisioning_templates", {}))@@ -328,6 +337,7 @@ def reset() -> None:_warned_sql_funcs.clear()_indexing_config.clear()_event_config.clear()+ _domain_configurations.clear()_ca_certificates.clear()_registration_codes.clear()_provisioning_templates.clear()@@ -506,6 +516,10 @@ async def _route_request(# Endpointif path == "/endpoint" and method == "GET":return _describe_endpoint(qp)+ if path == "/domainConfigurations" and method == "GET":+ return _list_domain_configurations(qp)+ if path.startswith("/domainConfigurations/"):+ return _handle_domain_configuration(method, path, body)# Things — list/describe/update/deleteif path == "/things" and method == "GET":@@ -705,6 +719,509 @@ def _describe_endpoint(qp: dict) -> tuple:return json_response({"endpointAddress": host})+# ---------------------------------------------------------------------------+# Domain configurations+# ---------------------------------------------------------------------------++# Names: Create and Delete take ``[\w.-]+``; Describe and Update also accept+# ``:`` so they reach the configurations IoT owns (``iot:Data-ATS``).+_DOMAIN_CONFIG_NAME_RE = re.compile(r"[\w.-]+", re.ASCII)+_RESERVED_DOMAIN_CONFIG_NAME_RE = re.compile(r"[\w.:-]+", re.ASCII)+_AUTHORIZER_NAME_RE = re.compile(r"[\w=,@-]+", re.ASCII)+# The configurations IoT owns. ListDomainConfigurations shows the first two on+# an account that never created one; ``iot:Jobs`` is retired with its endpoint.+_IOT_OWNED_DOMAIN_CONFIGS = {+ "iot:Data-ATS": "DATA",+ "iot:CredentialProvider": "CREDENTIAL_PROVIDER",+}+_RETIRED_DOMAIN_CONFIG_NAMES = frozenset({"iot:Jobs"})+_DEFAULT_SECURITY_POLICY = "IoTSecurityPolicy_TLS13_1_2_2022_10"+# Matched case-insensitively and stored in this spelling, as AWS does.+_SECURITY_POLICIES = {+ p.lower(): p+ for p in (+ "IoTSecurityPolicy_TLS13_1_3_2022_10",+ "IoTSecurityPolicy_TLS13_1_2_2022_10",+ "IoTSecurityPolicy_TLS12_1_2_2022_10",+ "IoTSecurityPolicy_TLS12_1_0_2016_01",+ "IoTSecurityPolicy_TLS12_1_0_2015_01",+ )+}+# Regions that answer "not supported in region" for the 2016 policy (measured+# 2026-10-05; the other ten commercial regions probed accept it).+_TLS12_2016_UNSUPPORTED_REGIONS = frozenset({+ "us-east-1", "us-west-2", "eu-west-1", "eu-central-1",+ "ap-southeast-1", "ap-northeast-1",+})+# authenticationType -> the applicationProtocols it combines with.+_AUTH_PROTOCOLS = {+ "DEFAULT": ("DEFAULT",),+ "AWS_X509": ("SECURE_MQTT", "HTTPS"),+ "AWS_SIGV4": ("MQTT_WSS", "HTTPS"),+ "CUSTOM_AUTH_X509": ("SECURE_MQTT", "HTTPS"),+ "CUSTOM_AUTH": ("SECURE_MQTT", "MQTT_WSS", "HTTPS"),+}+_DOMAIN_CONFIG_ENUMS = (+ ("serviceType", ("DATA", "JOBS", "CREDENTIAL_PROVIDER")),+ ("authenticationType", (+ "DEFAULT", "AWS_X509", "AWS_SIGV4", "CUSTOM_AUTH_X509", "CUSTOM_AUTH",+ "CUSTOM_AUTH_WITH_X509",+ )),+ ("applicationProtocol", ("DEFAULT", "HTTPS", "SECURE_MQTT", "MQTT_WSS")),+ ("domainConfigurationStatus", ("ENABLED", "DISABLED")),+)+_DOMAIN_CONFIG_UPDATE_MEMBERS = (+ "authorizerConfig", "domainConfigurationStatus", "tlsConfig",+ "serverCertificateConfig", "authenticationType", "applicationProtocol",+ "clientCertificateConfig",+)+_DOMAIN_CONFIG_LIST_LIMIT = 250+_PROTOCOLS_DOC = "<https://docs.aws.amazon.com/iot/latest/developerguide/protocols.html>"+++def _domain_config_invalid(message: str) -> tuple:+ return error_response_json("InvalidRequestException", message, 400)+++def _domain_config_constraint(field: str, constraint: str) -> tuple:+ return _domain_config_invalid(+ f"1 validation error detected: Value at '{field}' failed to satisfy "+ f"constraint: Member must {constraint}"+ )+++def _domain_config_name_error(name: str, pattern: re.Pattern) -> tuple | None:+ if len(name) > 128:+ return _domain_config_constraint(+ "domainConfigurationName", "have length less than or equal to 128")+ if not pattern.fullmatch(name):+ return _domain_config_constraint(+ "domainConfigurationName",+ f"satisfy regular expression pattern: {pattern.pattern}")+ return None+++def _domain_config_model_error(payload: dict) -> tuple | None:+ """The request-model checks AWS runs before anything else."""+ for field, allowed in _DOMAIN_CONFIG_ENUMS:+ value = payload.get(field)+ if value is not None and value not in allowed:+ return _domain_config_constraint(+ field, f"satisfy enum value set: [{', '.join(allowed)}]")+ authorizer = payload.get("authorizerConfig")+ authorizer_name = (authorizer or {}).get("defaultAuthorizerName")+ if authorizer_name is not None:+ if not 1 <= len(authorizer_name) <= 128:+ return _domain_config_constraint(+ "authorizerConfig.defaultAuthorizerName",+ "have length less than or equal to 128")+ if not _AUTHORIZER_NAME_RE.fullmatch(authorizer_name):+ return _domain_config_constraint(+ "authorizerConfig.defaultAuthorizerName",+ f"satisfy regular expression pattern: {_AUTHORIZER_NAME_RE.pattern}")+ if len(payload.get("serverCertificateArns") or ()) > 1:+ return _domain_config_constraint(+ "serverCertificateArns", "have length less than or equal to 1")+ return None+++def _domain_config_security_policy(tls_config: dict | None) -> tuple[str | None, tuple | None]:+ """The stored spelling of ``tlsConfig.securityPolicy`` (the default when+ absent), or the error AWS answers for a policy it does not offer here."""+ policy = (tls_config or {}).get("securityPolicy")+ if policy is None:+ return _DEFAULT_SECURITY_POLICY, None+ canonical = _SECURITY_POLICIES.get(str(policy).lower())+ if canonical is None:+ return None, _domain_config_invalid(f"SecurityPolicy {policy} not recognized")+ region = get_region()+ if canonical.endswith("_2016_01") and region in _TLS12_2016_UNSUPPORTED_REGIONS:+ return None, _domain_config_invalid(+ f"SecurityPolicy {policy} is not supported in region {region}")+ return canonical, None+++def _domain_config_auth_error(auth: str, protocol: str, authorizer: dict | None) -> tuple | None:+ if auth not in _AUTH_PROTOCOLS:+ return _domain_config_invalid(+ "The AuthenticationType provided in the request was not recognized. "+ f"Please refer to {_PROTOCOLS_DOC} for supported Authentication Type "+ "values and try again.")+ if protocol not in _AUTH_PROTOCOLS[auth]:+ return _domain_config_invalid(+ "Unsupported combination of AuthenticationType and ApplicationProtocol "+ f"provided. AuthenticationType: [{auth}], ApplicationProtocol: "+ f"[{protocol}]. Please refer to {_PROTOCOLS_DOC} for supported "+ "combinations and try again.")+ if auth.startswith("CUSTOM_AUTH") and not authorizer:+ return _domain_config_invalid(+ "The domain configuration must have a valid AuthorizerConfig configured "+ f"when using {auth} as the AuthenticationType. Please refer to "+ f"{_PROTOCOLS_DOC} for supported combinations and try again.")+ return None+++def _domain_config_arn(name: str, suffix: str | None) -> str:+ resource = f"domainconfiguration/{name}" + (f"/{suffix}" if suffix else "")+ return f"arn:aws:iot:{get_region()}:{get_account_id()}:{resource}"+++def _endpoint_address(endpoint_type: str) -> str:+ """The host DescribeEndpoint answers for ``iot:Data-ATS`` or+ ``iot:CredentialProvider``, which AWS's configurations of the same name+ carry as their ``domainName``. Same host as ``_describe_endpoint``."""+ prefix = _endpoint_prefix(get_account_id())+ region = get_region()+ if endpoint_type == "iot:CredentialProvider":+ return f"{prefix}.credentials.iot.{region}.{_MINISTACK_HOST}:{_GATEWAY_PORT}"+ return f"{prefix}-ats.iot.{region}.{_MINISTACK_HOST}:{_GATEWAY_PORT}"+++def _ensure_owned_domain_configurations() -> None:+ """Materialise the configurations IoT owns, the way AWS does on the+ first domain-configuration call of an account and region. A stored one+ follows the current DescribeEndpoint address (the host or port may differ+ after a restart with persisted state)."""+ for name, service_type in _IOT_OWNED_DOMAIN_CONFIGS.items():+ existing = _domain_configurations.get(name)+ if existing is not None:+ existing["domainName"] = _endpoint_address(name)+ continue+ record = {+ "domainConfigurationName": name,+ "domainConfigurationArn": _domain_config_arn(name, None),+ "domainName": _endpoint_address(name),+ "serverCertificates": [],+ "domainConfigurationStatus": "ENABLED",+ "serviceType": service_type,+ "domainType": "ENDPOINT",+ "lastStatusChangeDate": _now_epoch(),+ }+ if service_type == "DATA":+ record["tlsConfig"] = {"securityPolicy": _DEFAULT_SECURITY_POLICY}+ record["authenticationType"] = "DEFAULT"+ record["applicationProtocol"] = "DEFAULT"+ _domain_configurations[name] = record+++def _domain_config_not_found(name: str) -> tuple:+ return error_response_json(+ "ResourceNotFoundException",+ "Could not find domain configuration for given account ID and domain "+ f"configuration name, AccountId: {get_account_id()}, "+ f"DomainConfigurationName: {name}",+ 404,+ )+++def _acm_certificate(arn: str) -> dict | None:+ from ministack.services import acm as _acm++ return _acm._get_local_certificate(arn)+++def _certificate_lacks_server_auth(cert: dict) -> bool:+ """True for an imported certificate whose extended key usage does not+ include TLS server authentication (no EKU extension at all counts)."""+ pem = cert.get("_pem_body")+ if cert.get("Type") != "IMPORTED" or not pem:+ return False+ try:+ from cryptography import x509+ from cryptography.x509.oid import ExtendedKeyUsageOID++ parsed = x509.load_pem_x509_certificate(pem.encode() if isinstance(pem, str) else pem)+ except Exception:+ return False+ try:+ usages = parsed.extensions.get_extension_for_class(x509.ExtendedKeyUsage).value+ except x509.ExtensionNotFound:+ return True+ return ExtendedKeyUsageOID.SERVER_AUTH not in usages+++def _customer_managed_certificate_error(payload: dict) -> tuple | None:+ server_arn = payload["serverCertificateArns"][0]+ validation_arn = payload.get("validationCertificateArn")+ if not payload.get("domainName"):+ return _domain_config_invalid("Must provide a valid domain name to configure.")+ if validation_arn is not None and validation_arn == server_arn:+ return _domain_config_invalid(+ "Cannot provide a ServerCertificateArn that is the same as a "+ "ValidationCertificateArn")+ for arn in (server_arn, validation_arn):+ if arn is not None and _acm_certificate(arn) is None:+ return _domain_config_invalid(f"Certificate {arn} does not exist.")+ server_cert = _acm_certificate(server_arn)+ if _certificate_lacks_server_auth(server_cert):+ return error_response_json(+ "CertificateValidationException",+ "The certificate is missing ServerAuth in extended key usage of certificate.",+ 400,+ )+ # Only an ACM-issued certificate counts as signed by a trusted CA here; an+ # imported one has to be vouched for by a trusted validation certificate.+ if validation_arn is None and server_cert.get("Type") == "IMPORTED":+ return _domain_config_invalid(+ "Must provide validation certificate when using server certificates not "+ "signed by trusted CA or not within")+ if validation_arn is not None and _acm_certificate(validation_arn).get("Type") == "IMPORTED":+ return _domain_config_invalid("Validation certificate must be signed by trusted CA")+ return None+++def _create_domain_configuration(name: str, payload: dict) -> tuple:+ """``POST /domainConfigurations/{name}``. Without a server certificate+ the configuration is AWS_MANAGED and gets a generated ``-ats`` host; with+ one it is CUSTOMER_MANAGED on the caller's ``domainName``."""+ err = (_domain_config_name_error(name, _DOMAIN_CONFIG_NAME_RE)+ or _domain_config_model_error(payload))+ if err:+ return err+ service_type = payload.get("serviceType") or "DATA"+ if service_type == "JOBS":+ return _domain_config_invalid("Invalid Service Type")+ if service_type != "DATA":+ return _domain_config_invalid(+ "CreateDomainConfiguration only supports DATA Service Type")+ existing = _domain_configurations.get(name)+ if existing is not None:+ return error_response_json(+ "ResourceAlreadyExistsException",+ "Domain configuration already exists",+ 409,+ extra={"resourceId": existing["domainConfigurationArn"].split(":", 5)[5]},+ )+ policy, err = _domain_config_security_policy(payload.get("tlsConfig"))+ if err:+ return err+ auth = payload.get("authenticationType")+ protocol = payload.get("applicationProtocol")+ authorizer = payload.get("authorizerConfig")+ if auth is not None and protocol is None:+ return _domain_config_invalid(+ "The domain must configure a supported ApplicationProtocol when "+ f"configuring an AuthenticationType. Please refer to {_PROTOCOLS_DOC} "+ "for supported combinations and try again.")+ if protocol is not None and auth is None:+ return _domain_config_invalid(+ "The domain must configure a supported AuthenticationType when "+ f"configuring an ApplicationProtocol. Please refer to {_PROTOCOLS_DOC} "+ "for supported combinations and try again.")+ auth = auth or "DEFAULT"+ protocol = protocol or "DEFAULT"+ err = _domain_config_auth_error(auth, protocol, authorizer)+ if err:+ return err+ if payload.get("serverCertificateArns"):+ err = _customer_managed_certificate_error(payload)+ if err:+ return err+ domain_type = "CUSTOMER_MANAGED"+ domain_name = payload["domainName"]+ server_certificates = [{+ "serverCertificateArn": payload["serverCertificateArns"][0],+ "serverCertificateStatus": "VALID",+ }]+ else:+ if payload.get("domainName"):+ return _domain_config_invalid(+ "Cannot provide a custom domain name for an AWS Managed Domain")+ if payload.get("validationCertificateArn"):+ return _domain_config_invalid(+ "Cannot provide a Validation Certificate for AWS Managed Domain Configurations")+ if payload.get("serverCertificateConfig") is not None:+ return _domain_config_invalid(+ "Cannot create a server certificate config for an AWS Managed Domain")+ domain_type = "AWS_MANAGED"+ domain_name = (f"d{uuid.uuid4().hex[:20]}-ats.iot.{get_region()}."+ f"{_MINISTACK_HOST}:{_GATEWAY_PORT}")+ server_certificates = []+ record = {+ "domainConfigurationName": name,+ "domainConfigurationArn": _domain_config_arn(name, uuid.uuid4().hex[:5]),+ "domainName": domain_name,+ "serverCertificates": server_certificates,+ "domainConfigurationStatus": "ENABLED",+ "serviceType": service_type,+ "domainType": domain_type,+ "lastStatusChangeDate": _now_epoch(),+ "tlsConfig": {"securityPolicy": policy},+ "authenticationType": auth,+ "applicationProtocol": protocol,+ }+ for member in ("authorizerConfig", "serverCertificateConfig", "clientCertificateConfig"):+ if payload.get(member):+ record[member] = payload[member]+ _domain_configurations[name] = record+ return json_response({+ "domainConfigurationName": name,+ "domainConfigurationArn": record["domainConfigurationArn"],+ })+++def _describe_domain_configuration(name: str) -> tuple:+ err = _domain_config_name_error(name, _RESERVED_DOMAIN_CONFIG_NAME_RE)+ if err:+ return err+ if name in _RETIRED_DOMAIN_CONFIG_NAMES:+ return _domain_config_invalid("Invalid DomainConfiguration Name")+ _ensure_owned_domain_configurations()+ record = _domain_configurations.get(name)+ if record is None:+ return _domain_config_not_found(name)+ return json_response(record)+++def _list_domain_configurations(qp: dict) -> tuple:+ """``GET /domainConfigurations``. AWS pages with ``pageSize`` (1..250) and+ an opaque ``marker``; its ``serviceType`` filter answers every+ configuration for DATA and CREDENTIAL_PROVIDER alike and refuses JOBS."""+ raw_size = qp.get("pageSize")+ try:+ page_size = int(raw_size) if raw_size not in (None, "") else None+ except (TypeError, ValueError):+ return _domain_config_invalid("pageSize must be an integer")+ if page_size is not None and page_size > _DOMAIN_CONFIG_LIST_LIMIT:+ return _domain_config_constraint(+ "pageSize", f"have value less than or equal to {_DOMAIN_CONFIG_LIST_LIMIT}")+ if page_size is not None and page_size < 1:+ return _domain_config_constraint("pageSize", "have value greater than or equal to 1")+ err = _domain_config_model_error({"serviceType": qp.get("serviceType")})+ if err:+ return err+ if qp.get("serviceType") == "JOBS":+ return _domain_config_invalid("Invalid Service Type")+ offset = 0+ marker = qp.get("marker")+ if marker:+ try:+ prefix, _, value = base64.b64decode(marker, validate=True).decode().partition(":")+ offset = int(value) if prefix == "domainConfigurations" else -1+ except Exception:+ offset = -1+ if offset < 0:+ return _domain_config_invalid("Invalid Token")+ _ensure_owned_domain_configurations()+ records = list(_domain_configurations.values())+ end = len(records) if page_size is None else offset + page_size+ body = {+ "domainConfigurations": [+ {k: r[k] for k in ("domainConfigurationName", "domainConfigurationArn", "serviceType")}+ for r in records[offset:end]+ ]+ }+ if end < len(records):+ body["nextMarker"] = base64.b64encode(f"domainConfigurations:{end}".encode()).decode()+ return json_response(body)+++def _update_domain_configuration(name: str, payload: dict) -> tuple:+ """``PUT /domainConfigurations/{name}``. Unset members keep their value;+ ``tlsConfig`` is replaced whole (no policy means the default one), and+ ``lastStatusChangeDate`` only moves when the status does."""+ err = (_domain_config_name_error(name, _RESERVED_DOMAIN_CONFIG_NAME_RE)+ or _domain_config_model_error(payload))+ if err:+ return err+ remove_authorizer = payload.get("removeAuthorizerConfig") is True+ supplied = {m for m in _DOMAIN_CONFIG_UPDATE_MEMBERS if payload.get(m) is not None}+ if not supplied and not remove_authorizer:+ return _domain_config_invalid("No arguments supplied to update")+ if name in _IOT_OWNED_DOMAIN_CONFIGS or name in _RETIRED_DOMAIN_CONFIG_NAMES:+ # Of an owned configuration only iot:Data-ATS's TLS policy is settable.+ if name != "iot:Data-ATS" or supplied != {"tlsConfig"} or remove_authorizer:+ return _domain_config_invalid(+ "IoT owned domain configuration cannot be updated with the supplied arguments")+ if "authorizerConfig" in supplied and remove_authorizer:+ return _domain_config_invalid(+ "AuthorizerConfig supplied and removeAuthorizer is true, cannot set "+ "authorizer and remove it")+ policy = None+ if "tlsConfig" in supplied:+ policy, err = _domain_config_security_policy(payload["tlsConfig"])+ if err:+ return err+ _ensure_owned_domain_configurations()+ record = _domain_configurations.get(name)+ if record is None:+ return _domain_config_not_found(name)+ if "serverCertificateConfig" in supplied and record["domainType"] != "CUSTOMER_MANAGED":+ return _domain_config_invalid(+ "Cannot configure ServerCertificateConfig for non-customer-managed domains")+ authorizer = record.get("authorizerConfig")+ if remove_authorizer:+ authorizer = None+ elif "authorizerConfig" in supplied:+ authorizer = {**(authorizer or {}), **payload["authorizerConfig"]}+ if record["domainType"] != "ENDPOINT":+ err = _domain_config_auth_error(+ payload.get("authenticationType", record["authenticationType"]),+ payload.get("applicationProtocol", record["applicationProtocol"]),+ authorizer,+ )+ if err:+ return err+ if authorizer:+ record["authorizerConfig"] = authorizer+ else:+ record.pop("authorizerConfig", None)+ if policy is not None:+ record["tlsConfig"] = {"securityPolicy": policy}+ status = payload.get("domainConfigurationStatus")+ if status is not None and status != record["domainConfigurationStatus"]:+ record["domainConfigurationStatus"] = status+ record["lastStatusChangeDate"] = _now_epoch()+ for member in ("authenticationType", "applicationProtocol",+ "serverCertificateConfig", "clientCertificateConfig"):+ if member in supplied:+ record[member] = payload[member]+ _domain_configurations[name] = record+ return json_response({+ "domainConfigurationName": name,+ "domainConfigurationArn": record["domainConfigurationArn"],+ })+++def _delete_domain_configuration(name: str) -> tuple:+ """``DELETE /domainConfigurations/{name}``: only a DISABLED configuration+ goes, and an unknown name answers 200, as on AWS. AWS also keeps an+ AWS_MANAGED configuration until it has been DISABLED for seven days; that+ wall-clock hold is not enforced, so a test or stack can clean up after+ itself."""+ err = _domain_config_name_error(name, _DOMAIN_CONFIG_NAME_RE)+ if err:+ return err+ record = _domain_configurations.get(name)+ if record is None:+ return json_response({})+ if record["domainConfigurationStatus"] != "DISABLED":+ return _domain_config_invalid(+ "Cannot delete a domain configuration that is not disabled")+ del _domain_configurations[name]+ return json_response({})+++def _handle_domain_configuration(method: str, path: str, body: bytes) -> tuple:+ """Dispatch ``/domainConfigurations/{domainConfigurationName}``."""+ name = path[len("/domainConfigurations/"):]+ if not name or "/" in name:+ return error_response_json(+ "InvalidRequestException", f"Unsupported IoT path: {method} {path}", 400+ )+ if method == "POST":+ return _create_domain_configuration(name, _parse_body(body))+ if method == "GET":+ return _describe_domain_configuration(name)+ if method == "PUT":+ return _update_domain_configuration(name, _parse_body(body))+ if method == "DELETE":+ return _delete_domain_configuration(name)+ return error_response_json(+ "InvalidRequestException", f"Unsupported method: {method}", 400+ )++# ---------------------------------------------------------------------------# Thing CRUD# ---------------------------------------------------------------------------diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex c153658e..e19b0324 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -1924,6 +1924,116 @@ def test_cfn_iot_ca_certificate_pem_change_refused(cfn, iot_client):_wait_stack(cfn, "cfn-iot-ca-pem")+def _iot_domain_configuration_template(resources):+ return json.dumps({+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ logical_id: {"Type": "AWS::IoT::DomainConfiguration", "Properties": props}+ for logical_id, props in resources.items()+ },+ "Outputs": {+ f"{logical_id}{attr}": {"Value": {"Fn::GetAtt": [logical_id, attr]}}+ for logical_id in resources for attr in ("Arn", "DomainType")+ } | {f"{logical_id}Ref": {"Value": {"Ref": logical_id}} for logical_id in resources},+ })+++def test_cfn_iot_domain_configuration_lifecycle(cfn, iot_client):+ """Ref is the name (``{LogicalId}-{suffix}`` when generated); a create that+ does not declare DomainConfigurationStatus leaves the configuration+ DISABLED; an update applies the declared members in place and keeps the+ dropped ones; the delete disables an ENABLED configuration and then+ deletes it (AWS's seven-day hold on an AWS-managed one is not enforced)."""+ stack_name = f"cfn-iot-dc-{_uuid_mod.uuid4().hex[:8]}"+ named = f"cfn-dc-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(StackName=stack_name, TemplateBody=_iot_domain_configuration_template({+ "Named": {+ "DomainConfigurationName": named,+ "DomainConfigurationStatus": "ENABLED",+ "TlsConfig": {"SecurityPolicy": "IoTSecurityPolicy_TLS12_1_2_2022_10"},+ "AuthenticationType": "AWS_X509",+ "ApplicationProtocol": "SECURE_MQTT",+ },+ "Unnamed": {},+ }))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", _stack_event_reasons(cfn, stack_name)+ assert _output(stack, "NamedRef") == named+ unnamed = _output(stack, "UnnamedRef")+ assert re.fullmatch(r"Unnamed-[A-Za-z0-9]{12}", unnamed)+ for logical_id, name in (("Named", named), ("Unnamed", unnamed)):+ d = iot_client.describe_domain_configuration(domainConfigurationName=name)+ assert _output(stack, f"{logical_id}Arn") == d["domainConfigurationArn"]+ assert _output(stack, f"{logical_id}DomainType") == "AWS_MANAGED"+ named_desc = iot_client.describe_domain_configuration(domainConfigurationName=named)+ assert named_desc["domainConfigurationStatus"] == "ENABLED"+ assert named_desc["tlsConfig"] == {"securityPolicy": "IoTSecurityPolicy_TLS12_1_2_2022_10"}+ assert (named_desc["authenticationType"], named_desc["applicationProtocol"]) == (+ "AWS_X509", "SECURE_MQTT")+ assert iot_client.describe_domain_configuration(domainConfigurationName=unnamed)[+ "domainConfigurationStatus"] == "DISABLED"++ cfn.update_stack(StackName=stack_name, TemplateBody=_iot_domain_configuration_template({+ "Named": {+ "DomainConfigurationName": named,+ "TlsConfig": {"SecurityPolicy": "IoTSecurityPolicy_TLS13_1_3_2022_10"},+ },+ "Unnamed": {"DomainConfigurationStatus": "ENABLED"},+ }))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", _stack_event_reasons(cfn, stack_name)+ assert _output(stack, "UnnamedRef") == unnamed+ after = iot_client.describe_domain_configuration(domainConfigurationName=named)+ assert after["domainConfigurationArn"] == named_desc["domainConfigurationArn"]+ assert after["tlsConfig"] == {"securityPolicy": "IoTSecurityPolicy_TLS13_1_3_2022_10"}+ assert after["domainConfigurationStatus"] == "ENABLED"+ assert (after["authenticationType"], after["applicationProtocol"]) == ("AWS_X509", "SECURE_MQTT")+ assert iot_client.describe_domain_configuration(domainConfigurationName=unnamed)[+ "domainConfigurationStatus"] == "ENABLED"++ cfn.delete_stack(StackName=stack_name)+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "DELETE_COMPLETE", _stack_event_reasons(cfn, stack_name)+ listed = [d["domainConfigurationName"]+ for d in iot_client.list_domain_configurations()["domainConfigurations"]]+ assert named not in listed and unnamed not in listed+++def test_cfn_iot_domain_configuration_create_only_properties(cfn, iot_client):+ """ServiceType and the other create-only properties replace the+ configuration: refused under a custom name, a new generated name+ otherwise, with the predecessor deleted in the cleanup."""+ stack_name = f"cfn-iot-dc-replace-{_uuid_mod.uuid4().hex[:8]}"+ named = f"cfn-dc-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(StackName=stack_name, TemplateBody=_iot_domain_configuration_template({+ "Named": {"DomainConfigurationName": named}, "Unnamed": {},+ }))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", _stack_event_reasons(cfn, stack_name)+ first = _output(stack, "UnnamedRef")++ cfn.update_stack(StackName=stack_name, TemplateBody=_iot_domain_configuration_template({+ "Named": {"DomainConfigurationName": named, "ServiceType": "DATA"}, "Unnamed": {},+ }))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"+ assert "custom-named resource requires replacing" in _stack_event_reasons(cfn, stack_name)++ cfn.update_stack(StackName=stack_name, TemplateBody=_iot_domain_configuration_template({+ "Named": {"DomainConfigurationName": named}, "Unnamed": {"ServiceType": "DATA"},+ }))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", _stack_event_reasons(cfn, stack_name)+ second = _output(stack, "UnnamedRef")+ assert second != first and second.startswith("Unnamed-")+ listed = [d["domainConfigurationName"]+ for d in iot_client.list_domain_configurations()["domainConfigurations"]]+ assert second in listed and first not in listed++ cfn.delete_stack(StackName=stack_name)+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"++def test_cfn_deleted_stack_name_is_reusable(cfn):"""A DELETE_COMPLETE stack is addressable only by stack ID; its name is freeto re-create, and an UpdateStack against the deleted name is "does notdiff --git a/tests/test_iot.py b/tests/test_iot.pyindex 0f3bb42d..79fab159 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -63,6 +63,389 @@ def test_iot_describe_endpoint_unknown_type_rejected(iot_client):assert ei.value.response["Error"]["Code"] in ("InvalidRequestException",)+# ---------------------------------------------------------------------------+# Domain configurations+# ---------------------------------------------------------------------------++_PROTOCOLS_DOC = "<https://docs.aws.amazon.com/iot/latest/developerguide/protocols.html>"+++def _dc_error(call, **kwargs):+ with pytest.raises(ClientError) as ei:+ call(**kwargs)+ return ei.value.response["Error"]["Code"], ei.value.response["Error"]["Message"]+++def _self_signed_pem(cn, server_auth):+ """A self-signed certificate and key, with or without the serverAuth EKU."""+ import datetime++ from cryptography import x509+ from cryptography.hazmat.primitives import hashes, serialization+ from cryptography.hazmat.primitives.asymmetric import ec+ from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID++ key = ec.generate_private_key(ec.SECP256R1())+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, cn)])+ now = datetime.datetime.now(datetime.timezone.utc)+ builder = (x509.CertificateBuilder().subject_name(name).issuer_name(name)+ .public_key(key.public_key()).serial_number(x509.random_serial_number())+ .not_valid_before(now).not_valid_after(now + datetime.timedelta(days=1)))+ if server_auth:+ builder = builder.add_extension(+ x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)+ cert = builder.sign(key, hashes.SHA256())+ return (cert.public_bytes(serialization.Encoding.PEM),+ key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,+ serialization.NoEncryption()))+++def test_iot_domain_configuration_iot_owned_entries(iot_client):+ """A fresh account lists the iot:Data-ATS and iot:CredentialProvider+ configurations, whose domainName is the DescribeEndpoint address."""+ listed = {+ d["domainConfigurationName"]: d["serviceType"]+ for d in iot_client.list_domain_configurations()["domainConfigurations"]+ }+ assert listed["iot:Data-ATS"] == "DATA"+ assert listed["iot:CredentialProvider"] == "CREDENTIAL_PROVIDER"+ assert "iot:Jobs" not in listed++ ats = iot_client.describe_domain_configuration(domainConfigurationName="iot:Data-ATS")+ assert ats["domainName"] == iot_client.describe_endpoint(+ endpointType="iot:Data-ATS")["endpointAddress"]+ assert ats["domainConfigurationArn"].endswith(":domainconfiguration/iot:Data-ATS")+ assert ats["domainType"] == "ENDPOINT"+ assert ats["domainConfigurationStatus"] == "ENABLED"+ assert ats["serverCertificates"] == []+ assert ats["tlsConfig"] == {"securityPolicy": "IoTSecurityPolicy_TLS13_1_2_2022_10"}+ assert (ats["authenticationType"], ats["applicationProtocol"]) == ("DEFAULT", "DEFAULT")++ cp = iot_client.describe_domain_configuration(domainConfigurationName="iot:CredentialProvider")+ assert cp["domainName"] == iot_client.describe_endpoint(+ endpointType="iot:CredentialProvider")["endpointAddress"]+ assert cp["domainType"] == "ENDPOINT"+ assert not {"tlsConfig", "authenticationType", "applicationProtocol"} & cp.keys()++ assert _dc_error(iot_client.describe_domain_configuration,+ domainConfigurationName="iot:Jobs") == (+ "InvalidRequestException", "Invalid DomainConfiguration Name")+++def test_iot_domain_configuration_create_aws_managed(iot_client):+ name = _unique("dc")+ resp = iot_client.create_domain_configuration(domainConfigurationName=name)+ assert resp["domainConfigurationName"] == name+ assert re.fullmatch(+ rf"arn:aws:iot:us-east-1:\d{{12}}:domainconfiguration/{name}/[a-z0-9]{{5}}",+ resp["domainConfigurationArn"])++ d = iot_client.describe_domain_configuration(domainConfigurationName=name)+ assert d["domainConfigurationArn"] == resp["domainConfigurationArn"]+ assert re.match(r"d[a-z0-9]{20}-ats\.iot\.us-east-1\.", d["domainName"])+ assert d["domainType"] == "AWS_MANAGED"+ assert d["domainConfigurationStatus"] == "ENABLED"+ assert d["serviceType"] == "DATA"+ assert d["serverCertificates"] == []+ assert d["tlsConfig"] == {"securityPolicy": "IoTSecurityPolicy_TLS13_1_2_2022_10"}+ assert (d["authenticationType"], d["applicationProtocol"]) == ("DEFAULT", "DEFAULT")+ assert "authorizerConfig" not in d++ with pytest.raises(ClientError) as ei:+ iot_client.create_domain_configuration(+ domainConfigurationName=name, tlsConfig={"securityPolicy": "Bogus"})+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409+ assert ei.value.response["Error"]["Code"] == "ResourceAlreadyExistsException"+ assert ei.value.response["Error"]["Message"] == "Domain configuration already exists"+ assert ei.value.response["resourceId"] == resp["domainConfigurationArn"].split(":", 5)[5]+++ ("kwargs", "message"),+ [+ ({"domainConfigurationName": "bad:name"},+ "1 validation error detected: Value at 'domainConfigurationName' failed to satisfy "+ "constraint: Member must satisfy regular expression pattern: [\\w.-]+"),+ ({"domainConfigurationName": "x" * 129},+ "1 validation error detected: Value at 'domainConfigurationName' failed to satisfy "+ "constraint: Member must have length less than or equal to 128"),+ ({"serviceType": "CREDENTIAL_PROVIDER"},+ "CreateDomainConfiguration only supports DATA Service Type"),+ ({"serviceType": "JOBS"}, "Invalid Service Type"),+ ({"serviceType": "BOGUS"},+ "1 validation error detected: Value at 'serviceType' failed to satisfy constraint: "+ "Member must satisfy enum value set: [DATA, JOBS, CREDENTIAL_PROVIDER]"),+ ({"tlsConfig": {"securityPolicy": "Bogus"}}, "SecurityPolicy Bogus not recognized"),+ ({"tlsConfig": {"securityPolicy": "IoTSecurityPolicy_TLS12_1_0_2016_01"}},+ "SecurityPolicy IoTSecurityPolicy_TLS12_1_0_2016_01 is not supported in region us-east-1"),+ ({"authenticationType": "AWS_X509"},+ "The domain must configure a supported ApplicationProtocol when configuring an "+ f"AuthenticationType. Please refer to {_PROTOCOLS_DOC} for supported combinations "+ "and try again."),+ ({"applicationProtocol": "HTTPS"},+ "The domain must configure a supported AuthenticationType when configuring an "+ f"ApplicationProtocol. Please refer to {_PROTOCOLS_DOC} for supported combinations "+ "and try again."),+ ({"authenticationType": "AWS_SIGV4", "applicationProtocol": "SECURE_MQTT"},+ "Unsupported combination of AuthenticationType and ApplicationProtocol provided. "+ "AuthenticationType: [AWS_SIGV4], ApplicationProtocol: [SECURE_MQTT]. Please refer "+ f"to {_PROTOCOLS_DOC} for supported combinations and try again."),+ ({"authenticationType": "CUSTOM_AUTH", "applicationProtocol": "HTTPS", "authorizerConfig": {}},+ "The domain configuration must have a valid AuthorizerConfig configured when using "+ f"CUSTOM_AUTH as the AuthenticationType. Please refer to {_PROTOCOLS_DOC} for "+ "supported combinations and try again."),+ ({"domainName": "iot.example.com"},+ "Cannot provide a custom domain name for an AWS Managed Domain"),+ ({"validationCertificateArn": "arn:aws:acm:us-east-1:000000000000:certificate/abc"},+ "Cannot provide a Validation Certificate for AWS Managed Domain Configurations"),+ ({"serverCertificateConfig": {"enableOCSPCheck": True}},+ "Cannot create a server certificate config for an AWS Managed Domain"),+ ({"serverCertificateArns": ["arn:aws:acm:us-east-1:000000000000:certificate/abc"]},+ "Must provide a valid domain name to configure."),+ ({"domainName": "iot.example.com",+ "serverCertificateArns": ["arn:aws:acm:us-east-1:000000000000:certificate/abc"]},+ "Certificate arn:aws:acm:us-east-1:000000000000:certificate/abc does not exist."),+ ({"domainName": "iot.example.com",+ "serverCertificateArns": ["arn:aws:acm:us-east-1:000000000000:certificate/a"] * 2},+ "1 validation error detected: Value at 'serverCertificateArns' failed to satisfy "+ "constraint: Member must have length less than or equal to 1"),+ ],+)+def test_iot_domain_configuration_create_refusals(iot_client, kwargs, message):+ kwargs = {"domainConfigurationName": _unique("dc-refused"), **kwargs}+ assert _dc_error(iot_client.create_domain_configuration, **kwargs) == (+ "InvalidRequestException", message)+ listed = [d["domainConfigurationName"]+ for d in iot_client.list_domain_configurations()["domainConfigurations"]]+ assert kwargs["domainConfigurationName"] not in listed+++def test_iot_domain_configuration_customer_managed_certificates(iot_client, acm_client):+ """An imported (self-signed) server certificate needs serverAuth and a+ trusted validation certificate; an ACM-issued one makes the configuration+ CUSTOMER_MANAGED on the caller's domain."""+ pytest.importorskip("cryptography")+ domain = f"{_unique('dc')}.example.com"+ arns = {}+ for tag, server_auth in (("noeku", False), ("eku", True), ("validation", True)):+ pem, key = _self_signed_pem(domain, server_auth)+ arns[tag] = acm_client.import_certificate(Certificate=pem, PrivateKey=key)["CertificateArn"]+ create = iot_client.create_domain_configuration+ name = _unique("dc-cm")+ base = {"domainConfigurationName": name, "domainName": domain}++ assert _dc_error(create, serverCertificateArns=[arns["noeku"]], **base) == (+ "CertificateValidationException",+ "The certificate is missing ServerAuth in extended key usage of certificate.")+ assert _dc_error(create, serverCertificateArns=[arns["eku"]], **base) == (+ "InvalidRequestException",+ "Must provide validation certificate when using server certificates not signed by "+ "trusted CA or not within")+ assert _dc_error(create, serverCertificateArns=[arns["eku"]],+ validationCertificateArn=arns["eku"], **base) == (+ "InvalidRequestException",+ "Cannot provide a ServerCertificateArn that is the same as a ValidationCertificateArn")+ assert _dc_error(create, serverCertificateArns=[arns["eku"]],+ validationCertificateArn=arns["validation"], **base) == (+ "InvalidRequestException", "Validation certificate must be signed by trusted CA")++ issued = acm_client.request_certificate(DomainName=domain)["CertificateArn"]+ create(serverCertificateArns=[issued], **base)+ d = iot_client.describe_domain_configuration(domainConfigurationName=name)+ assert d["domainType"] == "CUSTOMER_MANAGED"+ assert d["domainName"] == domain+ assert d["serverCertificates"] == [+ {"serverCertificateArn": issued, "serverCertificateStatus": "VALID"}]+ iot_client.update_domain_configuration(+ domainConfigurationName=name, serverCertificateConfig={"enableOCSPCheck": False})+ assert iot_client.describe_domain_configuration(domainConfigurationName=name)[+ "serverCertificateConfig"] == {"enableOCSPCheck": False}+++def test_iot_domain_configuration_update(iot_client):+ name = _unique("dc-upd")+ iot_client.create_domain_configuration(domainConfigurationName=name)+ update = iot_client.update_domain_configuration++ def describe():+ return iot_client.describe_domain_configuration(domainConfigurationName=name)++ # The policy matches case-insensitively and is stored in AWS's spelling;+ # an empty tlsConfig falls back to the default policy.+ update(domainConfigurationName=name,+ tlsConfig={"securityPolicy": "iotsecuritypolicy_tls12_1_2_2022_10"})+ assert describe()["tlsConfig"] == {"securityPolicy": "IoTSecurityPolicy_TLS12_1_2_2022_10"}+ update(domainConfigurationName=name, tlsConfig={})+ assert describe()["tlsConfig"] == {"securityPolicy": "IoTSecurityPolicy_TLS13_1_2_2022_10"}++ assert _dc_error(update, domainConfigurationName=name, removeAuthorizerConfig=False) == (+ "InvalidRequestException", "No arguments supplied to update")+ assert _dc_error(update, domainConfigurationName=name, removeAuthorizerConfig=True,+ authorizerConfig={"allowAuthorizerOverride": True}) == (+ "InvalidRequestException",+ "AuthorizerConfig supplied and removeAuthorizer is true, cannot set authorizer and remove it")+ update(domainConfigurationName=name, authorizerConfig={"allowAuthorizerOverride": True})+ update(domainConfigurationName=name, authorizerConfig={})+ assert describe()["authorizerConfig"] == {"allowAuthorizerOverride": True}++ # The combination is checked against the stored values for the half the+ # request leaves out; a custom-auth type needs the authorizer to stay.+ update(domainConfigurationName=name, authenticationType="CUSTOM_AUTH",+ applicationProtocol="MQTT_WSS")+ assert _dc_error(update, domainConfigurationName=name, removeAuthorizerConfig=True) == (+ "InvalidRequestException",+ "The domain configuration must have a valid AuthorizerConfig configured when using "+ f"CUSTOM_AUTH as the AuthenticationType. Please refer to {_PROTOCOLS_DOC} for "+ "supported combinations and try again.")+ assert _dc_error(update, domainConfigurationName=name, authenticationType="AWS_X509") == (+ "InvalidRequestException",+ "Unsupported combination of AuthenticationType and ApplicationProtocol provided. "+ "AuthenticationType: [AWS_X509], ApplicationProtocol: [MQTT_WSS]. Please refer to "+ f"{_PROTOCOLS_DOC} for supported combinations and try again.")+ assert _dc_error(update, domainConfigurationName=name,+ authenticationType="CUSTOM_AUTH_WITH_X509")[1].startswith(+ "The AuthenticationType provided in the request was not recognized.")+ update(domainConfigurationName=name, authenticationType="DEFAULT",+ applicationProtocol="DEFAULT", removeAuthorizerConfig=True)+ assert "authorizerConfig" not in describe()++ assert _dc_error(update, domainConfigurationName=name,+ serverCertificateConfig={"enableOCSPCheck": True}) == (+ "InvalidRequestException",+ "Cannot configure ServerCertificateConfig for non-customer-managed domains")+ assert _dc_error(update, domainConfigurationName=name,+ domainConfigurationStatus="PAUSED")[1].endswith(+ "Member must satisfy enum value set: [ENABLED, DISABLED]")++ # lastStatusChangeDate only moves when the status does.+ stamp = describe()["lastStatusChangeDate"]+ update(domainConfigurationName=name, domainConfigurationStatus="ENABLED")+ assert describe()["lastStatusChangeDate"] == stamp+ time.sleep(0.01)+ update(domainConfigurationName=name, domainConfigurationStatus="DISABLED")+ assert describe()["domainConfigurationStatus"] == "DISABLED"+ assert describe()["lastStatusChangeDate"] > stamp++ # The policy is checked before the name is looked up.+ missing = _unique("dc-missing")+ assert _dc_error(update, domainConfigurationName=missing,+ tlsConfig={"securityPolicy": "Bogus"}) == (+ "InvalidRequestException", "SecurityPolicy Bogus not recognized")+ code, message = _dc_error(update, domainConfigurationName=missing,+ domainConfigurationStatus="DISABLED")+ assert code == "ResourceNotFoundException"+ assert message.endswith(f"DomainConfigurationName: {missing}")+++def test_iot_domain_configuration_update_iot_owned(iot_client):+ """Of the configurations IoT owns only iot:Data-ATS's TLS policy changes."""+ owned = "IoT owned domain configuration cannot be updated with the supplied arguments"+ update = iot_client.update_domain_configuration+ for name, kwargs in (+ ("iot:Data-ATS", {"domainConfigurationStatus": "ENABLED"}),+ ("iot:Data-ATS", {"removeAuthorizerConfig": True}),+ ("iot:CredentialProvider", {"tlsConfig": {"securityPolicy": "Bogus"}}),+ ("iot:Jobs", {"domainConfigurationStatus": "ENABLED"}),+ ):+ assert _dc_error(update, domainConfigurationName=name, **kwargs) == (+ "InvalidRequestException", owned)+ assert _dc_error(update, domainConfigurationName="iot:Data-ATS",+ tlsConfig={"securityPolicy": "Bogus"}) == (+ "InvalidRequestException", "SecurityPolicy Bogus not recognized")+ try:+ update(domainConfigurationName="iot:Data-ATS",+ tlsConfig={"securityPolicy": "IoTSecurityPolicy_TLS13_1_3_2022_10"})+ assert iot_client.describe_domain_configuration(+ domainConfigurationName="iot:Data-ATS")["tlsConfig"] == {+ "securityPolicy": "IoTSecurityPolicy_TLS13_1_3_2022_10"}+ finally:+ update(domainConfigurationName="iot:Data-ATS", tlsConfig={})+++def test_iot_domain_configuration_delete(iot_client):+ """Only a DISABLED configuration is deleted. AWS also holds an AWS-managed+ one for seven days after it was disabled; MiniStack deletes it at once."""+ name = _unique("dc-del")+ iot_client.create_domain_configuration(domainConfigurationName=name)+ delete = iot_client.delete_domain_configuration+ assert _dc_error(delete, domainConfigurationName=name) == (+ "InvalidRequestException", "Cannot delete a domain configuration that is not disabled")+ iot_client.update_domain_configuration(+ domainConfigurationName=name, domainConfigurationStatus="DISABLED")+ delete(domainConfigurationName=name)+ assert _dc_error(iot_client.describe_domain_configuration,+ domainConfigurationName=name)[0] == "ResourceNotFoundException"+ assert name not in [d["domainConfigurationName"]+ for d in iot_client.list_domain_configurations()["domainConfigurations"]]+ # An unknown name is a no-op; the IoT-owned names fail the Delete pattern.+ delete(domainConfigurationName=_unique("dc-never"))+ assert _dc_error(delete, domainConfigurationName="iot:Data-ATS")[1].endswith(+ "Member must satisfy regular expression pattern: [\\w.-]+")+++def test_iot_domain_configuration_list_paging(iot_client):+ names = [_unique("dc-page") for _ in range(3)]+ for name in names:+ iot_client.create_domain_configuration(domainConfigurationName=name)+ everything = [d["domainConfigurationName"]+ for d in iot_client.list_domain_configurations()["domainConfigurations"]]+ assert set(names) <= set(everything)++ walked, marker = [], None+ while True:+ page = iot_client.list_domain_configurations(+ pageSize=2, **({"marker": marker} if marker else {}))+ assert len(page["domainConfigurations"]) <= 2+ walked += [d["domainConfigurationName"] for d in page["domainConfigurations"]]+ marker = page.get("nextMarker")+ if not marker:+ break+ assert re.fullmatch(r"[A-Za-z0-9+/]+={0,2}", marker)+ assert walked == everything++ # serviceType does not filter on AWS: CREDENTIAL_PROVIDER still lists DATA.+ cp = iot_client.list_domain_configurations(serviceType="CREDENTIAL_PROVIDER")+ assert [d["domainConfigurationName"] for d in cp["domainConfigurations"]] == everything+ assert _dc_error(iot_client.list_domain_configurations, serviceType="JOBS") == (+ "InvalidRequestException", "Invalid Service Type")+ assert _dc_error(iot_client.list_domain_configurations, marker="Zm9v") == (+ "InvalidRequestException", "Invalid Token")+ assert _dc_error(iot_client.list_domain_configurations, pageSize=251) == (+ "InvalidRequestException",+ "1 validation error detected: Value at 'pageSize' failed to satisfy constraint: "+ "Member must have value less than or equal to 250")+++def test_iot_domain_configurations_are_region_scoped_persisted_and_reset():+ import asyncio++ from ministack.core.responses import set_request_account_id, set_request_region+ from ministack.services import iot as iot_module++ name = _unique("dc-scope")++ async def _request(region, method):+ set_request_account_id("123456789012")+ set_request_region(region)+ status, _headers, _body = await iot_module.handle_request(+ method, f"/domainConfigurations/{name}", {}, b"{}" if method == "POST" else b"", {})+ return status++ async def _run():+ assert await _request("eu-west-1", "POST") == 200+ assert await _request("eu-west-1", "GET") == 200+ assert await _request("eu-west-3", "GET") == 404+ assert await _request("eu-west-3", "POST") == 200+ saved = iot_module.get_state()+ iot_module.reset()+ assert await _request("eu-west-1", "GET") == 404+ iot_module.load_persisted_state(saved)+ assert await _request("eu-west-1", "GET") == 200+ assert await _request("eu-west-3", "GET") == 200++ asyncio.run(_run())++# ---------------------------------------------------------------------------# Thing CRUD# ---------------------------------------------------------------------------