Skip to content

Commit d0cf348

Browse files
authored
ACM: support certs without CN (#9912)
1 parent cbd409a commit d0cf348

2 files changed

Lines changed: 80 additions & 23 deletions

File tree

‎moto/acm/models.py‎

Lines changed: 26 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -158,9 +158,29 @@ def __init__(
158158
self._cert = self.validate_certificate()
159159
# Extracting some common fields for ease of use
160160
# Have to search through cert.subject for OIDs
161-
self.common_name: Any = self._cert.subject.get_attributes_for_oid(
162-
OID_COMMON_NAME
163-
)[0].value
161+
162+
# Parse SANs once here so they can be reused in describe() without re-parsing
163+
try:
164+
san_obj: Any = self._cert.extensions.get_extension_for_oid(
165+
cryptography.x509.OID_SUBJECT_ALTERNATIVE_NAME
166+
)
167+
self.sans: list[str] = [str(item.value) for item in san_obj.value]
168+
except cryptography.x509.ExtensionNotFound:
169+
self.sans = []
170+
171+
# CN is optional per CAB Forum baseline requirements; fall back to first SAN
172+
# (matching real AWS ACM DomainName behaviour) or empty string if no SANs either
173+
cn_attrs = self._cert.subject.get_attributes_for_oid(OID_COMMON_NAME)
174+
self.common_name: Any = (
175+
cn_attrs[0].value if cn_attrs else (self.sans[0] if self.sans else "")
176+
)
177+
178+
# Parse issuer CN, also optional
179+
issuer_cn_attrs = self._cert.issuer.get_attributes_for_oid(OID_COMMON_NAME)
180+
self.issuer_common_name: str = str(
181+
issuer_cn_attrs[0].value if issuer_cn_attrs else ""
182+
)
183+
164184
if chain is not None:
165185
self.validate_chain()
166186

@@ -364,25 +384,12 @@ def describe(self) -> dict[str, Any]:
364384
# Handle RSA keys
365385
key_algo = f"RSA_{self._key.key_size}"
366386

367-
# Look for SANs
368-
try:
369-
san_obj: Any = self._cert.extensions.get_extension_for_oid(
370-
cryptography.x509.OID_SUBJECT_ALTERNATIVE_NAME
371-
)
372-
except cryptography.x509.ExtensionNotFound:
373-
san_obj = None
374-
sans = []
375-
if san_obj is not None:
376-
sans = [str(item.value) for item in san_obj.value]
377-
378387
result: dict[str, Any] = {
379388
"Certificate": {
380389
"CertificateArn": self.arn,
381390
"DomainName": self.common_name,
382391
"InUseBy": self.in_use_by,
383-
"Issuer": self._cert.issuer.get_attributes_for_oid(OID_COMMON_NAME)[
384-
0
385-
].value,
392+
"Issuer": self.issuer_common_name,
386393
"KeyAlgorithm": key_algo,
387394
"NotAfter": datetime_to_epoch(self._not_valid_after(self._cert)),
388395
"NotBefore": datetime_to_epoch(self._not_valid_before(self._cert)),
@@ -392,7 +399,7 @@ def describe(self) -> dict[str, Any]:
392399
),
393400
"Status": self.status, # One of PENDING_VALIDATION, ISSUED, INACTIVE, EXPIRED, VALIDATION_TIMED_OUT, REVOKED, FAILED.
394401
"Subject": f"CN={self.common_name}",
395-
"SubjectAlternativeNames": sans,
402+
"SubjectAlternativeNames": self.sans,
396403
"Type": self.type, # One of IMPORTED, AMAZON_ISSUED,
397404
"ExtendedKeyUsages": [],
398405
"RenewalEligibility": "INELIGIBLE",
@@ -403,7 +410,7 @@ def describe(self) -> dict[str, Any]:
403410
if self.cert_authority_arn is not None:
404411
result["Certificate"]["CertificateAuthorityArn"] = self.cert_authority_arn
405412

406-
domain_names = set(sans + [self.common_name])
413+
domain_names = set(self.sans + ([self.common_name] if self.common_name else []))
407414
validation_options = []
408415

409416
domain_name_status = "SUCCESS" if self.status == "ISSUED" else self.status

‎tests/test_acm/test_acm.py‎

Lines changed: 54 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,22 @@
88
import pytest
99
from botocore.config import Config
1010
from botocore.exceptions import ClientError
11+
from cryptography import x509
12+
from cryptography.hazmat.backends import default_backend
13+
from cryptography.hazmat.primitives import hashes, serialization
14+
from cryptography.hazmat.primitives.asymmetric import rsa
1115
from cryptography.x509 import (
16+
DNSName,
1217
IPAddress,
18+
NameOID,
1319
SubjectAlternativeName,
1420
load_pem_x509_certificate,
1521
)
1622
from freezegun import freeze_time
1723

1824
from moto import mock_aws, settings
1925
from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID
26+
from moto.core.utils import utcnow
2027
from tests.test_elbv2.test_elbv2 import create_load_balancer
2128

2229
RESOURCE_FOLDER = os.path.join(os.path.dirname(__file__), "resources")
@@ -76,6 +83,51 @@ def test_import_certificate():
7683
assert "CertificateChain" in resp
7784

7885

86+
@mock_aws
87+
def test_import_certificate_without_cn():
88+
"""CN is optional per CAB Forum baseline requirements since 2017.
89+
import_certificate should succeed and DomainName should fall back to the first SAN."""
90+
# Generate a cert with SANs but no CN in the subject
91+
key = rsa.generate_private_key(
92+
public_exponent=65537, key_size=2048, backend=default_backend()
93+
)
94+
subject = x509.Name([]) # empty subject — no CN
95+
cert = (
96+
x509.CertificateBuilder()
97+
.subject_name(subject)
98+
.issuer_name(
99+
x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "Test Issuer")])
100+
)
101+
.public_key(key.public_key())
102+
.serial_number(x509.random_serial_number())
103+
.not_valid_before(utcnow())
104+
.not_valid_after(utcnow() + datetime.timedelta(days=365))
105+
.add_extension(
106+
x509.SubjectAlternativeName(
107+
[DNSName("app.test.example.com"), DNSName("app2.test.example.com")]
108+
),
109+
critical=False,
110+
)
111+
.sign(key, hashes.SHA256(), default_backend())
112+
)
113+
cert_pem = cert.public_bytes(serialization.Encoding.PEM)
114+
key_pem = key.private_bytes(
115+
encoding=serialization.Encoding.PEM,
116+
format=serialization.PrivateFormat.TraditionalOpenSSL,
117+
encryption_algorithm=serialization.NoEncryption(),
118+
)
119+
120+
client = boto3.client("acm", region_name="us-east-1")
121+
resp = client.import_certificate(Certificate=cert_pem, PrivateKey=key_pem)
122+
arn = resp["CertificateArn"]
123+
124+
desc = client.describe_certificate(CertificateArn=arn)["Certificate"]
125+
# DomainName should fall back to the first SAN when CN is absent
126+
assert desc["DomainName"] == "app.test.example.com"
127+
assert "app.test.example.com" in desc["SubjectAlternativeNames"]
128+
assert "app2.test.example.com" in desc["SubjectAlternativeNames"]
129+
130+
79131
@mock_aws
80132
def test_import_certificate_with_tags():
81133
client = boto3.client("acm", region_name="eu-central-1")
@@ -556,14 +608,12 @@ def test_list_certificates_with_key_types_filter():
556608
certs = client.list_certificates(
557609
Includes={"keyTypes": ["RSA_2048", "RSA_4096", "EC_prime256v1"]}
558610
)["CertificateSummaryList"]
559-
560-
assert len(certs) == 1
561-
assert certs[0]["CertificateArn"] == arn
611+
assert any(cert["CertificateArn"] == arn for cert in certs)
562612

563613
certs = client.list_certificates(Includes={"keyTypes": ["RSA_1024"]})[
564614
"CertificateSummaryList"
565615
]
566-
assert len(certs) == 0
616+
assert not any(cert["CertificateArn"] == arn for cert in certs)
567617

568618

569619
@mock_aws

0 commit comments

Comments
 (0)