Light, fluffy, and always free - The AWS Local Emulator alternative
fix(acm): reject empty SAN arrays in certificate requests (#5688)
Jackson Pricee15c081d3379
diff --git a/compatibility-tests/sdk-test-python/tests/test_acm.py b/compatibility-tests/sdk-test-python/tests/test_acm.pyindex 6d78e47ea4..18c9ad4afc 100644--- a/compatibility-tests/sdk-test-python/tests/test_acm.py+++ b/compatibility-tests/sdk-test-python/tests/test_acm.py@@ -1,8 +1,13 @@"""ACM integration tests."""+import jsonimport re+import uuid+from contextlib import closing+import boto3import pytest+from botocore.config import Configfrom botocore.exceptions import ClientErrorfrom cryptography import x509from cryptography.hazmat.primitives import serialization@@ -14,6 +19,55 @@ FAKE_ARN = "arn:aws:acm:us-east-1:000000000000:certificate/00000000-0000-0000-00class TestACMCertificateLifecycle:"""Test ACM certificate lifecycle operations."""+ def test_request_certificate_rejects_empty_sans(self, aws_config, client_config):+ """Disable SDK validation so the empty list reaches the server."""+ with closing(boto3.client(+ "acm",+ config=client_config.merge(Config(parameter_validation=False)),+ **aws_config,+ )) as client:+ with pytest.raises(ClientError) as error:+ response = client.request_certificate(+ DomainName="empty-sans.example.com", SubjectAlternativeNames=[]+ )+ client.delete_certificate(CertificateArn=response["CertificateArn"])+ assert error.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+ assert error.value.response["Error"]["Code"] == "ValidationException"++ @pytest.mark.parametrize("sans", [None, [], ["alt.san-probe.example.com"]])+ def test_cloudformation_certificate_sans(+ self, cloudformation_client, acm_client, sans+ ):+ stack = f"acm-sans-{uuid.uuid4().hex[:12]}"+ properties = {+ "DomainName": "san-probe.example.com",+ "ValidationMethod": "DNS",+ }+ if sans is not None:+ properties["SubjectAlternativeNames"] = sans+ template = {"Resources": {"Certificate": {+ "Type": "AWS::CertificateManager::Certificate",+ "Properties": properties,+ }}}+ cloudformation_client.create_stack(+ StackName=stack, TemplateBody=json.dumps(template)+ )+ try:+ cloudformation_client.get_waiter("stack_create_complete").wait(+ StackName=stack, WaiterConfig={"Delay": 1, "MaxAttempts": 60}+ )+ resource = cloudformation_client.describe_stack_resource(+ StackName=stack, LogicalResourceId="Certificate"+ )["StackResourceDetail"]+ certificate = acm_client.describe_certificate(+ CertificateArn=resource["PhysicalResourceId"]+ )["Certificate"]+ assert set(certificate["SubjectAlternativeNames"]) == {+ properties["DomainName"], *(sans or [])+ }+ finally:+ cloudformation_client.delete_stack(StackName=stack)+def test_request_certificate(self, acm_client):"""Test RequestCertificate creates a certificate and returns a valid ARN."""response = acm_client.request_certificate(DomainName="test.example.com")diff --git a/docs/services/acm.md b/docs/services/acm.mdindex 0d92f7ca89..b9f1275637 100644--- a/docs/services/acm.md+++ b/docs/services/acm.md@@ -34,6 +34,7 @@- **One Local CA:** Every issued certificate (`AMAZON_ISSUED` and `PRIVATE`) is signed by Floci's local root CA, and `GetCertificate` returns that CA as `CertificateChain`. Trust it once (`GET /_floci/ca.pem`, see [TLS](../configuration/tls.md)) and both Floci's HTTPS endpoint and every ACM certificate validate. `DescribeCertificate` reports `Issuer` as the CA's name, `CN=Floci Local CA`, where AWS reports `Amazon`. `ImportCertificate` keeps the chain you upload.- **CA on First Use:** The CA is created under `{persistent-path}/tls/` the first time a certificate is issued, also with TLS off and in `memory` storage mode, so that directory must be writable. A certificate keeps the chain it was issued with; after a CA regeneration, delete and re-request it.- **Key Algorithms:** `RequestCertificate` accepts `RSA_2048`, `EC_prime256v1`, and `EC_secp384r1` and rejects the rest with a `ValidationException`, matching real ACM; the wider list (`RSA_1024`, `RSA_3072`, `RSA_4096`, `EC_secp521r1`) remains valid for `ImportCertificate`+- **Alternative names:** `RequestCertificate` rejects an explicit empty `SubjectAlternativeNames` array with `ValidationException`, since the API requires at least one name in it; omit the field when there are no additional names. An `AWS::CertificateManager::Certificate` resource still accepts an empty array and requests the certificate for `DomainName` alone, but the CloudFormation template reference also lists a one-item minimum, so omit the property in templates that also deploy to AWS.- **Certificate Types:** `AMAZON_ISSUED` (default) and `PRIVATE` (when `CertificateAuthorityArn` is provided)- **Export:** Only `PRIVATE` type certificates can be exported with their private key- **In use:** `DescribeCertificate` lists under `InUseBy` the CloudFront distribution of each Cognito custom domain that uses the certificate, and `DeleteCertificate` refuses with `ResourceInUseException` while that list is not empty. Other consumers, such as load balancers and API Gateway domain names, are not tracked yet.diff --git a/src/main/java/io/github/hectorvent/floci/services/acm/AcmJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/acm/AcmJsonHandler.javaindex 8008ef7a03..119a743752 100644--- a/src/main/java/io/github/hectorvent/floci/services/acm/AcmJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/acm/AcmJsonHandler.java@@ -100,7 +100,13 @@ public class AcmJsonHandler {"Value null at 'domainName' failed to satisfy constraint: Member must not be null")).build();}- List<String> sans = parseStringList(request.path("SubjectAlternativeNames"));+ JsonNode sanNode = request.path("SubjectAlternativeNames");+ if (sanNode.isArray() && sanNode.isEmpty()) {+ throw new AwsException("ValidationException",+ "1 validation error detected: Value '[]' at 'subjectAlternativeNames' failed to satisfy "+ + "constraint: Member must have length greater than or equal to 1", 400);+ }+ List<String> sans = parseStringList(sanNode);ValidationMethod validationMethod = parseValidationMethod(request.path("ValidationMethod").asText(null));String idempotencyToken = request.path("IdempotencyToken").asText(null);KeyAlgorithm keyAlgorithm = KeyAlgorithm.fromAwsName(request.path("KeyAlgorithm").asText(null));diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/AcmIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/AcmIntegrationTest.javaindex d00a2bcde2..6caf9f9c66 100644--- a/src/test/java/io/github/hectorvent/floci/services/acm/AcmIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/acm/AcmIntegrationTest.java@@ -42,6 +42,22 @@ class AcmIntegrationTest {// ==================== User Story 1: RequestCertificate ====================+ @Test+ void requestCertificateRejectsEmptySans() {+ given()+ .header("X-Amz-Target", "CertificateManager.RequestCertificate")+ .contentType(ACM_CONTENT_TYPE)+ .body("""+ {"DomainName": "empty-sans.example.com", "SubjectAlternativeNames": []}+ """)+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("1 validation error detected: Value '[]' at 'subjectAlternativeNames' "+ + "failed to satisfy constraint: Member must have length greater than or equal to 1"));+ }+@Test@Order(1)void requestCertificateBasic() {diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/AcmCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/AcmCfnIntegrationTest.javaindex 4ab9c34460..64cacfa9ea 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/AcmCfnIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/AcmCfnIntegrationTest.java@@ -8,6 +8,7 @@ import io.restassured.specification.RequestSpecification;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;+import java.util.List;import java.util.Map;import static io.restassured.RestAssured.given;@@ -114,6 +115,34 @@ class AcmCfnIntegrationTest {.body("__type", equalTo("ResourceNotFoundException"));}+ @Test+ void certificateStackAcceptsEmptySans() {+ String stack = "acm-empty-sans";+ String template = """+ {+ "Resources": {"Cert": {+ "Type": "AWS::CertificateManager::Certificate",+ "Properties": {+ "DomainName": "empty-sans.example.com",+ "SubjectAlternativeNames": [],+ "ValidationMethod": "DNS"+ }+ }},+ "Outputs": {"CertArn": {"Value": {"Ref": "Cert"}}}+ }+ """;+ cloudFormation(stack, "CreateStack", template, Map.of());+ try {+ String arn = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "CertArn");+ describeCertificate(arn).then()+ .statusCode(200)+ .body("Certificate.SubjectAlternativeNames", equalTo(List.of("empty-sans.example.com")));+ } finally {+ cloudFormation(stack, "DeleteStack", null, Map.of());+ CfnStackWaits.awaitStackDeleted(stack);+ }+ }+@Testvoid certificateOptionsFollowTheTemplateThroughCreateAndUpdate() {cloudFormation(OPTIONS_STACK, "CreateStack", OPTIONS_TEMPLATE, options("ENABLED", "DISABLED"));