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
fix(acm): refuse key-less imports and deletes of certificates in use (#2194)
iot-rocket56b586a063d3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2a7d3f28..1bf583cd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **ACM / Signer — certificate key and in-use refusals** — `ImportCertificate` accepted a call without a `PrivateKey` and now answers AWS's `ValidationException`; `DeleteCertificate` removed a certificate an Active Signer signing profile uses and now answers `ResourceInUseException`, with those profiles listed in `DescribeCertificate`'s `InUseBy`; `CancelSigningProfile` answered 200 with `{}` and now answers 204 with an empty body, as on AWS. Contributed by @iot-rocket.- **IoT — not-found messages match AWS** — a call naming a thing, thing type, thing group, certificate, CA certificate, principal, policy, policy version, job, job execution, job target or provisioning template that does not exist answered `ResourceNotFoundException` with a generic `<Resource> '<name>' not found`, and the device jobs plane (HTTP and MQTT `/rejected`) with `No job execution found for thing … and job …`; each now carries the wording AWS uses for that operation, with the same error code and status. Contributed by @iot-rocket.- **IoT Jobs — terminal job executions on the device plane** — a device's `DescribeJobExecution` (HTTP and the MQTT `get` topic) of a SUCCEEDED, FAILED, REJECTED, TIMED_OUT, CANCELED or REMOVED execution answered with the execution; it now answers `TerminalStateException` (410) and `TerminalStateReached` over MQTT, as AWS does. `UpdateJobExecution` and `CancelJobExecution` of a terminal execution now refuse with AWS's messages (over MQTT `InvalidStateTransition` with the `executionState`), a refused status such as QUEUED is checked first, and a device that reports SUCCEEDED or FAILED straight from QUEUED now stamps `startedAt`. Contributed by @iot-rocket.- **IoT / CloudFormation — stack tags and provisioning templates** — stack-level tags never reached IoT resources; they now reach thing types, thing groups, policies, topic rules, CA certificates and provisioning templates without the `aws:cloudformation:` tags (job templates get none, as on AWS), and an update that only changes tags no longer adds a policy version. An `AWS::IoT::ProvisioningTemplate` `Enabled` of `"false"` from a parameter or the template enabled the template; it now disables it. `CreateProvisioningTemplate` and the CloudFormation type accepted any certificate resource; they now refuse one without a `Status` of `Active` or `Inactive` (any case) or whose `CertificateId` is not a reference to `AWS::IoT::Certificate::Id`, a second certificate resource and a resource without `Properties`, with AWS's messages. Contributed by @iot-rocket.diff --git a/ministack/services/acm.py b/ministack/services/acm.pyindex b415aa5f..3ab5d8ca 100644--- a/ministack/services/acm.py+++ b/ministack/services/acm.py@@ -208,7 +208,7 @@ def _cert_shape(cert):"Type": cert.get("Type", "AMAZON_ISSUED"),"KeyAlgorithm": "RSA_2048","SignatureAlgorithm": "SHA256WITHRSA",- "InUseBy": cert.get("InUseBy", []),+ "InUseBy": cert.get("InUseBy", []) + _signing_profiles_using(cert["CertificateArn"]),"CreatedAt": _epoch(cert["CreatedAt"]),"IssuedAt": _epoch(cert.get("IssuedAt", cert["CreatedAt"])),"NotBefore": _epoch(cert.get("NotBefore", cert["CreatedAt"])),@@ -311,10 +311,22 @@ def _list_certificates(data):return json_response({"CertificateSummaryList": summaries})+def _signing_profiles_using(arn):+ """ARNs of the Active Signer signing profiles whose signing material is this certificate."""+ from ministack.services import signer++ return [profile["arn"] for profile in signer._profiles.values()+ if profile.get("status") == "Active"+ and (profile.get("signingMaterial") or {}).get("certificateArn") == arn]++def _delete_certificate(data):arn = data.get("CertificateArn", "")if _get_local_certificate(arn) is None:return _certificate_not_found(arn)+ if _signing_profiles_using(arn):+ return error_response_json(+ "ResourceInUseException", f"Certificate {arn} in account {get_account_id()} is in use.", 400)del _certificates[arn]return json_response({})@@ -356,6 +368,12 @@ def _get_certificate(data):def _import_certificate(data):+ if not data.get("PrivateKey"):+ constraint = ("Member must not be null" if data.get("PrivateKey") is None+ else "Member must have length greater than or equal to 1")+ return error_response_json(+ "ValidationException",+ f"1 validation error detected: Value at 'privateKey' failed to satisfy constraint: {constraint}", 400)arn = data.get("CertificateArn") or _cert_arn()if data.get("CertificateArn") and not _is_local_certificate_arn(arn):return _certificate_not_found(arn)diff --git a/ministack/services/signer.py b/ministack/services/signer.pyindex 470d17f7..6ee64786 100644--- a/ministack/services/signer.py+++ b/ministack/services/signer.py@@ -1072,7 +1072,7 @@ def _cancel_signing_profile(name):if profile.get("status") == "Active" and profile.get("policy"):profile["policy"] = dict(profile["policy"], revisionId=str(uuid.uuid4()))profile["status"] = "Canceled"- return json_response({})+ return 204, {"Content-Type": REST_JSON_CONTENT_TYPE}, b""# ---------------------------------------------------------------------------diff --git a/tests/test_acm.py b/tests/test_acm.pyindex 1a19319c..188b82ad 100644--- a/tests/test_acm.py+++ b/tests/test_acm.py@@ -2,6 +2,8 @@ import jsonimport osimport pytest+from botocore.exceptions import ClientError+from conftest import make_clientdef test_acm_request_certificate(acm_client):@@ -78,6 +80,24 @@ def test_acm_import_certificate(acm_client):desc = acm_client.describe_certificate(CertificateArn=arn)assert desc["Certificate"]["Type"] == "IMPORTED"+def test_acm_import_certificate_requires_a_private_key(acm_client):+ raw = make_client("acm", {"parameter_validation": False})+ fake_cert = b"-----BEGIN CERTIFICATE-----\nfake\n-----END CERTIFICATE-----"+ fake_key = b"-----BEGIN RSA PRIVATE KEY-----\nfake\n-----END RSA PRIVATE KEY-----"+ arn = acm_client.import_certificate(Certificate=fake_cert, PrivateKey=fake_key)["CertificateArn"]+ for args, constraint in (+ ({}, "Member must not be null"),+ ({"PrivateKey": b""}, "Member must have length greater than or equal to 1"),+ ({"CertificateArn": arn}, "Member must not be null"),+ ):+ with pytest.raises(ClientError) as exc:+ raw.import_certificate(Certificate=fake_cert, **args)+ assert exc.value.response["Error"] == {+ "Code": "ValidationException",+ "Message": f"1 validation error detected: Value at 'privateKey' failed to satisfy constraint: {constraint}",+ }+ acm_client.delete_certificate(CertificateArn=arn)+def test_acm_delete_certificate(acm_client):arn = acm_client.request_certificate(DomainName="delete.example.com")["CertificateArn"]acm_client.delete_certificate(CertificateArn=arn)@@ -85,6 +105,36 @@ def test_acm_delete_certificate(acm_client):arns = [c["CertificateArn"] for c in resp["CertificateSummaryList"]]assert arn not in arns+def test_acm_delete_certificate_refused_while_an_active_signing_profile_uses_it(acm_client, signer):+ fake_cert = b"-----BEGIN CERTIFICATE-----\nfake\n-----END CERTIFICATE-----"+ fake_key = b"-----BEGIN RSA PRIVATE KEY-----\nfake\n-----END RSA PRIVATE KEY-----"+ arn = acm_client.import_certificate(Certificate=fake_cert, PrivateKey=fake_key)["CertificateArn"]+ account = arn.split(":")[4]+ assert acm_client.describe_certificate(CertificateArn=arn)["Certificate"]["InUseBy"] == []+ suffix = os.urandom(4).hex()+ profiles = [+ signer.put_signing_profile(+ profileName=f"acm_in_use_{tag}_{suffix}",+ platformId="AWSIoTDeviceManagement-SHA256-ECDSA",+ signingMaterial={"certificateArn": arn},+ )["arn"]+ for tag in ("first", "second")+ ]+ signer.put_signing_profile(profileName=f"acm_in_use_lambda_{suffix}", platformId="AWSLambda-SHA384-ECDSA")++ for in_use in (profiles, profiles[1:]):+ assert acm_client.describe_certificate(CertificateArn=arn)["Certificate"]["InUseBy"] == in_use+ with pytest.raises(ClientError) as exc:+ acm_client.delete_certificate(CertificateArn=arn)+ assert exc.value.response["Error"] == {+ "Code": "ResourceInUseException",+ "Message": f"Certificate {arn} in account {account} is in use.",+ }+ signer.cancel_signing_profile(profileName=in_use[0].rsplit("/", 1)[-1])++ assert acm_client.describe_certificate(CertificateArn=arn)["Certificate"]["InUseBy"] == []+ acm_client.delete_certificate(CertificateArn=arn)+def test_acm_update_certificate_options(acm_client):arn = acm_client.request_certificate(DomainName="options.example.com")["CertificateArn"]acm_client.update_certificate_options(diff --git a/tests/test_signer.py b/tests/test_signer.pyindex 2ed01f7a..ab67b1ad 100644--- a/tests/test_signer.py+++ b/tests/test_signer.py@@ -1169,6 +1169,14 @@ def test_signer_cancel_profile_keeps_the_name_and_freezes_permissions(signer):f"Signing Profile with name {ghost} does not exist.")+def test_signer_cancel_profile_answers_204_with_an_empty_body(signer):+ name, _put, _account = _permissions_profile(signer)+ meta = signer.cancel_signing_profile(profileName=name)["ResponseMetadata"]+ assert meta["HTTPStatusCode"] == 204+ assert meta["HTTPHeaders"]["content-type"] == "application/json"+ assert meta["HTTPHeaders"].get("content-length", "0") == "0"++@pytest.mark.parametrize("name", ["fw-profile", "p" * 65])def test_signer_profile_name_outside_documented_pattern_is_refused(signer, s3, buckets, name