Skip to content

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

feat(iot): add ListCertificatesByCA (#2004)

iot-rocket05b3fe977b07
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 90fe13ad..9e80a209 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Fixed
+- **IoT — `RegisterCertificate` links the CA that signed the certificate** — a certificate registered without `caCertificatePem` carried no `caCertificateId`, even when a registered ACTIVE CA had signed it, so `DescribeCertificate` named no CA and `ListCertificatesByCA` left it out. It is now linked to that CA, as AWS does; when several registered CAs share a subject, the signature decides. Contributed by @iot-rocket.
- **IoT — a CONTINUOUS job runs again for a thing that rejoins its target group** — executions were kept one per thing and job, so a thing that finished the job, left the group and was added back never got another execution. Joining a target group now queues the next execution number when the thing's newest execution is finished, leaving the group moves a QUEUED execution to `REMOVED`, both publish `jobs/notify(-next)`, the `notify-next` execution leaves out `thingName` and an empty `statusDetails`, and `ListJobExecutionsForThing`, `DescribeJobExecution` with `executionNumber` and `jobProcessDetails` include the earlier executions, as AWS does. Contributed by @iot-rocket.
- **IoT — a `#` region no longer widens topic filters** — a WebSocket session whose credential names `#` as its region received every message published under that region, whatever its filter, because filters were matched with the account and region prefix in front of them. Contributed by @iot-rocket.
- **Cognito — app client secret hashes** — clients created with `GenerateSecret=true` require a valid `SecretHash` on signup, confirmation and password recovery, and `SECRET_HASH` on authentication and challenge responses. Missing or incorrect hashes return `NotAuthorizedException` before user changes, email delivery or Lambda triggers. Clients without a secret reject a supplied hash on self-service and initial authentication calls, while refresh and challenge responses ignore it, as on AWS. Refresh authentication verifies the token owner's username, or `sub` when the pool uses `UsernameAttributes`, and custom challenge sessions cannot be answered through a different client. The checks apply in both `AUTH` modes.
@@ -36,6 +37,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **RDS — a MySQL master user started in the background keeps its admin grant** — an instance whose engine image was not cached yet, or one respawned on restore, started on a background path that skipped the master-user grant the inline path gives, so the master user held only its own database and `SET PERSIST` failed for lack of `SYSTEM_VARIABLES_ADMIN`. Both paths now grant it. Contributed by @skialpine.
### Added
+- **IoT — `ListCertificatesByCA`** — `GET /certificates-by-ca/{caCertificateId}` answered `Unsupported IoT path`. It now lists the device certificates registered under the CA, in every status, newest first unless `isAscendingOrder=true`, and pages with `pageSize` (1 to 250) and a `nextMarker` that continues after the last certificate of the page; an id that names no CA is an empty list, and out of range page sizes, malformed ids and markers answer AWS's `InvalidRequestException` messages. Contributed by @iot-rocket.
- **IoT — lifecycle events** — the broker publishes `$aws/events/presence/connected|disconnected/{clientId}` and `$aws/events/subscriptions/subscribed|unsubscribed/{clientId}` with the AWS payload (`sessionIdentifier` kept by a resumed session, `principalIdentifier` the client certificate id, `versionNumber` advancing on every connect and disconnect, `disconnectReason` and `clientInitiatedDisconnect`), and as on AWS a subscription or topic rule whose filter starts with `#` or `+` does not receive `$aws/events` messages; client ids containing `#` or `+` get no lifecycle events. Contributed by @iot-rocket.
- **Cognito — `SetUICustomization` and `GetUICustomization`** — store and return the classic hosted UI branding (CSS) for a user pool (`ClientId` `ALL`) or one app client, with the client falling back to the pool default, so SDK calls and Terraform's `aws_cognito_user_pool_ui_customization` work. As on AWS the pool needs a domain first. A logo `ImageFile` is accepted but not stored, as ministack does not serve hosted UI assets.
- **OpenSearch Serverless — collections, security and access policies, and a proxied data plane** — `CreateCollection`, `BatchGetCollection`, `ListCollections`, `UpdateCollection`, `DeleteCollection`, `Create`/`Get`/`Update`/`Delete`/`ListSecurityPolicy` (`encryption`, `network`), `Create`/`Get`/`Update`/`Delete`/`ListAccessPolicy` (`data`), `GetPoliciesStats` and `TagResource` / `UntagResource` / `ListTagsForResource`, enough for Terraform's `aws_opensearchserverless_collection`, `_security_policy` and `_access_policy` to apply, plan clean and destroy. A collection needs a matching encryption policy (exact name or `prefix*`, most specific wins) unless `encryptionConfig` is given, and answers `kmsKeyArn: auto` for an AWS-owned key; policy documents are validated, a resource pattern may sit in only one encryption policy, a data policy refuses empty or wildcard principals, and an update must name the current `policyVersion` (`base64("<lastModifiedDate>_<n>")`). Its `collectionEndpoint`, `http://<id>.<region>.aoss.<host>:<port>`, is served through the gateway and requests must be SigV4-signed for `aoss` and carry `x-amz-content-sha256` (403 otherwise); with `OPENSEARCH_DATAPLANE=1` it is backed by its own `opensearchproject/opensearch` container, persisted on a named Docker volume across a restart under `PERSIST_STATE` and removed on `DeleteCollection`, otherwise it answers 503. APIs AOSS does not support answer 404, as `_refresh`, `_cluster/*` and scroll do on AWS, and `TIMESERIES` collections refuse custom document ids and updates. Data access and network policies are stored, not enforced. Checked against the botocore model and the OpenSearch Serverless developer guide and API reference.
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index e74dfcab..e4c2afde 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -13,9 +13,10 @@ Implements the JSON/REST APIs under ``iot.{region}.amazonaws.com``:
``DeleteCertificate``, ``AttachThingPrincipal`` / ``DetachThingPrincipal``
- CA certificates + JITR: ``GetRegistrationCode`` / ``DeleteRegistrationCode``,
``RegisterCACertificate``, ``DescribeCACertificate``, ``UpdateCACertificate``,
- ``ListCACertificates``, ``DeleteCACertificate``; an mTLS connect with an
- unknown certificate signed by a CA with auto-registration enabled creates
- it PENDING_ACTIVATION and publishes the AWS JITR event to
+ ``ListCACertificates``, ``DeleteCACertificate``, ``ListCertificatesByCA``;
+ an mTLS connect with an unknown certificate signed by a CA with
+ auto-registration enabled creates it PENDING_ACTIVATION and publishes the
+ AWS JITR event to
``$aws/events/certificates/registered/{caCertificateId}``
- Provisioning templates: ``CreateProvisioningTemplate``,
``DescribeProvisioningTemplate``, ``ListProvisioningTemplates``,
@@ -565,6 +566,8 @@ async def _route_request(
if path == "/certificates" and method == "GET":
return _list_certificates(qp)
+ if path.startswith("/certificates-by-ca/") and method == "GET":
+ return _list_certificates_by_ca(path, qp)
if path.startswith("/certificates/") and method in ("GET", "PUT", "DELETE"):
return _handle_certificate(method, path, body, qp)
@@ -1507,6 +1510,18 @@ def _certificate_already_exists(cert_id: str, arn: str | None = None) -> tuple:
)
+def _registered_issuer_id(cert_pem: str) -> str | None:
+ """The id of the ACTIVE CA registered in this account/region that signed
+ ``cert_pem``, or None. Several CAs may share a subject, so the signature
+ decides, not the issuer name."""
+ for ca in _ca_certificates.values():
+ if ca.get("status") == "ACTIVE" and certificate_is_signed_by(
+ cert_pem, ca.get("certificatePem") or ""
+ ):
+ return ca["certificateId"]
+ return None
+
+
async def _register_certificate(
payload: dict, qp: dict, *, without_ca: bool = False
) -> tuple:
@@ -1522,7 +1537,10 @@ async def _register_certificate(
``caCertificatePem`` must name a CA registered via
``RegisterCACertificate`` in this account/region that really signed the
- leaf; anything else is a ``CertificateValidationException``. Registering
+ leaf; anything else is a ``CertificateValidationException``. Without it,
+ ``RegisterCertificate`` links the certificate to the registered ACTIVE CA
+ that signed it, as AWS does, so DescribeCertificate names that CA and
+ ListCertificatesByCA lists the certificate. Registering
publishes no JITR event, whatever the CA's ``autoRegistrationStatus``: AWS
sends that event only from a device connect (see ``_mtls_auto_register``),
and refuses a registration with status PENDING_ACTIVATION.
@@ -1585,6 +1603,8 @@ async def _register_certificate(
)
if cert_id in _certificates:
return _certificate_already_exists(cert_id)
+ if ca_id is None and not without_ca:
+ ca_id = _registered_issuer_id(cert_pem)
record = _certificate_record(
cert_id, cert_pem, status or ("ACTIVE" if set_active else "INACTIVE"), ca_id
)
@@ -1609,6 +1629,132 @@ def _list_certificates(qp: dict) -> tuple:
})
+_CERTIFICATE_ID_RE = re.compile(r"(0x)?[a-fA-F0-9]+")
+_MARKER_RE = re.compile(r"[A-Za-z0-9+/]+={0,2}")
+_BY_CA_MARKER_PREFIX = "certificates-by-ca"
+
+
+def _by_ca_sort_key(record: dict) -> tuple[float, str]:
+ """Creation order, the certificate id breaking ties within one timestamp."""
+ return record.get("creationDate") or 0.0, record["certificateId"]
+
+
+def _by_ca_marker(record: dict) -> str:
+ """An opaque page cursor naming the last certificate of a page.
+
+ It is the position, not an offset: AWS continues after that certificate in
+ whatever order the next request asks for, so a marker from a descending
+ page followed by ``isAscendingOrder=true`` yields the newer certificates.
+ Standard base64, so it matches the ``Marker`` pattern botocore checks.
+ """
+ created, cert_id = _by_ca_sort_key(record)
+ raw = f"{_BY_CA_MARKER_PREFIX}:{created!r}:{cert_id}"
+ return base64.b64encode(raw.encode()).decode()
+
+
+def _by_ca_marker_position(marker: str) -> tuple[float, str] | None:
+ """The (creationDate, certificateId) a marker stands for, or None."""
+ try:
+ raw = base64.b64decode(marker, validate=True).decode()
+ prefix, created, cert_id = raw.split(":")
+ if prefix != _BY_CA_MARKER_PREFIX:
+ return None
+ return float(created), cert_id
+ except ValueError:
+ return None
+
+
+def _list_certificates_by_ca(path: str, qp: dict) -> tuple:
+ """``GET /certificates-by-ca/{caCertificateId}`` (``ListCertificatesByCA``).
+
+ Lists the device certificates whose record names the CA: those registered
+ with that ``caCertificatePem``, in every status as on AWS, and those the
+ CA's auto-registration created. ``RegisterCertificateWithoutCA`` leaves
+ are not listed even when the CA issued them, as on AWS. Newest first unless
+ ``isAscendingOrder=true``. A well-formed id that names no CA is an empty
+ list, not an error.
+ """
+ ca_id = path[len("/certificates-by-ca/"):]
+ errors = []
+ if not _CERTIFICATE_ID_RE.fullmatch(ca_id):
+ errors.append(
+ "Value at 'caCertificateId' failed to satisfy constraint: Member must "
+ "satisfy regular expression pattern: (0x)?[a-fA-F0-9]+"
+ )
+ if len(ca_id) != 64:
+ bound = "greater than or equal to" if len(ca_id) < 64 else "less than or equal to"
+ errors.append(
+ "Value at 'caCertificateId' failed to satisfy constraint: Member must "
+ f"have length {bound} 64"
+ )
+ page_size = qp.get("pageSize")
+ if page_size is not None:
+ try:
+ page_size = int(page_size)
+ except ValueError:
+ return error_response_json(
+ "InvalidRequestException", "pageSize must be an integer", 400
+ )
+ if page_size < 1:
+ errors.append(
+ "Value at 'pageSize' failed to satisfy constraint: Member must have "
+ "value greater than or equal to 1"
+ )
+ elif page_size > 250:
+ errors.append(
+ "Value at 'pageSize' failed to satisfy constraint: Member must have "
+ "value less than or equal to 250"
+ )
+ marker = qp.get("marker")
+ if marker is not None and not _MARKER_RE.fullmatch(marker):
+ errors.append(
+ "Value at 'marker' failed to satisfy constraint: Member must satisfy "
+ "regular expression pattern: [A-Za-z0-9+/]+={0,2}"
+ )
+ if errors:
+ noun = "error" if len(errors) == 1 else "errors"
+ return error_response_json(
+ "InvalidRequestException",
+ f"{len(errors)} validation {noun} detected: " + "; ".join(errors),
+ 400,
+ )
+ position = None
+ if marker is not None:
+ position = _by_ca_marker_position(marker)
+ if position is None:
+ return error_response_json(
+ "InvalidRequestException",
+ "Invalid/Malformed marker passed for listCertificateByCA",
+ 400,
+ )
+ ascending = _qp_bool(qp, "isAscendingOrder")
+ matched = sorted(
+ (c for c in _certificates.values() if c.get("caCertificateId") == ca_id),
+ key=_by_ca_sort_key,
+ reverse=not ascending,
+ )
+ if position is not None:
+ matched = [
+ c for c in matched
+ if (_by_ca_sort_key(c) > position if ascending else _by_ca_sort_key(c) < position)
+ ]
+ page = matched[:page_size or 250]
+ body = {
+ "certificates": [
+ {
+ "certificateArn": c["certificateArn"],
+ "certificateId": c["certificateId"],
+ "status": c["status"],
+ "creationDate": c.get("creationDate"),
+ }
+ for c in page
+ ]
+ }
+ if len(matched) > len(page):
+ body["nextMarker"] = _by_ca_marker(page[-1])
+ return json_response(body)
+
+
def _handle_certificate(method: str, path: str, body: bytes, qp: dict) -> tuple:
cert_id = path[len("/certificates/"):]
if not cert_id or "/" in cert_id:
diff --git a/tests/conftest.py b/tests/conftest.py
index 1a69eb00..3d0329cf 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -320,6 +320,7 @@ _SERIAL_TESTS = {
"tests/test_iot_data.py::test_mtls_ambiguous_cert_is_refused",
"tests/test_iot_data.py::test_mtls_registered_cert_connects_whatever_its_ca",
"tests/test_iot_data.py::test_mtls_registered_ca_chain_connects",
+ "tests/test_iot_data.py::test_mtls_jitr_certificate_is_listed_by_its_ca",
"tests/test_iot_data.py::test_mtls_jitr_auto_registers_an_unknown_cert_without_connack",
"tests/test_iot_data.py::test_mtls_account_scoped_delivery",
"tests/test_iot_data.py::test_mtls_garbage_bytes_dropped",
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index dddd60db..2805b35d 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -1228,6 +1228,46 @@ def test_cfn_iot_ca_certificate_lifecycle(cfn, iot_client):
assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
+def test_cfn_iot_ca_certificate_lists_certificates_registered_under_it(cfn, iot_client):
+ """A CA the stack registered is the same registry entry the API uses:
+ device certificates registered under it by RegisterCertificate come back
+ from ListCertificatesByCA for the stack's CA id, newest first."""
+ pytest.importorskip("cryptography")
+ from ministack.core.x509_utils import generate_ca, sign_leaf_certificate
+
+ suffix = _uuid_mod.uuid4().hex[:8]
+ name = f"cfn-iot-ca-by-ca-{suffix}"
+ ca_pem, ca_key = generate_ca(common_name=f"cfn-by-ca-{suffix}")
+ template = json.dumps({
+ "Resources": {"CA": {"Type": "AWS::IoT::CACertificate", "Properties": {
+ "CACertificatePem": ca_pem, "Status": "ACTIVE", "CertificateMode": "SNI_ONLY",
+ }}},
+ "Outputs": {"CaId": {"Value": {"Fn::GetAtt": ["CA", "Id"]}}},
+ })
+ cfn.create_stack(StackName=name, TemplateBody=template)
+ cert_ids = []
+ try:
+ stack = _wait_stack(cfn, name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ ca_id = stack["Outputs"][0]["OutputValue"]
+ for i in range(2):
+ leaf_pem = sign_leaf_certificate(
+ ca_cert_pem=ca_pem, ca_key_pem=ca_key, common_name=f"cfn-by-ca-device-{i}"
+ )[0]
+ cert_ids.append(iot_client.register_certificate(
+ certificatePem=leaf_pem, caCertificatePem=ca_pem, status="ACTIVE",
+ )["certificateId"])
+
+ listing = iot_client.list_certificates_by_ca(caCertificateId=ca_id)["certificates"]
+ assert [c["certificateId"] for c in listing] == cert_ids[::-1]
+ finally:
+ for cert_id in cert_ids:
+ iot_client.update_certificate(certificateId=cert_id, newStatus="INACTIVE")
+ iot_client.delete_certificate(certificateId=cert_id)
+ cfn.delete_stack(StackName=name)
+ _wait_stack(cfn, name)
+
+
def test_cfn_iot_ca_certificate_existing_registration_fails_the_stack(cfn, iot_client):
"""A CA already registered out of band answers ResourceAlreadyExists when
the stack's create re-registers the PEM (the certificate id is derived
diff --git a/tests/test_iot.py b/tests/test_iot.py
index f97eabb5..89f0966e 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -6369,6 +6369,41 @@ def test_iot_register_certificate_under_ca_links_ca_certificate_id(iot_client):
iot_client.delete_ca_certificate(certificateId=ca_id)
+def test_iot_register_certificate_without_ca_pem_links_the_signing_ca(iot_client):
+ """Without ``caCertificatePem``, AWS links the certificate to the
+ registered ACTIVE CA that signed it: DescribeCertificate names that CA and
+ ListCertificatesByCA lists it. Two CAs share a subject here, so only the
+ signature tells them apart."""
+ pytest.importorskip("cryptography")
+ from ministack.core.x509_utils import generate_ca, sign_leaf_certificate
+
+ subject = _unique("twin-ca")
+ twins = [generate_ca(common_name=subject) for _ in range(2)]
+ ca_ids, cert_ids = [], []
+ try:
+ for ca_pem, _key in twins:
+ ca_ids.append(iot_client.register_ca_certificate(
+ caCertificate=ca_pem, certificateMode="SNI_ONLY", setAsActive=True,
+ )["certificateId"])
+ for ca_pem, ca_key in reversed(twins):
+ leaf_pem = sign_leaf_certificate(
+ ca_cert_pem=ca_pem, ca_key_pem=ca_key, common_name=_unique("twin-device")
+ )[0]
+ cert_ids.insert(0, iot_client.register_certificate(
+ certificatePem=leaf_pem, status="ACTIVE"
+ )["certificateId"])
+
+ for ca_id, cert_id in zip(ca_ids, cert_ids):
+ desc = iot_client.describe_certificate(certificateId=cert_id)[
+ "certificateDescription"
+ ]
+ assert desc["caCertificateId"] == ca_id
+ listing = iot_client.list_certificates_by_ca(caCertificateId=ca_id)
+ assert [c["certificateId"] for c in listing["certificates"]] == [cert_id]
+ finally:
+ _delete_certificates_and_cas(iot_client, cert_ids, ca_ids)
+
+
def test_iot_register_certificate_rejects_an_unregistered_ca(iot_client):
"""``caCertificatePem`` naming a CA that was never registered is a
``CertificateValidationException``, and nothing is stored — otherwise the
@@ -6433,6 +6468,167 @@ def test_iot_register_certificate_rejects_a_leaf_from_another_ca(iot_client):
iot_client.delete_ca_certificate(certificateId=ca_id)
+def _delete_certificates_and_cas(iot_client, cert_ids, ca_ids):
+ for cert_id in cert_ids:
+ iot_client.update_certificate(certificateId=cert_id, newStatus="INACTIVE")
+ iot_client.delete_certificate(certificateId=cert_id)
+ for ca_id in ca_ids:
+ iot_client.update_ca_certificate(certificateId=ca_id, newStatus="INACTIVE")
+ iot_client.delete_ca_certificate(certificateId=ca_id)
+
+
+def test_iot_list_certificates_by_ca_lists_what_was_registered_under_the_ca(iot_client):
+ """As measured on AWS: every certificate registered with the CA's
+ ``caCertificatePem`` is listed whatever its status, newest first unless
+ ``isAscendingOrder=true``, with the four ``ListCertificates`` members. A
+ leaf the CA issued but registered through RegisterCertificateWithoutCA is
+ not listed, nor is a leaf of another CA."""
+ code = _registration_code(iot_client)
+ ca_pem, verification_pem, leaves = _generate_ca_and_leaves(code, count=4)
+ other_ca_pem, other_verification_pem, other_leaf = _generate_ca_and_leaf(code)
+ ca_id = iot_client.register_ca_certificate(
+ caCertificate=ca_pem, verificationCertificate=verification_pem, setAsActive=True,
+ )["certificateId"]
+ other_ca_id = iot_client.register_ca_certificate(
+ caCertificate=other_ca_pem, verificationCertificate=other_verification_pem,
+ setAsActive=True,
+ )["certificateId"]
+ created = []
+ try:
+ for leaf_pem, status in zip(leaves[:3], ("ACTIVE", "INACTIVE", "REVOKED")):
+ created.append(iot_client.register_certificate(
+ certificatePem=leaf_pem, caCertificatePem=ca_pem, status=status,
+ )["certificateId"])
+ under_ca = list(created)
+ created.append(iot_client.register_certificate_without_ca(
+ certificatePem=leaves[3], status="ACTIVE",
+ )["certificateId"])
+ other = iot_client.register_certificate(
+ certificatePem=other_leaf, caCertificatePem=other_ca_pem, status="ACTIVE",
+ )["certificateId"]
+ created.append(other)
+
+ listing = iot_client.list_certificates_by_ca(caCertificateId=ca_id)
+ assert "nextMarker" not in listing
+ certificates = listing["certificates"]
+ assert [c["certificateId"] for c in certificates] == under_ca[::-1]
+ assert [c["status"] for c in certificates] == ["REVOKED", "INACTIVE", "ACTIVE"]
+ for c in certificates:
+ assert set(c) == {"certificateArn", "certificateId", "status", "creationDate"}
+ assert c["certificateArn"].endswith(":cert/" + c["certificateId"])
+
+ ascending = iot_client.list_certificates_by_ca(
+ caCertificateId=ca_id, ascendingOrder=True
+ )["certificates"]
+ assert [c["certificateId"] for c in ascending] == under_ca
+
+ other_listing = iot_client.list_certificates_by_ca(caCertificateId=other_ca_id)
+ assert [c["certificateId"] for c in other_listing["certificates"]] == [other]
+ finally:
+ _delete_certificates_and_cas(iot_client, created, (ca_id, other_ca_id))
+
+
+def test_iot_list_certificates_by_ca_pages_from_the_last_certificate(iot_client):
+ """``pageSize`` pages carry a ``nextMarker`` until the last one. The marker
+ names a position, the way AWS's does: continuing a descending page with
+ ``isAscendingOrder=true`` yields the certificates newer than that page's
+ last one. A CA without certificates, an id that names no CA and the
+ upper-case form of a CA id all answer an empty list."""
+ ca_pem, verification_pem, leaves = _generate_ca_and_leaves(
+ _registration_code(iot_client), count=3
+ )
+ ca_id = iot_client.register_ca_certificate(
+ caCertificate=ca_pem, verificationCertificate=verification_pem, setAsActive=True,
+ )["certificateId"]
+ created = []
+ try:
+ assert iot_client.list_certificates_by_ca(caCertificateId=ca_id)["certificates"] == []
+ for leaf_pem in leaves:
+ created.append(iot_client.register_certificate(
+ certificatePem=leaf_pem, caCertificatePem=ca_pem, status="ACTIVE",
+ )["certificateId"])
+
+ seen, marker = [], None
+ for _ in range(len(created)):
+ kwargs = {"marker": marker} if marker else {}
+ page = iot_client.list_certificates_by_ca(caCertificateId=ca_id, pageSize=1, **kwargs)
+ assert len(page["certificates"]) == 1
+ seen.append(page["certificates"][0]["certificateId"])
+ marker = page.get("nextMarker")
+ if marker:
+ assert re.fullmatch(r"[A-Za-z0-9+/]+={0,2}", marker)
+ assert marker is None
+ assert seen == created[::-1]
+
+ paginator = iot_client.get_paginator("list_certificates_by_ca")
+ pages = paginator.paginate(
+ caCertificateId=ca_id, ascendingOrder=True, PaginationConfig={"PageSize": 2}
+ )
+ assert [c["certificateId"] for p in pages for c in p["certificates"]] == created
+
+ first = iot_client.list_certificates_by_ca(caCertificateId=ca_id, pageSize=2)
+ flipped = iot_client.list_certificates_by_ca(
+ caCertificateId=ca_id, pageSize=2, marker=first["nextMarker"], ascendingOrder=True
+ )
+ assert [c["certificateId"] for c in flipped["certificates"]] == [created[2]]
+
+ for unknown in ("0" * 64, ca_id.upper()):
+ assert iot_client.list_certificates_by_ca(caCertificateId=unknown)["certificates"] == []
+ finally:
+ _delete_certificates_and_cas(iot_client, created, (ca_id,))
+
+
+ ("kwargs", "message"),
+ [
+ (
+ {"pageSize": 0},
+ "1 validation error detected: Value at 'pageSize' failed to satisfy "
+ "constraint: Member must have value greater than or equal to 1",
+ ),
+ (
+ {"pageSize": 251},
+ "1 validation error detected: Value at 'pageSize' failed to satisfy "
+ "constraint: Member must have value less than or equal to 250",
+ ),
+ (
+ {"caCertificateId": "not-a-ca-id"},
+ "2 validation errors detected: Value at 'caCertificateId' failed to "
+ "satisfy constraint: Member must satisfy regular expression pattern: "
+ "(0x)?[a-fA-F0-9]+; Value at 'caCertificateId' failed to satisfy "
+ "constraint: Member must have length greater than or equal to 64",
+ ),
+ (
+ {"caCertificateId": "a" * 63},
+ "1 validation error detected: Value at 'caCertificateId' failed to "
+ "satisfy constraint: Member must have length greater than or equal to 64",
+ ),
+ (
+ {"marker": "not-a-marker!"},
+ "1 validation error detected: Value at 'marker' failed to satisfy "
+ "constraint: Member must satisfy regular expression pattern: "
+ "[A-Za-z0-9+/]+={0,2}",
+ ),
+ (
+ {"marker": "bm90LWEtbWFya2Vy"},
+ "Invalid/Malformed marker passed for listCertificateByCA",
+ ),
+ ],
+ ids=["page-size-0", "page-size-251", "malformed-id", "short-id", "marker-pattern", "unissued-marker"],
+)
+def test_iot_list_certificates_by_ca_rejects_what_aws_rejects(kwargs, message):
+ """The messages AWS answers once the SDK's own validation is out of the
+ way; the base64 marker is well formed but was never issued."""
+ from conftest import make_client
+
+ raw = make_client("iot", {"parameter_validation": False})
+ with pytest.raises(ClientError) as ei:
+ raw.list_certificates_by_ca(**{"caCertificateId": "0" * 64, **kwargs})
+ assert ei.value.response["Error"]["Code"] == "InvalidRequestException"
+ assert ei.value.response["Error"]["Message"] == message
+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+
+
def test_iot_update_ca_certificate_applies_a_body_only_status(iot_client):
"""newStatus / newAutoRegistrationStatus are modeled in the query string,
but a raw caller that sends them in the JSON body must not get a 200 that
diff --git a/tests/test_iot_data.py b/tests/test_iot_data.py
index 91affb70..30241341 100644
--- a/tests/test_iot_data.py
+++ b/tests/test_iot_data.py
@@ -3609,6 +3609,37 @@ def test_mtls_registered_ca_chain_connects(broker, tmp_path):
peer.close()
+def test_mtls_jitr_certificate_is_listed_by_its_ca(broker, tmp_path):
+ """As measured on AWS, ListCertificatesByCA lists the certificate that
+ just-in-time registration created, while it is still PENDING_ACTIVATION."""
+ from ministack.core.x509_utils import get_certificate_id, sign_leaf_certificate
+
+ iot = broker.client("iot")
+ ca_pem, ca_key, verification_pem = iot_test_ca(
+ iot.get_registration_code()["registrationCode"], _unique("jitr-list-ca")
+ )
+ ca_id = iot.register_ca_certificate(
+ caCertificate=ca_pem, verificationCertificate=verification_pem,
+ setAsActive=True, allowAutoRegistration=True,
+ )["certificateId"]
+ leaf_pem, leaf_key, _public = sign_leaf_certificate(ca_pem, ca_key, common_name="jitr-listed")
+ cert_id = get_certificate_id(leaf_pem)
+ try:
+ assert _refused_below_mqtt(broker, leaf_pem, leaf_key, tmp_path, _unique("jitr-listed"))
+ listing = iot.list_certificates_by_ca(caCertificateId=ca_id)["certificates"]
+ assert [(c["certificateId"], c["status"]) for c in listing] == [
+ (cert_id, "PENDING_ACTIVATION")
+ ]
+ finally:
+ try:
+ iot.update_certificate(certificateId=cert_id, newStatus="INACTIVE")
+ iot.delete_certificate(certificateId=cert_id, forceDelete=True)
+ except ClientError:
+ pass
+ iot.update_ca_certificate(certificateId=ca_id, newStatus="INACTIVE")
+ iot.delete_ca_certificate(certificateId=ca_id)
+
+
def test_mtls_jitr_auto_registers_an_unknown_cert_without_connack(broker, tmp_path):
"""Just-in-time registration, as on AWS: an unknown certificate signed by a
CA with auto-registration enabled is created PENDING_ACTIVATION, the