Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(cloudformation): provision IoT things, certificates and attachments (#2037)

iot-rocketedd2e3917d0c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9a205ac0..5e39ae84 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,14 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+
+- **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.
+- **IoT — `CreateCertificateFromCsr`** — the operation was missing: `POST /certificates` answered `Unsupported IoT path`. It now signs the CSR with the local CA, as AWS signs it with its own: the certificate keeps the CSR's subject and public key and is `INACTIVE` unless `setAsActive`, and a CSR that does not parse or verify, or whose key is not RSA of at least 2048 bits or EC on P-256, P-384 or P-521, gets `InvalidRequestException` `CSR violates constraints`. Contributed by @iot-rocket.
+
+### Fixed
+
+- **IoT — `DescribeCertificate` reports `certificateMode`** — the field was missing from the description. It is now `SNI_ONLY` for a certificate registered with `RegisterCertificateWithoutCA` and `DEFAULT` for the others, as AWS reports it. Contributed by @iot-rocket.
### Fixed
- **Lambda — preserve invocation aliases in runtime context** — `Invoke` retains the requested alias or version in `invoked_function_arn`, while `function_version` remains the resolved published version. Warm workers receive invocation identity per request.
diff --git a/README.md b/README.md
index ac7d717d..2c1a0347 100644
--- a/README.md
+++ b/README.md
@@ -540,6 +540,10 @@ subnet = ec2.create_subnet(
| `AWS::Cognito::IdentityPool` | Pool ID | — |
| `AWS::Cognito::IdentityPoolPrincipalTag` | `<pool ID>\|<provider name>` | — |
| `AWS::Cognito::UserPoolDomain` | Domain | — |
+| `AWS::IoT::Thing` | Thing name | Arn, Id |
+| `AWS::IoT::Certificate` | Certificate id | Arn, Id |
+| `AWS::IoT::ThingPrincipalAttachment` | `{ThingName}\|{Principal}` | None |
+| `AWS::IoT::PolicyPrincipalAttachment` | `{PolicyName}\|{Principal}` | None |
| `AWS::IoT::CACertificate` | Certificate id | Arn, Id |
| `AWS::IoT::ThingGroup` | Thing group id | Arn, Id |
| `AWS::ECR::Repository` | Repo name | Arn, RepositoryUri |
diff --git a/ministack/core/x509_utils.py b/ministack/core/x509_utils.py
index e0dec800..3c71fbf2 100644
--- a/ministack/core/x509_utils.py
+++ b/ministack/core/x509_utils.py
@@ -231,6 +231,70 @@ def sign_leaf_certificate(
return cert_pem, private_pem, public_pem
+def sign_certificate_request(ca_cert_pem: str, ca_key_pem: str, csr_pem: str) -> str:
+ """Issue a leaf certificate for a PEM CSR, signed by the given CA.
+
+ The certificate carries the CSR's subject and public key; the key never
+ leaves the caller. It is shaped like the certificates AWS IoT's
+ ``CreateCertificateFromCsr`` returns: not a CA, digital signature only,
+ valid until the end of 2049.
+
+ Raises:
+ ValueError: the CSR does not parse, its self-signature does not
+ verify, or its key is neither RSA of at least 2048 bits nor EC on
+ P-256, P-384 or P-521 (the keys AWS accepts).
+ """
+ _require_crypto()
+
+ try:
+ csr = x509.load_pem_x509_csr(csr_pem.encode("utf-8"))
+ valid = csr.is_signature_valid
+ except Exception as e:
+ raise ValueError(f"invalid CSR: {e}") from e
+ if not valid:
+ raise ValueError("invalid CSR: the signature does not verify")
+ key = csr.public_key()
+ if not (
+ (isinstance(key, rsa.RSAPublicKey) and key.key_size >= 2048)
+ or (isinstance(key, ec.EllipticCurvePublicKey) and key.curve.name in ("secp256r1", "secp384r1", "secp521r1"))
+ ):
+ raise ValueError("invalid CSR: the key type or size is not accepted")
+ ca_cert = x509.load_pem_x509_certificate(ca_cert_pem.encode("utf-8"))
+ ca_key = serialization.load_pem_private_key(ca_key_pem.encode("utf-8"), password=None)
+ now = _dt.datetime.now(_dt.timezone.utc)
+ cert = (
+ x509.CertificateBuilder()
+ .subject_name(csr.subject)
+ .issuer_name(ca_cert.subject)
+ .public_key(csr.public_key())
+ .serial_number(x509.random_serial_number())
+ .not_valid_before(now - _dt.timedelta(minutes=1))
+ .not_valid_after(_dt.datetime(2049, 12, 31, 23, 59, 59, tzinfo=_dt.timezone.utc))
+ .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
+ .add_extension(
+ x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_cert.public_key()),
+ critical=False,
+ )
+ .add_extension(x509.SubjectKeyIdentifier.from_public_key(csr.public_key()), critical=False)
+ .add_extension(
+ x509.KeyUsage(
+ digital_signature=True,
+ content_commitment=False,
+ key_encipherment=False,
+ data_encipherment=False,
+ key_agreement=False,
+ key_cert_sign=False,
+ crl_sign=False,
+ encipher_only=False,
+ decipher_only=False,
+ ),
+ critical=True,
+ )
+ .sign(private_key=ca_key, algorithm=hashes.SHA256())
+ )
+ return cert.public_bytes(serialization.Encoding.PEM).decode("utf-8")
+
+
def certificate_is_signed_by(cert_pem: str, ca_cert_pem: str) -> bool:
"""Return True when ``cert_pem`` carries a valid signature from ``ca_cert_pem``.
diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.py
index fc41cbdf..b223d3cf 100644
--- a/ministack/services/cloudformation/changesets.py
+++ b/ministack/services/cloudformation/changesets.py
@@ -179,6 +179,18 @@ def _function_import_problem(name):
return None
+def _thing_import_problem(name):
+ if name not in _iot._things:
+ return _IMPORT_NOT_FOUND.format(type="AWS::IoT::Thing", value=name)
+ return None
+
+
+def _certificate_import_problem(cert_id):
+ if cert_id not in _iot._certificates:
+ return _IMPORT_NOT_FOUND.format(type="AWS::IoT::Certificate", value=cert_id)
+ return None
+
+
def _iot_policy_import_problem(name):
if name not in _iot._policies:
return _IMPORT_NOT_FOUND.format(type="AWS::IoT::Policy", value=name)
@@ -275,6 +287,8 @@ _IMPORT_LOOKUPS = {
"AWS::IAM::Role": (("RoleName",), _role_import_problem),
"AWS::Logs::LogGroup": (("LogGroupName",), _log_group_import_problem),
"AWS::Lambda::Function": (("FunctionName",), _function_import_problem),
+ "AWS::IoT::Thing": (("ThingName",), _thing_import_problem),
+ "AWS::IoT::Certificate": (("Id",), _certificate_import_problem),
"AWS::IoT::Policy": (("Id",), _iot_policy_import_problem),
"AWS::IoT::CACertificate": (("Id",), _ca_certificate_import_problem),
"AWS::Cognito::UserPool": (("UserPoolId",), _user_pool_import_problem),
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index ca6b7097..e77830c7 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -12628,6 +12628,193 @@ def _glue_trigger_delete(physical_id, props):
_glue._delete_trigger({"Name": physical_id})
+# --- IoT Thing, Certificate and the principal attachments ---
+# Each calls the IoT control-plane handler the matching API call reaches. The
+# delete handlers follow the CloudFormation resource handlers: a certificate
+# is deactivated first, and a thing or certificate that still has an
+# attachment made outside the stack fails the delete with the service's
+# message instead of losing it.
+
+
+def _iot_thing_attrs(name):
+ rec = _iot._things.get(name) or {}
+ return {"Arn": rec.get("thingArn", _iot._thing_arn(name)), "Id": rec.get("thingId", "")}
+
+
+def _iot_thing_create(logical_id, props, stack_name):
+ name = props.get("ThingName") or _physical_name(stack_name, logical_id)
+ # CreateThing answers 200 for an identical existing thing, but a stack
+ # never adopts one: AWS fails its name-conflict validation first.
+ if name in _iot._things:
+ raise ValueError(f"Resource of type 'AWS::IoT::Thing' with identifier '{name}' already exists.")
+ payload = {}
+ if props.get("AttributePayload"):
+ payload["attributePayload"] = {
+ "attributes": props["AttributePayload"].get("Attributes") or {}}
+ resp = _iot._create_thing(name, payload)
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::IoT::Thing create failed: {resp[2]!r}")
+ return name, _iot_thing_attrs(name)
+
+
+def _iot_thing_update(physical_id, old_props, new_props, stack_name):
+ """Apply AttributePayload in place: the declared attributes replace the
+ stored ones, and a template that drops AttributePayload leaves them as
+ they are (measured on an account). A ThingName change is a replacement,
+ performed before this runs."""
+ payload = {}
+ if new_props.get("AttributePayload"):
+ payload["attributePayload"] = {
+ "attributes": new_props["AttributePayload"].get("Attributes") or {}}
+ resp = _iot._update_thing(physical_id, payload)
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::IoT::Thing update failed: {resp[2]!r}")
+ return physical_id, _iot_thing_attrs(physical_id)
+
+
+def _iot_thing_import(identifier):
+ return identifier["ThingName"], _iot_thing_attrs(identifier["ThingName"])
+
+
+def _iot_thing_delete(physical_id, props):
+ thing = _iot._things.get(physical_id)
+ if thing is None:
+ return
+ if any(p.rsplit("/", 1)[-1] in _iot._certificates for p in thing.get("principals", [])):
+ raise ValueError(
+ f"Cannot delete. Thing {physical_id} is still attached to one or more principals")
+ _iot._delete_thing(physical_id)
+
+
+def _iot_certificate_attrs(cert_id):
+ return {"Arn": _iot._cert_arn(cert_id), "Id": cert_id}
+
+
+def _iot_certificate_status(cert_id, status):
+ resp = _iot._handle_certificate("PUT", f"/certificates/{cert_id}", b"", {"newStatus": status})
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::IoT::Certificate status update failed: {resp[2]!r}")
+
+
+def _iot_certificate_call(path, payload):
+ """POST to the IoT control plane. Its register handlers are async, so the
+ type runs on a worker thread (``_runs_on_worker_thread``) and waits for
+ the request on the serving loop."""
+ from ministack import app
+
+ return app.call_service_handler_sync(
+ _iot.handle_request, "POST", path, {}, json.dumps(payload).encode(), {})
+
+
+def _iot_certificate_create(logical_id, props, stack_name):
+ """Create the certificate the way the declared properties select:
+ SNI_ONLY registers CertificatePem without a CA, DEFAULT either signs
+ CertificateSigningRequest or registers CertificatePem under
+ CACertificatePem. Any other combination is refused with AWS's message."""
+ status = props.get("Status")
+ if not status:
+ raise ValueError("AWS::IoT::Certificate requires Status")
+ csr = props.get("CertificateSigningRequest")
+ pem = props.get("CertificatePem")
+ ca_pem = props.get("CACertificatePem")
+ if props.get("CertificateMode") == "SNI_ONLY":
+ if csr or ca_pem or not pem:
+ raise ValueError(
+ "Invalid request provided: For certificate mode SNI_ONLY, the following "
+ "combination must be specified exactly: [CertificatePem]")
+ resp = _iot_certificate_call(
+ "/certificate/register-no-ca", {"certificatePem": pem, "status": status})
+ elif csr and not pem and not ca_pem:
+ resp = _iot_certificate_call("/certificates", {"certificateSigningRequest": csr})
+ elif pem and ca_pem and not csr:
+ resp = _iot_certificate_call(
+ "/certificate/register", {"certificatePem": pem, "caCertificatePem": ca_pem, "status": status})
+ else:
+ raise ValueError(
+ "Invalid request provided: For certificate mode Default, one of the following "
+ "combinations must be specified exactly: [CertificatePem and CACertificatePem] "
+ "OR [CertificateSigningRequest]")
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::IoT::Certificate create failed: {resp[2]!r}")
+ cert_id = json.loads(resp[2])["certificateId"]
+ if csr and status != "INACTIVE":
+ # CreateCertificateFromCsr only knows setAsActive.
+ _iot_certificate_status(cert_id, status)
+ return cert_id, _iot_certificate_attrs(cert_id)
+
+
+def _iot_certificate_update(physical_id, old_props, new_props, stack_name):
+ """Status is the one property that updates in place; the PEM, CSR and
+ mode properties are create-only and replace the certificate."""
+ _iot_certificate_status(physical_id, new_props.get("Status"))
+ return physical_id, _iot_certificate_attrs(physical_id)
+
+
+def _iot_certificate_import(identifier):
+ return identifier["Id"], _iot_certificate_attrs(identifier["Id"])
+
+
+def _iot_certificate_delete(physical_id, props):
+ cert = _iot._certificates.get(physical_id)
+ if cert is None:
+ return
+ if cert["status"] == "ACTIVE":
+ _iot_certificate_status(physical_id, "INACTIVE")
+ arn = cert["certificateArn"]
+ # The service refuses DeleteCertificate while things are attached, then
+ # while policies are, in that order.
+ if any(_iot._thing_name_from_arn(t) in _iot._things for t in cert.get("attachedThings", [])):
+ raise ValueError(f"Things must be detached before deletion (arn: {arn})")
+ if _iot._policies_attached_to(arn):
+ raise ValueError(f"Certificate policies must be detached before deletion (arn: {arn})")
+ resp = _iot._handle_certificate("DELETE", f"/certificates/{physical_id}", b"", {})
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::IoT::Certificate delete failed: {resp[2]!r}")
+
+
+def _iot_thing_principal_attachment_call(method, thing, principal, thing_principal_type=None):
+ qp = {"thingPrincipalType": thing_principal_type} if thing_principal_type else {}
+ return _iot._handle_thing_principals(
+ method, f"/things/{thing}/principals", {"x-amzn-principal": principal}, b"", qp)
+
+
+def _iot_thing_principal_attachment_create(logical_id, props, stack_name):
+ """Ref is ``{ThingName}|{Principal}``, the physical id AWS reports."""
+ thing, principal = props.get("ThingName"), props.get("Principal")
+ if not thing or not principal:
+ raise ValueError("AWS::IoT::ThingPrincipalAttachment requires ThingName and Principal")
+ resp = _iot_thing_principal_attachment_call(
+ "PUT", thing, principal, props.get("ThingPrincipalType"))
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::IoT::ThingPrincipalAttachment create failed: {resp[2]!r}")
+ return f"{thing}|{principal}", {}
+
+
+def _iot_thing_principal_attachment_delete(physical_id, props):
+ thing, _, principal = physical_id.partition("|")
+ resp = _iot_thing_principal_attachment_call("DELETE", thing, principal)
+ if resp[0] >= 400 and resp[0] != 404:
+ raise ValueError(f"AWS::IoT::ThingPrincipalAttachment delete failed: {resp[2]!r}")
+
+
+def _iot_policy_principal_attachment_create(logical_id, props, stack_name):
+ """Ref is ``{PolicyName}|{Principal}``, the physical id AWS reports."""
+ policy, principal = props.get("PolicyName"), props.get("Principal")
+ if not policy or not principal:
+ raise ValueError("AWS::IoT::PolicyPrincipalAttachment requires PolicyName and Principal")
+ resp = _iot._change_policy_target(policy, principal, attach=True)
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::IoT::PolicyPrincipalAttachment create failed: {resp[2]!r}")
+ return f"{policy}|{principal}", {}
+
+
+def _iot_policy_principal_attachment_delete(physical_id, props):
+ policy, _, principal = physical_id.partition("|")
+ resp = _iot._change_policy_target(policy, principal, attach=False)
+ if resp[0] >= 400 and resp[0] != 404:
+ raise ValueError(f"AWS::IoT::PolicyPrincipalAttachment delete failed: {resp[2]!r}")
+
+
# --- IoT ThingType / Policy, Cognito IdentityPoolRoleAttachment,
# Lambda LayerVersionPermission (#1345, item 5) ---
# Each maps onto the service's own control-plane create, so the resource is
@@ -13435,6 +13622,12 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {
"AWS::Cognito::UserPoolGroup": ("GroupName", "UserPoolId"),
"AWS::Cognito::UserPoolResourceServer": ("Identifier", "UserPoolId"),
"AWS::Scheduler::ScheduleGroup": ("Name",),
+ "AWS::IoT::Thing": ("ThingName",),
+ "AWS::IoT::Certificate": (
+ "CACertificatePem", "CertificateMode", "CertificatePem", "CertificateSigningRequest",
+ ),
+ "AWS::IoT::ThingPrincipalAttachment": ("Principal", "ThingName", "ThingPrincipalType"),
+ "AWS::IoT::PolicyPrincipalAttachment": ("PolicyName", "Principal"),
"AWS::IoT::ThingGroup": ("ThingGroupName", "ParentGroupName"),
"AWS::IoT::ThingType": ("ThingTypeName",),
"AWS::Backup::BackupVault": ("BackupVaultName", "EncryptionKeyArn"),
@@ -14311,6 +14504,26 @@ _RESOURCE_HANDLERS = {
"update": _sm_target_attachment_update,
"delete": _sm_target_attachment_delete,
},
+ "AWS::IoT::Thing": {
+ "create": _iot_thing_create,
+ "update": _iot_thing_update,
+ "delete": _iot_thing_delete,
+ "import": _iot_thing_import,
+ },
+ "AWS::IoT::Certificate": {
+ "create": _iot_certificate_create,
+ "update": _iot_certificate_update,
+ "delete": _iot_certificate_delete,
+ "import": _iot_certificate_import,
+ },
+ "AWS::IoT::ThingPrincipalAttachment": {
+ "create": _iot_thing_principal_attachment_create,
+ "delete": _iot_thing_principal_attachment_delete,
+ },
+ "AWS::IoT::PolicyPrincipalAttachment": {
+ "create": _iot_policy_principal_attachment_create,
+ "delete": _iot_policy_principal_attachment_delete,
+ },
"AWS::IoT::TopicRule": {
"create": _iot_topic_rule_create,
"update": _iot_topic_rule_update,
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index 2d136a84..608d1016 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -79,13 +79,15 @@ def _runs_on_worker_thread(resource_type: str) -> bool:
signals on its handle, and a nested stack deploys inline and may contain
either. ElastiCache clusters and replication groups start and stop their
containers through the Docker daemon, the calls elasticache.py itself
- keeps off the event loop."""
+ keeps off the event loop. An IoT certificate is registered through the
+ async IoT handler, which a worker thread can wait for."""
return (resource_type.startswith("Custom::")
or resource_type in ("AWS::CloudFormation::CustomResource",
"AWS::CloudFormation::WaitCondition",
"AWS::CloudFormation::Stack",
"AWS::ElastiCache::CacheCluster",
- "AWS::ElastiCache::ReplicationGroup"))
+ "AWS::ElastiCache::ReplicationGroup",
+ "AWS::IoT::Certificate"))
def _update_keeping_seed(*args):
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 8d736967..edcd0c8b 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -8,8 +8,8 @@ Implements the JSON/REST APIs under ``iot.{region}.amazonaws.com``:
``UpdateThing``, ``DeleteThing``
- ThingType: ``CreateThingType`` and friends
- ThingGroup: ``CreateThingGroup`` and friends
- - Certificates: ``CreateKeysAndCertificate``, ``RegisterCertificate``,
- ``RegisterCertificateWithoutCA``, ``UpdateCertificate``,
+ - Certificates: ``CreateKeysAndCertificate``, ``CreateCertificateFromCsr``,
+ ``RegisterCertificate``, ``RegisterCertificateWithoutCA``, ``UpdateCertificate``,
``DeleteCertificate``, ``AttachThingPrincipal`` / ``DetachThingPrincipal``
- CA certificates + JITR: ``GetRegistrationCode`` / ``DeleteRegistrationCode``,
``RegisterCACertificate``, ``DescribeCACertificate``, ``UpdateCACertificate``,
@@ -92,6 +92,7 @@ from ministack.core.x509_utils import (
certificate_is_signed_by,
generate_ca,
get_certificate_id,
+ sign_certificate_request,
sign_leaf_certificate,
)
@@ -557,10 +558,12 @@ async def _route_request(
# Certificates
if path == "/keys-and-certificate" and method == "POST":
return _create_keys_and_certificate(qp)
+ if path == "/certificates" and method == "POST":
+ return _create_certificate_from_csr(_parse_body(body), qp)
if path == "/certificate/register" and method == "POST":
return await _register_certificate(_parse_body(body), qp)
if path == "/certificate/register-no-ca" and method == "POST":
- return await _register_certificate(_parse_body(body), qp, without_ca=True)
+ return await _register_certificate_without_ca(_parse_body(body), qp)
# CA certificates + JITR registration code
if path == "/registrationcode" and method in ("GET", "DELETE"):
@@ -1562,6 +1565,42 @@ def _create_keys_and_certificate(qp: dict) -> tuple:
})
+def _create_certificate_from_csr(payload: dict, qp: dict) -> tuple:
+ """``POST /certificates``: sign the caller's CSR with the Local CA.
+
+ The certificate keeps the CSR's subject and key and is INACTIVE unless
+ ``setAsActive``; a CSR that does not parse or verify, or whose key AWS
+ does not accept, is refused with the message AWS uses for all of these.
+ """
+ try:
+ ca_cert_pem, ca_key_pem = _ensure_ca()
+ cert_pem = sign_certificate_request(
+ ca_cert_pem, ca_key_pem, payload.get("certificateSigningRequest") or "")
+ except ValueError:
+ return error_response_json("InvalidRequestException", "CSR violates constraints", 400)
+ except RuntimeError as e:
+ return error_response_json("InternalFailureException", str(e), 503)
+ cert_id = get_certificate_id(cert_pem)
+ record = _certificate_record(
+ cert_id, cert_pem, "ACTIVE" if _qp_bool(qp, "setAsActive") else "INACTIVE")
+ _certificates[cert_id] = record
+ return json_response({
+ "certificateArn": record["certificateArn"],
+ "certificateId": cert_id,
+ "certificatePem": cert_pem,
+ })
+
+
+async def _register_certificate_without_ca(payload: dict, qp: dict) -> tuple:
+ """``RegisterCertificateWithoutCA``: a certificate registered without a
+ CA is in ``SNI_ONLY`` mode, which DescribeCertificate reports."""
+ response = await _register_certificate(payload, qp, without_ca=True)
+ if response[0] == 200:
+ cert_id = json.loads(response[2])["certificateId"]
+ _certificates[cert_id] = {**_certificates[cert_id], "certificateMode": "SNI_ONLY"}
+ return response
+
+
def _certificate_already_exists(cert_id: str, arn: str | None = None) -> tuple:
"""409 for a duplicate PEM, carrying ``resourceId``/``resourceArn`` the way
real AWS's ``ResourceAlreadyExistsException`` does — all register variants
@@ -1836,6 +1875,7 @@ def _handle_certificate(method: str, path: str, body: bytes, qp: dict) -> tuple:
"certificatePem": record["certificatePem"],
"ownedBy": record["ownedBy"],
"creationDate": record.get("creationDate"),
+ "certificateMode": record.get("certificateMode", "DEFAULT"),
}
# Present only for CA-signed registrations, so JITR consumers can
# resolve the signing CA (per the CertificateDescription model).
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 4c7cf895..be1fec1d 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -914,6 +914,327 @@ def test_cfn_cognito_identity_pool_principal_tag(cfn, cognito_identity):
_wait_stack(cfn, "cfn-cog-tag")
+def _cfn_iot_outputs(stack):
+ return {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}
+
+
+def _cfn_iot_failure(cfn, stack, logical_id, status):
+ events = cfn.describe_stack_events(StackName=stack)["StackEvents"]
+ return next(e["ResourceStatusReason"] for e in events
+ if e["LogicalResourceId"] == logical_id and e["ResourceStatus"] == status)
+
+
+def _cfn_iot_csr(common_name):
+ from cryptography import x509
+ from cryptography.hazmat.primitives import hashes, serialization
+ from cryptography.hazmat.primitives.asymmetric import ec
+ from cryptography.x509.oid import NameOID
+
+ key = ec.generate_private_key(ec.SECP256R1())
+ csr = (x509.CertificateSigningRequestBuilder()
+ .subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, common_name)]))
+ .sign(key, hashes.SHA256()))
+ return csr.public_bytes(serialization.Encoding.PEM).decode(), key
+
+
+def test_cfn_iot_thing_lifecycle(cfn, iot_client):
+ """AWS::IoT::Thing: Ref is the name, Arn and Id come from the registry, an
+ AttributePayload change applies in place (a dropped key is removed, a
+ dropped AttributePayload keeps the attributes), a ThingName change
+ replaces the thing, and the stack delete removes it."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack, first, second = f"cfn-thing-{uid}", f"cfn-thing-a-{uid}", f"cfn-thing-b-{uid}"
+
+ def template(name, attributes):
+ props = {"ThingName": name}
+ if attributes is not None:
+ props["AttributePayload"] = {"Attributes": attributes}
+ return json.dumps({
+ "Resources": {"Named": {"Type": "AWS::IoT::Thing", "Properties": props},
+ "Unnamed": {"Type": "AWS::IoT::Thing"}},
+ "Outputs": {f"{lid}{key}": {"Value": {"Ref": lid} if key == "Ref" else {"Fn::GetAtt": [lid, key]}}
+ for lid in ("Named", "Unnamed") for key in ("Ref", "Arn", "Id")},
+ })
+
+ try:
+ cfn.create_stack(StackName=stack, TemplateBody=template(first, {"color": "red", "size": "m"}))
+ out = _cfn_iot_outputs(_wait_stack(cfn, stack))
+ thing = iot_client.describe_thing(thingName=first)
+ assert (out["NamedRef"], out["NamedArn"], out["NamedId"]) == (first, thing["thingArn"], thing["thingId"])
+ assert thing["attributes"] == {"color": "red", "size": "m"}
+ assert out["UnnamedRef"].startswith(f"{stack}-Unnamed-")
+ unnamed = iot_client.describe_thing(thingName=out["UnnamedRef"])
+ assert (out["UnnamedArn"], out["UnnamedId"]) == (unnamed["thingArn"], unnamed["thingId"])
+
+ cfn.update_stack(StackName=stack, TemplateBody=template(first, {"color": "blue"}))
+ assert _wait_stack(cfn, stack)["StackStatus"] == "UPDATE_COMPLETE"
+ updated = iot_client.describe_thing(thingName=first)
+ assert (updated["thingId"], updated["attributes"]) == (thing["thingId"], {"color": "blue"})
+
+ cfn.update_stack(StackName=stack, TemplateBody=template(first, None))
+ assert _wait_stack(cfn, stack)["StackStatus"] == "UPDATE_COMPLETE"
+ assert iot_client.describe_thing(thingName=first)["attributes"] == {"color": "blue"}
+
+ cfn.update_stack(StackName=stack, TemplateBody=template(second, {"color": "green"}))
+ out = _cfn_iot_outputs(_wait_stack(cfn, stack))
+ renamed = iot_client.describe_thing(thingName=second)
+ assert (out["NamedRef"], out["NamedId"]) == (second, renamed["thingId"]) != (first, thing["thingId"])
+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):
+ iot_client.describe_thing(thingName=first)
+ finally:
+ _delete_cfn_test_stack(cfn, stack)
+ for name in (second, out["UnnamedRef"]):
+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):
+ iot_client.describe_thing(thingName=name)
+
+
+def test_cfn_iot_certificate_lifecycle(cfn, iot_client):
+ """AWS::IoT::Certificate from a CSR (signed by the local CA), from a PEM
+ under a registered CA, and SNI_ONLY without a CA: Ref is the id, Status
+ updates in place, a new CSR replaces the certificate, and the stack
+ delete removes the certificates although they are ACTIVE."""
+ pytest.importorskip("cryptography")
+ from cryptography import x509
+ from cryptography.hazmat.primitives import serialization
+
+ from ministack.core.x509_utils import generate_ca, sign_leaf_certificate
+
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack = f"cfn-cert-{uid}"
+ ca_pem, ca_key, verification_pem = iot_test_ca(
+ iot_client.get_registration_code()["registrationCode"], f"cfn-cert-ca-{uid}")
+ leaf_pem = sign_leaf_certificate(ca_pem, ca_key, common_name=f"cfn-cert-leaf-{uid}")[0]
+ other_pem, other_key = generate_ca(common_name=f"cfn-cert-other-{uid}")
+ sni_pem = sign_leaf_certificate(other_pem, other_key, common_name=f"cfn-cert-sni-{uid}")[0]
+ csr_one, key_one = _cfn_iot_csr(f"cfn-cert-csr-{uid}")
+ csr_two, _key = _cfn_iot_csr(f"cfn-cert-csr2-{uid}")
+
+ def template(csr, csr_status, sni_status):
+ return json.dumps({
+ "Resources": {
+ "Ca": {"Type": "AWS::IoT::CACertificate", "Properties": {
+ "CACertificatePem": ca_pem, "VerificationCertificatePem": verification_pem,
+ "Status": "ACTIVE"}},
+ "CsrCert": {"Type": "AWS::IoT::Certificate", "Properties": {
+ "CertificateSigningRequest": csr, "Status": csr_status}},
+ "CaCert": {"Type": "AWS::IoT::Certificate", "DependsOn": "Ca", "Properties": {
+ "CertificatePem": leaf_pem, "CACertificatePem": ca_pem,
+ "CertificateMode": "DEFAULT", "Status": "ACTIVE"}},
+ "SniCert": {"Type": "AWS::IoT::Certificate", "Properties": {
+ "CertificatePem": sni_pem, "CertificateMode": "SNI_ONLY", "Status": sni_status}},
+ },
+ "Outputs": {"CaId": {"Value": {"Ref": "Ca"}}} | {
+ f"{lid}{key}": {"Value": {"Ref": lid} if key == "Ref" else {"Fn::GetAtt": [lid, key]}}
+ for lid in ("CsrCert", "CaCert", "SniCert") for key in ("Ref", "Arn", "Id")},
+ })
+
+ def describe(cert_id):
+ return iot_client.describe_certificate(certificateId=cert_id)["certificateDescription"]
+
+ try:
+ cfn.create_stack(StackName=stack, TemplateBody=template(csr_one, "ACTIVE", "INACTIVE"))
+ first = _cfn_iot_outputs(_wait_stack(cfn, stack))
+ for lid in ("CsrCert", "CaCert", "SniCert"):
+ assert first[f"{lid}Ref"] == first[f"{lid}Id"]
+ assert first[f"{lid}Arn"].endswith(":cert/" + first[f"{lid}Id"])
+ shapes = {lid: (d["status"], d.get("caCertificateId"), d["certificateMode"])
+ for lid in ("CsrCert", "CaCert", "SniCert") for d in [describe(first[f"{lid}Id"])]}
+ assert shapes == {"CsrCert": ("ACTIVE", None, "DEFAULT"),
+ "CaCert": ("ACTIVE", first["CaId"], "DEFAULT"),
+ "SniCert": ("INACTIVE", None, "SNI_ONLY")}
+ issued = x509.load_pem_x509_certificate(describe(first["CsrCertId"])["certificatePem"].encode())
+ spki = (serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
+ assert issued.public_key().public_bytes(*spki) == key_one.public_key().public_bytes(*spki)
+
+ cfn.update_stack(StackName=stack, TemplateBody=template(csr_one, "INACTIVE", "ACTIVE"))
+ out = _cfn_iot_outputs(_wait_stack(cfn, stack))
+ assert out == first
+ assert (describe(out["CsrCertId"])["status"], describe(out["SniCertId"])["status"]) == (
+ "INACTIVE", "ACTIVE")
+
+ cfn.update_stack(StackName=stack, TemplateBody=template(csr_two, "ACTIVE", "ACTIVE"))
+ out = _cfn_iot_outputs(_wait_stack(cfn, stack))
+ assert out["CsrCertId"] != first["CsrCertId"]
+ assert describe(out["CsrCertId"])["status"] == "ACTIVE"
+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):
+ describe(first["CsrCertId"])
+ finally:
+ _delete_cfn_test_stack(cfn, stack)
+ for key in ("CsrCertId", "CaCertId", "SniCertId"):
+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):
+ describe(out[key])
+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):
+ iot_client.describe_ca_certificate(certificateId=out["CaId"])
+
+
+def test_cfn_iot_thing_existing_name_fails_the_stack(cfn, iot_client):
+ """A stack never adopts a thing created outside it, even with the same
+ properties: the resource fails with AWS's name-conflict message and the
+ thing is left as it was."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack, name = f"cfn-thing-exists-{uid}", f"cfn-thing-exists-{uid}"
+ iot_client.create_thing(thingName=name, attributePayload={"attributes": {"k": "v"}})
+ try:
+ cfn.create_stack(StackName=stack, TemplateBody=json.dumps({"Resources": {"Thing": {
+ "Type": "AWS::IoT::Thing",
+ "Properties": {"ThingName": name, "AttributePayload": {"Attributes": {"k": "v"}}}}}}))
+ assert _wait_stack(cfn, stack)["StackStatus"] == "ROLLBACK_COMPLETE"
+ assert _cfn_iot_failure(cfn, stack, "Thing", "CREATE_FAILED") == (
+ f"Resource of type 'AWS::IoT::Thing' with identifier '{name}' already exists.")
+ finally:
+ _delete_cfn_test_stack(cfn, stack)
+ thing = iot_client.describe_thing(thingName=name)
+ assert (thing["attributes"], thing["version"]) == ({"k": "v"}, 1)
+ iot_client.delete_thing(thingName=name)
+
+
+_CFN_IOT_DEFAULT_COMBINATIONS = (
+ "Invalid request provided: For certificate mode Default, one of the following combinations must be "
+ "specified exactly: [CertificatePem and CACertificatePem] OR [CertificateSigningRequest]")
+_CFN_IOT_SNI_COMBINATION = (
+ "Invalid request provided: For certificate mode SNI_ONLY, the following combination must be "
+ "specified exactly: [CertificatePem]")
+
+
[email protected]("props, reason", [
+ ({"CertificatePem": "leaf"}, _CFN_IOT_DEFAULT_COMBINATIONS),
+ ({"CertificatePem": "leaf", "CertificateSigningRequest": "csr"}, _CFN_IOT_DEFAULT_COMBINATIONS),
+ ({}, _CFN_IOT_DEFAULT_COMBINATIONS),
+ ({"CertificateSigningRequest": "csr", "CertificateMode": "SNI_ONLY"}, _CFN_IOT_SNI_COMBINATION),
+ ({"CertificatePem": "leaf", "CACertificatePem": "ca", "CertificateMode": "SNI_ONLY"},
+ _CFN_IOT_SNI_COMBINATION),
+], ids=["pem-only", "csr-and-pem", "nothing", "sni-csr", "sni-with-ca"])
+def test_cfn_iot_certificate_refuses_property_combinations(cfn, iot_client, props, reason):
+ """Each certificate mode takes one exact set of sources; anything else
+ fails the resource with AWS's message and creates no certificate."""
+ pytest.importorskip("cryptography")
+ from ministack.core.x509_utils import generate_ca, sign_leaf_certificate
+
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack = f"cfn-cert-bad-{uid}"
+ ca_pem, ca_key = generate_ca(common_name=f"cfn-cert-bad-{uid}")
+ values = {"leaf": sign_leaf_certificate(ca_pem, ca_key, common_name=uid)[0], "ca": ca_pem,
+ "csr": _cfn_iot_csr(uid)[0]}
+ props = {k: values.get(v, v) for k, v in props.items()}
+ before = {c["certificateId"] for c in iot_client.list_certificates()["certificates"]}
+ try:
+ cfn.create_stack(StackName=stack, TemplateBody=json.dumps({"Resources": {"Cert": {
+ "Type": "AWS::IoT::Certificate", "Properties": {**props, "Status": "ACTIVE"}}}}))
+ assert _wait_stack(cfn, stack)["StackStatus"] == "ROLLBACK_COMPLETE"
+ assert _cfn_iot_failure(cfn, stack, "Cert", "CREATE_FAILED") == reason
+ assert {c["certificateId"] for c in iot_client.list_certificates()["certificates"]} == before
+ finally:
+ _delete_cfn_test_stack(cfn, stack)
+
+
+def test_cfn_iot_principal_attachments(cfn, iot_client):
+ """ThingPrincipalAttachment and PolicyPrincipalAttachment attach the
+ certificate, Ref is ``{name}|{principal}``, a ThingName or PolicyName
+ change replaces the attachment (the old one is detached), and the stack
+ delete detaches before it deletes the certificate."""
+ pytest.importorskip("cryptography")
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack = f"cfn-att-{uid}"
+ thing1, thing2, pol1, pol2 = (f"cfn-att-{s}-{uid}" for s in ("t1", "t2", "p1", "p2"))
+ csr = _cfn_iot_csr(uid)[0]
+ document = {"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "iot:Connect", "Resource": "*"}]}
+
+ def template(tpa_thing, ppa_policy):
+ return json.dumps({
+ "Resources": {
+ "Thing1": {"Type": "AWS::IoT::Thing", "Properties": {"ThingName": thing1}},
+ "Thing2": {"Type": "AWS::IoT::Thing", "Properties": {"ThingName": thing2}},
+ "Cert": {"Type": "AWS::IoT::Certificate", "Properties": {
+ "CertificateSigningRequest": csr, "Status": "ACTIVE"}},
+ "Pol1": {"Type": "AWS::IoT::Policy", "Properties": {"PolicyName": pol1, "PolicyDocument": document}},
+ "Pol2": {"Type": "AWS::IoT::Policy", "Properties": {"PolicyName": pol2, "PolicyDocument": document}},
+ "Tpa": {"Type": "AWS::IoT::ThingPrincipalAttachment", "Properties": {
+ "ThingName": {"Ref": tpa_thing}, "Principal": {"Fn::GetAtt": ["Cert", "Arn"]}}},
+ "Ppa": {"Type": "AWS::IoT::PolicyPrincipalAttachment", "Properties": {
+ "PolicyName": {"Ref": ppa_policy}, "Principal": {"Fn::GetAtt": ["Cert", "Arn"]}}},
+ },
+ "Outputs": {"Tpa": {"Value": {"Ref": "Tpa"}}, "Ppa": {"Value": {"Ref": "Ppa"}},
+ "CertArn": {"Value": {"Fn::GetAtt": ["Cert", "Arn"]}},
+ "CertId": {"Value": {"Ref": "Cert"}}},
+ })
+
+ def principals(thing):
+ return iot_client.list_thing_principals(thingName=thing)["principals"]
+
+ def policies(arn):
+ return [p["policyName"] for p in iot_client.list_attached_policies(target=arn)["policies"]]
+
+ try:
+ cfn.create_stack(StackName=stack, TemplateBody=template("Thing1", "Pol1"))
+ out = _cfn_iot_outputs(_wait_stack(cfn, stack))
+ arn = out["CertArn"]
+ assert (out["Tpa"], out["Ppa"]) == (f"{thing1}|{arn}", f"{pol1}|{arn}")
+ assert (principals(thing1), principals(thing2), policies(arn)) == ([arn], [], [pol1])
+
+ cfn.update_stack(StackName=stack, TemplateBody=template("Thing2", "Pol2"))
+ out = _cfn_iot_outputs(_wait_stack(cfn, stack))
+ assert (out["Tpa"], out["Ppa"]) == (f"{thing2}|{arn}", f"{pol2}|{arn}")
+ assert (principals(thing1), principals(thing2), policies(arn)) == ([], [arn], [pol2])
+ finally:
+ _delete_cfn_test_stack(cfn, stack)
+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):
+ iot_client.describe_certificate(certificateId=out["CertId"])
+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):
+ iot_client.describe_thing(thingName=thing2)
+
+
+def test_cfn_iot_delete_keeps_what_is_attached_outside_the_stack(cfn, iot_client):
+ """A certificate with a policy or a thing attached outside the stack is
+ deactivated and then fails its delete, as is a thing with an outside
+ certificate; the stack lands in DELETE_FAILED, and once detached a
+ second delete completes."""
+ pytest.importorskip("cryptography")
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack, thing, policy = f"cfn-iot-keep-{uid}", f"cfn-iot-keep-{uid}", f"cfn-iot-keep-{uid}"
+ iot_client.create_policy(policyName=policy, policyDocument=json.dumps({
+ "Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "iot:Connect", "Resource": "*"}]}))
+ outside = iot_client.create_keys_and_certificate(setAsActive=False)
+ cfn.create_stack(StackName=stack, TemplateBody=json.dumps({
+ "Resources": {"Cert": {"Type": "AWS::IoT::Certificate", "Properties": {
+ "CertificateSigningRequest": _cfn_iot_csr(uid)[0], "Status": "ACTIVE"}},
+ "Thing": {"Type": "AWS::IoT::Thing", "Properties": {"ThingName": thing}}},
+ "Outputs": {"Arn": {"Value": {"Fn::GetAtt": ["Cert", "Arn"]}}, "Id": {"Value": {"Ref": "Cert"}}},
+ }))
+ out = _cfn_iot_outputs(_wait_stack(cfn, stack))
+ arn, cert_id = out["Arn"], out["Id"]
+ try:
+ iot_client.attach_policy(policyName=policy, target=arn)
+ iot_client.attach_thing_principal(thingName=thing, principal=outside["certificateArn"])
+ cfn.delete_stack(StackName=stack)
+ assert _wait_stack(cfn, stack)["StackStatus"] == "DELETE_FAILED"
+ assert _cfn_iot_failure(cfn, stack, "Cert", "DELETE_FAILED") == (
+ f"Certificate policies must be detached before deletion (arn: {arn})")
+ assert _cfn_iot_failure(cfn, stack, "Thing", "DELETE_FAILED") == (
+ f"Cannot delete. Thing {thing} is still attached to one or more principals")
+ assert iot_client.describe_certificate(certificateId=cert_id)["certificateDescription"]["status"] == "INACTIVE"
+ assert iot_client.describe_thing(thingName=thing)["thingName"] == thing
+
+ # The things check comes first.
+ iot_client.detach_thing_principal(thingName=thing, principal=outside["certificateArn"])
+ iot_client.attach_thing_principal(thingName=thing, principal=arn)
+ cfn.delete_stack(StackName=stack)
+ assert _wait_stack(cfn, stack)["StackStatus"] == "DELETE_FAILED"
+ assert _cfn_iot_failure(cfn, stack, "Cert", "DELETE_FAILED") == (
+ f"Things must be detached before deletion (arn: {arn})")
+
+ iot_client.detach_thing_principal(thingName=thing, principal=arn)
+ iot_client.detach_policy(policyName=policy, target=arn)
+ cfn.delete_stack(StackName=stack)
+ assert _wait_stack(cfn, stack)["StackStatus"] == "DELETE_COMPLETE"
+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):
+ iot_client.describe_certificate(certificateId=cert_id)
+ finally:
+ _delete_cfn_test_stack(cfn, stack)
+ iot_client.delete_certificate(certificateId=outside["certificateId"])
+ iot_client.delete_policy(policyName=policy)
+
+
def test_cfn_iot_policy_document_update_applies_in_place(cfn, iot_client):
"""A changed PolicyDocument updates the policy instead of rolling the stack
back: IoT stores a new default version and Ref keeps the same name."""
@@ -31531,6 +31852,8 @@ def test_cfn_import_adopts_each_supported_type(cfn, sqs, ssm, s3, ddb, iam, logs
zf.writestr("index.py", "def handler(e, c):\n return e\n")
fn_arn = lam.create_function(FunctionName=name, Runtime="python3.12", Role=role["Arn"],
Handler="index.handler", Code={"ZipFile": buf.getvalue()})["FunctionArn"]
+ thing = iot_client.create_thing(thingName=name)
+ cert = iot_client.create_keys_and_certificate(setAsActive=True)
policy_arn = iot_client.create_policy(policyName=name, policyDocument=json.dumps(document))["policyArn"]
ca = iot_client.register_ca_certificate(caCertificate=ca_pem, certificateMode="SNI_ONLY",
setAsActive=True)
@@ -31554,6 +31877,11 @@ def test_cfn_import_adopts_each_supported_type(cfn, sqs, ssm, s3, ddb, iam, logs
"F": ("AWS::Lambda::Function", {"FunctionName": name}, {
"FunctionName": name, "Runtime": "python3.12", "Handler": "index.handler", "Role": role["Arn"],
"Code": {"ZipFile": "def handler(e, c):\n return e\n"}}, {"Arn": fn_arn}),
+ "IT": ("AWS::IoT::Thing", {"ThingName": name}, {"ThingName": name},
+ {"Arn": thing["thingArn"], "Id": thing["thingId"]}),
+ "IC": ("AWS::IoT::Certificate", {"Id": cert["certificateId"]}, {
+ "CertificatePem": cert["certificatePem"], "Status": "ACTIVE"},
+ {"Arn": cert["certificateArn"], "Id": cert["certificateId"]}),
"IP": ("AWS::IoT::Policy", {"Id": name}, {"PolicyName": name, "PolicyDocument": document},
{"Arn": policy_arn, "Id": name}),
"CA": ("AWS::IoT::CACertificate", {"Id": ca["certificateId"]}, {
@@ -31595,6 +31923,9 @@ def test_cfn_import_adopts_each_supported_type(cfn, sqs, ssm, s3, ddb, iam, logs
lam.delete_function(FunctionName=name)
iam.delete_role(RoleName=name)
logs.delete_log_group(logGroupName=name)
+ iot_client.delete_thing(thingName=name)
+ iot_client.update_certificate(certificateId=cert["certificateId"], newStatus="INACTIVE")
+ iot_client.delete_certificate(certificateId=cert["certificateId"])
iot_client.delete_policy(policyName=name)
iot_client.update_ca_certificate(certificateId=ca["certificateId"], newStatus="INACTIVE")
iot_client.delete_ca_certificate(certificateId=ca["certificateId"])
@@ -31615,6 +31946,10 @@ _CFN_IMPORT_MISSING = {
"FunctionName",
r"Function not found: arn:aws:lambda:[a-z0-9-]+:\d{{12}}:function:{v} \(Service: Lambda, "
r"Status Code: 404, Request ID: [0-9a-f-]+\) \(SDK Attempt Count: 1\)"),
+ "AWS::IoT::Thing": (
+ "ThingName", r"Resource of type 'AWS::IoT::Thing' with identifier '{v}' was not found\."),
+ "AWS::IoT::Certificate": (
+ "Id", r"Resource of type 'AWS::IoT::Certificate' with identifier '{v}' was not found\."),
"AWS::IoT::Policy": (
"Id", r"Resource of type 'AWS::IoT::Policy' with identifier '{v}' was not found\."),
"AWS::IoT::CACertificate": (
diff --git a/tests/test_iot.py b/tests/test_iot.py
index a9540aff..0f3bb42d 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -491,6 +491,54 @@ def test_iot_create_keys_and_certificate_inactive(iot_client):
iot_client.delete_certificate(certificateId=resp["certificateId"])
+def test_iot_create_certificate_from_csr(iot_client):
+ """CreateCertificateFromCsr signs the CSR with the local CA: the
+ certificate keeps the CSR's subject and key, is INACTIVE unless
+ setAsActive, and is in DEFAULT mode; a CSR that does not parse or verify,
+ or carries a key AWS refuses, is refused with AWS's message."""
+ pytest.importorskip("cryptography")
+ from cryptography import x509
+ from cryptography.hazmat.primitives import hashes, serialization
+ from cryptography.hazmat.primitives.asymmetric import ec, rsa
+ from cryptography.x509.oid import NameOID
+
+ key = ec.generate_private_key(ec.SECP256R1())
+ subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "csr-device"),
+ x509.NameAttribute(NameOID.ORGANIZATION_NAME, "csr-org")])
+ csr = (x509.CertificateSigningRequestBuilder().subject_name(subject)
+ .sign(key, hashes.SHA256()).public_bytes(serialization.Encoding.PEM).decode())
+
+ inactive = iot_client.create_certificate_from_csr(certificateSigningRequest=csr)
+ active = iot_client.create_certificate_from_csr(certificateSigningRequest=csr, setAsActive=True)
+ assert inactive["certificateId"] != active["certificateId"]
+ assert inactive["certificateArn"].endswith(":cert/" + inactive["certificateId"])
+ issued = x509.load_pem_x509_certificate(inactive["certificatePem"].encode())
+ spki = (serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
+ assert issued.subject == subject
+ assert issued.public_key().public_bytes(*spki) == key.public_key().public_bytes(*spki)
+ assert not issued.extensions.get_extension_for_class(x509.BasicConstraints).value.ca
+ desc = iot_client.describe_certificate(certificateId=inactive["certificateId"])["certificateDescription"]
+ assert (desc["status"], desc["certificateMode"], desc["certificatePem"]) == (
+ "INACTIVE", "DEFAULT", inactive["certificatePem"])
+ assert iot_client.describe_certificate(
+ certificateId=active["certificateId"])["certificateDescription"]["status"] == "ACTIVE"
+
+ tampered = csr.replace(csr.splitlines()[-2], csr.splitlines()[-2][:-6] + "AAAAAA")
+ weak = [rsa.generate_private_key(public_exponent=65537, key_size=1024),
+ ec.generate_private_key(ec.SECP224R1()), ec.generate_private_key(ec.SECP256K1())]
+ refused = [(x509.CertificateSigningRequestBuilder().subject_name(subject)
+ .sign(k, hashes.SHA256()).public_bytes(serialization.Encoding.PEM).decode()) for k in weak]
+ for bad in ("not a csr", tampered, *refused):
+ with pytest.raises(ClientError) as ei:
+ iot_client.create_certificate_from_csr(certificateSigningRequest=bad)
+ assert ei.value.response["Error"]["Code"] == "InvalidRequestException"
+ assert ei.value.response["Error"]["Message"] == "CSR violates constraints"
+
+ iot_client.update_certificate(certificateId=active["certificateId"], newStatus="INACTIVE")
+ for resp in (inactive, active):
+ iot_client.delete_certificate(certificateId=resp["certificateId"])
+
+
def test_iot_delete_active_certificate_rejected(iot_client):
pytest.importorskip("cryptography")
resp = iot_client.create_keys_and_certificate(setAsActive=True)
@@ -700,6 +748,7 @@ def test_iot_register_certificate_without_ca_roundtrip(iot_client):
desc = iot_client.describe_certificate(certificateId=cert_id)
assert desc["certificateDescription"]["certificatePem"] == cert_pem
assert desc["certificateDescription"]["status"] == "ACTIVE"
+ assert desc["certificateDescription"]["certificateMode"] == "SNI_ONLY"
iot_client.update_certificate(certificateId=cert_id, newStatus="INACTIVE")
iot_client.delete_certificate(certificateId=cert_id)