1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
|
import datetime
import os
import uuid
from ipaddress import IPv4Address
from unittest import SkipTest, mock
import boto3
import pytest
from botocore.exceptions import ClientError
from cryptography.x509 import (
IPAddress,
SubjectAlternativeName,
load_pem_x509_certificate,
)
from freezegun import freeze_time
from moto import mock_aws, settings
from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID
from tests.test_elbv2.test_elbv2 import create_load_balancer
RESOURCE_FOLDER = os.path.join(os.path.dirname(__file__), "resources")
def get_resource(filename):
return open(os.path.join(RESOURCE_FOLDER, filename), "rb").read()
CA_CRT = get_resource("ca.pem")
CA_KEY = get_resource("ca.key")
SERVER_CRT = get_resource("star_moto_com.pem")
SERVER_COMMON_NAME = "*.moto.com"
SERVER_CRT_BAD = get_resource("star_moto_com-bad.pem")
SERVER_KEY = get_resource("star_moto_com.key")
BAD_ARN = f"arn:aws:acm:us-east-2:{ACCOUNT_ID}:certificate/_0000000-0000-0000-0000-000000000000"
CERT_AUTH_ARN = f"arn:aws:acm-pca:eu-central-1:{ACCOUNT_ID}:certificate-authority/12345678-1234-1234-1234-123456789012"
def _import_cert(client):
response = client.import_certificate(
Certificate=SERVER_CRT, PrivateKey=SERVER_KEY, CertificateChain=CA_CRT
)
return response["CertificateArn"]
def _pca_cert(client):
response = client.request_certificate(
DomainName=SERVER_COMMON_NAME, CertificateAuthorityArn=CERT_AUTH_ARN
)
return response["CertificateArn"]
# Also tests GetCertificate
@mock_aws
def test_import_certificate():
client = boto3.client("acm", region_name="eu-central-1")
resp = client.import_certificate(
Certificate=SERVER_CRT, PrivateKey=SERVER_KEY, CertificateChain=CA_CRT
)
resp = client.get_certificate(CertificateArn=resp["CertificateArn"])
assert resp["Certificate"] == SERVER_CRT.decode()
assert "CertificateChain" in resp
@mock_aws
def test_import_certificate_with_tags():
client = boto3.client("acm", region_name="eu-central-1")
resp = client.import_certificate(
Certificate=SERVER_CRT,
PrivateKey=SERVER_KEY,
CertificateChain=CA_CRT,
Tags=[{"Key": "Environment", "Value": "QA"}, {"Key": "KeyOnly"}],
)
arn = resp["CertificateArn"]
resp = client.get_certificate(CertificateArn=arn)
assert resp["Certificate"] == SERVER_CRT.decode()
assert "CertificateChain" in resp
resp = client.list_tags_for_certificate(CertificateArn=arn)
tags = {item["Key"]: item.get("Value", "__NONE__") for item in resp["Tags"]}
assert "Environment" in tags
assert "KeyOnly" in tags
assert tags["Environment"] == "QA"
assert tags["KeyOnly"] == "__NONE__"
@mock_aws
def test_import_bad_certificate():
client = boto3.client("acm", region_name="eu-central-1")
try:
client.import_certificate(Certificate=SERVER_CRT_BAD, PrivateKey=SERVER_KEY)
except ClientError as err:
assert err.response["Error"]["Code"] == "ValidationException"
else:
raise RuntimeError("Should have raised ValidationException")
@mock_aws
def test_list_certificates():
client = boto3.client("acm", region_name="eu-central-1")
issued_arn = _import_cert(client)
pending_arn = client.request_certificate(DomainName="google.com")["CertificateArn"]
try:
certs = client.list_certificates()["CertificateSummaryList"]
except OverflowError:
pytest.skip("This test requires 64-bit time_t")
assert issued_arn in [c["CertificateArn"] for c in certs]
assert pending_arn in [c["CertificateArn"] for c in certs]
for cert in certs:
assert "CertificateArn" in cert
assert "DomainName" in cert
assert "Status" in cert
assert "Type" in cert
assert "KeyAlgorithm" in cert
assert "RenewalEligibility" in cert
assert "NotBefore" in cert
assert "NotAfter" in cert
resp = client.list_certificates(CertificateStatuses=["EXPIRED", "INACTIVE"])
assert len(resp["CertificateSummaryList"]) == 0
certs = client.list_certificates(CertificateStatuses=["PENDING_VALIDATION"])[
"CertificateSummaryList"
]
assert issued_arn not in [c["CertificateArn"] for c in certs]
assert pending_arn in [c["CertificateArn"] for c in certs]
certs = client.list_certificates(CertificateStatuses=["ISSUED"])[
"CertificateSummaryList"
]
assert issued_arn in [c["CertificateArn"] for c in certs]
assert pending_arn not in [c["CertificateArn"] for c in certs]
certs = client.list_certificates(
CertificateStatuses=["ISSUED", "PENDING_VALIDATION"]
)["CertificateSummaryList"]
assert issued_arn in [c["CertificateArn"] for c in certs]
assert pending_arn in [c["CertificateArn"] for c in certs]
@mock_aws
def test_get_invalid_certificate():
client = boto3.client("acm", region_name="eu-central-1")
try:
client.get_certificate(CertificateArn=BAD_ARN)
except ClientError as err:
assert err.response["Error"]["Code"] == "ResourceNotFoundException"
else:
raise RuntimeError("Should have raised ResourceNotFoundException")
# Also tests deleting invalid certificate
@mock_aws
def test_delete_certificate():
client = boto3.client("acm", region_name="eu-central-1")
arn = _import_cert(client)
# If it does not raise an error and the next call does, all is fine
client.delete_certificate(CertificateArn=arn)
try:
client.delete_certificate(CertificateArn=arn)
except ClientError as err:
assert err.response["Error"]["Code"] == "ResourceNotFoundException"
else:
raise RuntimeError("Should have raised ResourceNotFoundException")
@mock_aws
def test_request_certificate_for_ip():
client = boto3.client("acm", region_name="eu-central-1")
arn = client.request_certificate(DomainName="10.0.0.1")["CertificateArn"]
try:
cert_arn = client.describe_certificate(CertificateArn=arn)["Certificate"][
"CertificateArn"
]
except OverflowError:
pytest.skip("This test requires 64-bit time_t")
resp = client.get_certificate(CertificateArn=cert_arn)
cert = load_pem_x509_certificate(resp["Certificate"].encode("utf-8"))
san = cert.extensions[0].value
assert isinstance(san, SubjectAlternativeName)
ip_address = san.get_values_for_type(IPAddress)[0]
assert isinstance(ip_address, IPv4Address)
assert ip_address.compressed == "10.0.0.1"
@mock_aws
def test_describe_certificate():
client = boto3.client("acm", region_name="eu-central-1")
arn = client.request_certificate(DomainName=SERVER_COMMON_NAME)["CertificateArn"]
try:
resp = client.describe_certificate(CertificateArn=arn)
except OverflowError:
pytest.skip("This test requires 64-bit time_t")
assert resp["Certificate"]["CertificateArn"] == arn
assert resp["Certificate"]["DomainName"] == SERVER_COMMON_NAME
assert resp["Certificate"]["Issuer"] == "Amazon"
assert resp["Certificate"]["KeyAlgorithm"] == "RSA_2048"
assert resp["Certificate"]["Status"] == "PENDING_VALIDATION"
assert resp["Certificate"]["Type"] == "AMAZON_ISSUED"
assert resp["Certificate"]["RenewalEligibility"] == "INELIGIBLE"
assert "Options" in resp["Certificate"]
assert len(resp["Certificate"]["DomainValidationOptions"]) == 1
validation_option = resp["Certificate"]["DomainValidationOptions"][0]
assert validation_option["DomainName"] == SERVER_COMMON_NAME
@mock_aws
def test_describe_certificate_with_bad_arn():
client = boto3.client("acm", region_name="eu-central-1")
with pytest.raises(ClientError) as err:
client.describe_certificate(CertificateArn=BAD_ARN)
assert err.value.response["Error"]["Code"] == "ResourceNotFoundException"
@mock_aws
def test_describe_certificate_with_imported_cert():
client = boto3.client("acm", region_name="eu-central-1")
arn = _import_cert(client)
try:
resp = client.describe_certificate(CertificateArn=arn)
except OverflowError:
pytest.skip("This test requires 64-bit time_t")
assert resp["Certificate"]["CertificateArn"] == arn
assert resp["Certificate"]["DomainName"] == SERVER_COMMON_NAME
assert resp["Certificate"]["Issuer"] == "Moto"
assert resp["Certificate"]["KeyAlgorithm"] == "RSA_2048"
assert resp["Certificate"]["Status"] == "ISSUED"
assert resp["Certificate"]["Type"] == "IMPORTED"
assert resp["Certificate"]["RenewalEligibility"] == "INELIGIBLE"
assert "Options" in resp["Certificate"]
assert "DomainValidationOptions" not in resp["Certificate"]
@mock_aws
def test_describe_certificate_with_pca_cert():
client = boto3.client("acm", region_name="eu-central-1")
arn = _pca_cert(client)
try:
resp = client.describe_certificate(CertificateArn=arn)
except OverflowError:
pytest.skip("This test requires 64-bit time_t")
assert resp["Certificate"]["CertificateArn"] == arn
assert resp["Certificate"]["DomainName"] == SERVER_COMMON_NAME
assert resp["Certificate"]["Issuer"] == "Amazon"
assert resp["Certificate"]["KeyAlgorithm"] == "RSA_2048"
assert resp["Certificate"]["Status"] == "ISSUED"
assert resp["Certificate"]["Type"] == "PRIVATE"
assert resp["Certificate"]["RenewalEligibility"] == "INELIGIBLE"
assert "Options" in resp["Certificate"]
assert resp["Certificate"]["CertificateAuthorityArn"] == CERT_AUTH_ARN
assert "DomainValidationOptions" not in resp["Certificate"]
@mock_aws
def test_export_certificate_with_pca_cert():
client = boto3.client("acm", region_name="eu-central-1")
arn = _pca_cert(client)
resp = client.export_certificate(CertificateArn=arn, Passphrase="passphrase")
assert "CertificateChain" in resp
assert "Certificate" in resp
assert "PrivateKey" in resp
@mock_aws
def test_export_certificate_with_imported_cert():
client = boto3.client("acm", region_name="eu-central-1")
arn = _import_cert(client)
with pytest.raises(ClientError) as err:
client.export_certificate(CertificateArn=arn, Passphrase="passphrase")
assert err.value.response["Error"]["Code"] == "ValidationException"
assert "is not a private certificate" in err.value.response["Error"]["Message"]
@mock_aws
def test_export_certificate_with_short_passphrase():
client = boto3.client("acm", region_name="eu-central-1")
arn = _pca_cert(client)
with pytest.raises(ClientError) as err:
client.export_certificate(CertificateArn=arn, Passphrase="")
assert err.value.response["Error"]["Code"] == "ValidationException"
assert "passphrase" in err.value.response["Error"]["Message"]
@mock_aws
def test_export_certificate_with_bad_arn():
client = boto3.client("acm", region_name="eu-central-1")
with pytest.raises(ClientError) as err:
client.export_certificate(CertificateArn=BAD_ARN, Passphrase="pass")
assert err.value.response["Error"]["Code"] == "ResourceNotFoundException"
# Also tests ListTagsForCertificate
@mock_aws
def test_add_tags_to_certificate():
client = boto3.client("acm", region_name="eu-central-1")
arn = _import_cert(client)
client.add_tags_to_certificate(
CertificateArn=arn, Tags=[{"Key": "key1", "Value": "value1"}, {"Key": "key2"}]
)
resp = client.list_tags_for_certificate(CertificateArn=arn)
tags = {item["Key"]: item.get("Value", "__NONE__") for item in resp["Tags"]}
assert "key1" in tags
assert "key2" in tags
assert tags["key1"] == "value1"
# This way, it ensures that we can detect if None is passed back when it shouldnt,
# as we store keys without values with a value of None, but it shouldnt be passed back
assert tags["key2"] == "__NONE__"
@mock_aws
def test_add_tags_to_invalid_certificate():
client = boto3.client("acm", region_name="eu-central-1")
try:
client.add_tags_to_certificate(
CertificateArn=BAD_ARN,
Tags=[{"Key": "key1", "Value": "value1"}, {"Key": "key2"}],
)
except ClientError as err:
assert err.response["Error"]["Code"] == "ResourceNotFoundException"
else:
raise RuntimeError("Should have raised ResourceNotFoundException")
@mock_aws
def test_list_tags_for_invalid_certificate():
client = boto3.client("acm", region_name="eu-central-1")
try:
client.list_tags_for_certificate(CertificateArn=BAD_ARN)
except ClientError as err:
assert err.response["Error"]["Code"] == "ResourceNotFoundException"
else:
raise RuntimeError("Should have raised ResourceNotFoundException")
@mock_aws
def test_remove_tags_from_certificate():
client = boto3.client("acm", region_name="eu-central-1")
arn = _import_cert(client)
client.add_tags_to_certificate(
CertificateArn=arn,
Tags=[
{"Key": "key1", "Value": "value1"},
{"Key": "key2"},
{"Key": "key3", "Value": "value3"},
{"Key": "key4", "Value": "value4"},
],
)
client.remove_tags_from_certificate(
CertificateArn=arn,
Tags=[
{"Key": "key1", "Value": "value2"}, # Should not remove as doesnt match
{"Key": "key2"}, # Single key removal
{"Key": "key3", "Value": "value3"}, # Exact match removal
{"Key": "key4"}, # Partial match removal
],
)
resp = client.list_tags_for_certificate(CertificateArn=arn)
tags = {item["Key"]: item.get("Value", "__NONE__") for item in resp["Tags"]}
for key in ("key2", "key3", "key4"):
assert key not in tags
assert "key1" in tags
@mock_aws
def test_remove_tags_from_invalid_certificate():
client = boto3.client("acm", region_name="eu-central-1")
try:
client.remove_tags_from_certificate(
CertificateArn=BAD_ARN,
Tags=[{"Key": "key1", "Value": "value1"}, {"Key": "key2"}],
)
except ClientError as err:
assert err.response["Error"]["Code"] == "ResourceNotFoundException"
else:
raise RuntimeError("Should have raised ResourceNotFoundException")
@mock_aws
def test_resend_validation_email():
client = boto3.client("acm", region_name="eu-central-1")
arn = _import_cert(client)
client.resend_validation_email(
CertificateArn=arn, Domain="*.moto.com", ValidationDomain="NOTUSEDYET"
)
# Returns nothing, boto would raise Exceptions otherwise
@mock_aws
def test_resend_validation_email_invalid():
client = boto3.client("acm", region_name="eu-central-1")
arn = _import_cert(client)
try:
client.resend_validation_email(
CertificateArn=arn,
Domain="no-match.moto.com",
ValidationDomain="NOTUSEDYET",
)
except ClientError as err:
assert (
err.response["Error"]["Code"] == "InvalidDomainValidationOptionsException"
)
else:
raise RuntimeError("Should have raised InvalidDomainValidationOptionsException")
try:
client.resend_validation_email(
CertificateArn=BAD_ARN,
Domain="no-match.moto.com",
ValidationDomain="NOTUSEDYET",
)
except ClientError as err:
assert err.response["Error"]["Code"] == "ResourceNotFoundException"
else:
raise RuntimeError("Should have raised ResourceNotFoundException")
@mock_aws
def test_request_certificate():
client = boto3.client("acm", region_name="eu-central-1")
token = str(uuid.uuid4())
resp = client.request_certificate(
DomainName="google.com",
IdempotencyToken=token,
SubjectAlternativeNames=["google.com", "www.google.com", "mail.google.com"],
)
assert "CertificateArn" in resp
arn = resp["CertificateArn"]
assert f"arn:aws:acm:eu-central-1:{ACCOUNT_ID}:certificate/" in arn
resp = client.request_certificate(
DomainName="google.com",
IdempotencyToken=token,
SubjectAlternativeNames=["google.com", "www.google.com", "mail.google.com"],
)
assert resp["CertificateArn"] == arn
@mock_aws
@mock.patch("moto.settings.ACM_VALIDATION_WAIT", 1)
def test_request_exportable_certificate():
if not settings.TEST_DECORATOR_MODE:
raise SkipTest("Can only change setting in DecoratorMode")
client = boto3.client("acm", region_name="eu-central-1")
resp = client.request_certificate(
DomainName="example.com",
Options={"Export": "ENABLED"},
)
assert "CertificateArn" in resp
arn_1 = resp["CertificateArn"]
waiter = client.get_waiter("certificate_validated")
waiter.wait(CertificateArn=arn_1, WaiterConfig={"Delay": 1})
cert = client.describe_certificate(CertificateArn=arn_1)["Certificate"]
assert cert["Options"]["Export"] == "ENABLED"
resp = client.export_certificate(CertificateArn=arn_1, Passphrase="passphrase")
assert "CertificateChain" in resp
assert "Certificate" in resp
assert "PrivateKey" in resp
# Test that certificates are not exportable by default
resp = client.request_certificate(DomainName="example.com")
assert "CertificateArn" in resp
arn_2 = resp["CertificateArn"]
waiter = client.get_waiter("certificate_validated")
waiter.wait(CertificateArn=arn_2, WaiterConfig={"Delay": 1})
cert = client.describe_certificate(CertificateArn=arn_2)["Certificate"]
assert cert["Options"]["Export"] == "DISABLED"
with pytest.raises(ClientError) as err:
client.export_certificate(CertificateArn=arn_2, Passphrase="passphrase")
assert err.value.response["Error"]["Code"] == "ValidationException"
assert "is not a private certificate" in err.value.response["Error"]["Message"]
# Test filtering for exported certs
certs = client.list_certificates(Includes={"exportOption": "ENABLED"})[
"CertificateSummaryList"
]
assert len(certs) == 1
assert certs[0]["Exported"]
# Test filtering for non-exported certs
certs = client.list_certificates(Includes={"exportOption": "DISABLED"})[
"CertificateSummaryList"
]
assert len(certs) == 1
assert not certs[0]["Exported"]
# Test both certs are returned when no filters are applied
certs = client.list_certificates()["CertificateSummaryList"]
assert len(certs) == 2
@mock_aws
def test_list_certificates_with_key_types_filter():
client = boto3.client("acm", region_name="us-east-1")
arn = _import_cert(client)
certs = client.list_certificates(
Includes={"keyTypes": ["RSA_2048", "RSA_4096", "EC_prime256v1"]}
)["CertificateSummaryList"]
assert len(certs) == 1
assert certs[0]["CertificateArn"] == arn
certs = client.list_certificates(Includes={"keyTypes": ["RSA_1024"]})[
"CertificateSummaryList"
]
assert len(certs) == 0
@mock_aws
@mock.patch("moto.settings.ACM_VALIDATION_WAIT", 1)
def test_request_certificate_with_optional_arguments():
if not settings.TEST_DECORATOR_MODE:
raise SkipTest("Can only change setting in DecoratorMode")
client = boto3.client("acm", region_name="eu-central-1")
token = str(uuid.uuid4())
resp = client.request_certificate(
DomainName="google.com",
IdempotencyToken=token,
SubjectAlternativeNames=["google.com", "www.google.com", "mail.google.com"],
Tags=[
{"Key": "Environment", "Value": "QA"},
{"Key": "WithEmptyStr", "Value": ""},
],
)
assert "CertificateArn" in resp
arn_1 = resp["CertificateArn"]
cert = client.describe_certificate(CertificateArn=arn_1)["Certificate"]
assert cert["Status"] == "PENDING_VALIDATION"
assert len(cert["SubjectAlternativeNames"]) == 3
validation_options = cert["DomainValidationOptions"].copy()
assert len(validation_options) == 3
assert {option["DomainName"] for option in validation_options} == set(
cert["SubjectAlternativeNames"]
)
# Verify SAN's are still the same, even after the Certificate is validated
waiter = client.get_waiter("certificate_validated")
waiter.wait(CertificateArn=arn_1, WaiterConfig={"Delay": 1})
for opt in validation_options:
opt["ValidationStatus"] = "SUCCESS"
cert = client.describe_certificate(CertificateArn=arn_1)["Certificate"]
assert cert["DomainValidationOptions"] == validation_options
resp = client.list_tags_for_certificate(CertificateArn=arn_1)
tags = {item["Key"]: item.get("Value", "__NONE__") for item in resp["Tags"]}
assert len(tags) == 2
assert tags["Environment"] == "QA"
assert tags["WithEmptyStr"] == ""
# Request certificate for "google.com" with same IdempotencyToken but with different Tags
resp = client.request_certificate(
DomainName="google.com",
IdempotencyToken=token,
SubjectAlternativeNames=["google.com", "www.google.com", "mail.google.com"],
Tags=[{"Key": "Environment", "Value": "Prod"}, {"Key": "KeyOnly"}],
)
arn_2 = resp["CertificateArn"]
assert arn_1 != arn_2 # if tags are matched, ACM would have returned same arn
resp = client.list_tags_for_certificate(CertificateArn=arn_2)
tags = {item["Key"]: item.get("Value", "__NONE__") for item in resp["Tags"]}
assert len(tags) == 2
assert tags["Environment"] == "Prod"
assert tags["KeyOnly"] == "__NONE__"
resp = client.request_certificate(
DomainName="google.com",
IdempotencyToken=token,
SubjectAlternativeNames=["google.com", "www.google.com", "mail.google.com"],
Tags=[
{"Key": "Environment", "Value": "QA"},
{"Key": "WithEmptyStr", "Value": ""},
],
)
arn_3 = resp["CertificateArn"]
assert arn_1 != arn_3 # if tags are matched, ACM would have returned same arn
resp = client.request_certificate(
DomainName="google.com",
IdempotencyToken=token,
SubjectAlternativeNames=["google.com", "www.google.com", "mail.google.com"],
)
arn_4 = resp["CertificateArn"]
assert arn_1 != arn_4 # if tags are matched, ACM would have returned same arn
@mock_aws
def test_request_certificate_with_certificate_authority():
client = boto3.client("acm", region_name="eu-central-1")
resp = client.request_certificate(
DomainName="example.com",
CertificateAuthorityArn="arn:aws:acm-pca:eu-central-1:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012",
)
assert "CertificateArn" in resp
@mock_aws
def test_operations_with_invalid_tags():
client = boto3.client("acm", region_name="eu-central-1")
# request certificate with invalid tags
with pytest.raises(ClientError) as ex:
client.request_certificate(
DomainName="example.com", Tags=[{"Key": "X" * 200, "Value": "Valid"}]
)
err = ex.value.response["Error"]
assert err["Code"] == "ValidationException"
assert "Member must have length less than or equal to 128" in err["Message"]
# import certificate with invalid tags
with pytest.raises(ClientError) as ex:
client.import_certificate(
Certificate=SERVER_CRT,
PrivateKey=SERVER_KEY,
CertificateChain=CA_CRT,
Tags=[
{"Key": "Valid", "Value": "X" * 300},
{"Key": "aws:xx", "Value": "Valid"},
],
)
err = ex.value.response["Error"]
assert err["Code"] == "ValidationException"
assert "Member must have length less than or equal to 256" in err["Message"]
arn = _import_cert(client)
# add invalid tags to existing certificate
with pytest.raises(ClientError) as ex:
client.add_tags_to_certificate(
CertificateArn=arn,
Tags=[{"Key": "aws:xxx", "Value": "Valid"}, {"Key": "key2"}],
)
err = ex.value.response["Error"]
assert err["Code"] == "ValidationException"
assert "AWS internal tags cannot be changed with this API" in err["Message"]
# try removing invalid tags from existing certificate
with pytest.raises(ClientError) as ex:
client.remove_tags_from_certificate(
CertificateArn=arn, Tags=[{"Key": "aws:xxx", "Value": "Valid"}]
)
err = ex.value.response["Error"]
assert err["Code"] == "ValidationException"
assert "AWS internal tags cannot be changed with this API" in err["Message"]
@mock_aws
def test_add_too_many_tags():
client = boto3.client("acm", region_name="eu-central-1")
arn = _import_cert(client)
# Add 51 tags
with pytest.raises(ClientError) as ex:
client.add_tags_to_certificate(
CertificateArn=arn,
Tags=[{"Key": f"a-{i}", "Value": "abcd"} for i in range(1, 52)],
)
assert ex.value.response["Error"]["Code"] == "TooManyTagsException"
assert "contains too many Tags" in ex.value.response["Error"]["Message"]
assert client.list_tags_for_certificate(CertificateArn=arn)["Tags"] == []
# Add 49 tags first, then try to add 2 more.
client.add_tags_to_certificate(
CertificateArn=arn,
Tags=[{"Key": f"p-{i}", "Value": "pqrs"} for i in range(1, 50)],
)
assert len(client.list_tags_for_certificate(CertificateArn=arn)["Tags"]) == 49
with pytest.raises(ClientError) as ex:
client.add_tags_to_certificate(
CertificateArn=arn,
Tags=[{"Key": "x-1", "Value": "xyz"}, {"Key": "x-2", "Value": "xyz"}],
)
assert ex.value.response["Error"]["Code"] == "TooManyTagsException"
assert "contains too many Tags" in ex.value.response["Error"]["Message"]
assert ex.value.response["Error"]["Message"].count("pqrs") == 49
assert ex.value.response["Error"]["Message"].count("xyz") == 2
assert len(client.list_tags_for_certificate(CertificateArn=arn)["Tags"]) == 49
@mock_aws
def test_request_certificate_no_san():
client = boto3.client("acm", region_name="eu-central-1")
resp = client.request_certificate(DomainName="google.com")
assert "CertificateArn" in resp
resp2 = client.describe_certificate(CertificateArn=resp["CertificateArn"])
assert "Certificate" in resp2
assert resp2["Certificate"]["RenewalEligibility"] == "INELIGIBLE"
assert "Options" in resp2["Certificate"]
assert len(resp2["Certificate"]["DomainValidationOptions"]) == 1
validation_option = resp2["Certificate"]["DomainValidationOptions"][0]
assert validation_option["DomainName"] == "google.com"
assert validation_option["ValidationDomain"] == "google.com"
# Also tests the SAN code
@mock_aws
def test_request_certificate_issued_status():
# After requesting a certificate, it should then auto-validate after 1 minute
# Some sneaky programming for that ;-)
client = boto3.client("acm", region_name="eu-central-1")
with freeze_time("2012-01-01 12:00:00"):
resp = client.request_certificate(
DomainName="google.com",
SubjectAlternativeNames=["google.com", "www.google.com", "mail.google.com"],
)
arn = resp["CertificateArn"]
with freeze_time("2012-01-01 12:00:00"):
resp = client.describe_certificate(CertificateArn=arn)
assert resp["Certificate"]["CertificateArn"] == arn
assert resp["Certificate"]["DomainName"] == "google.com"
assert resp["Certificate"]["Issuer"] == "Amazon"
assert resp["Certificate"]["KeyAlgorithm"] == "RSA_2048"
assert resp["Certificate"]["Status"] == "PENDING_VALIDATION"
assert resp["Certificate"]["Type"] == "AMAZON_ISSUED"
assert len(resp["Certificate"]["SubjectAlternativeNames"]) == 3
# validation will be pending for 1 minute.
with freeze_time("2012-01-01 12:00:00"):
resp = client.describe_certificate(CertificateArn=arn)
assert resp["Certificate"]["CertificateArn"] == arn
assert resp["Certificate"]["Status"] == "PENDING_VALIDATION"
if settings.TEST_DECORATOR_MODE:
# Move time to get it issued.
with freeze_time("2012-01-01 12:02:00"):
resp = client.describe_certificate(CertificateArn=arn)
assert resp["Certificate"]["CertificateArn"] == arn
assert resp["Certificate"]["Status"] == "ISSUED"
@mock.patch("moto.settings.ACM_VALIDATION_WAIT", 3)
@mock_aws
def test_request_certificate_issued_status_with_wait_in_envvar():
# After requesting a certificate, it should then auto-validate after 3 seconds
if not settings.TEST_DECORATOR_MODE:
raise SkipTest("Cant manipulate time in server mode")
client = boto3.client("acm", region_name="eu-central-1")
with freeze_time("2012-01-01 12:00:00"):
resp = client.request_certificate(DomainName="google.com")
arn = resp["CertificateArn"]
with freeze_time("2012-01-01 12:00:00"):
resp = client.describe_certificate(CertificateArn=arn)
assert resp["Certificate"]["CertificateArn"] == arn
assert resp["Certificate"]["Status"] == "PENDING_VALIDATION"
# validation will be pending for 3 seconds.
with freeze_time("2012-01-01 12:00:02"):
resp = client.describe_certificate(CertificateArn=arn)
assert resp["Certificate"]["CertificateArn"] == arn
assert resp["Certificate"]["Status"] == "PENDING_VALIDATION"
with freeze_time("2012-01-01 12:00:04"):
resp = client.describe_certificate(CertificateArn=arn)
assert resp["Certificate"]["CertificateArn"] == arn
assert resp["Certificate"]["Status"] == "ISSUED"
@mock_aws
def test_request_certificate_with_multiple_times():
if not settings.TEST_DECORATOR_MODE:
raise SkipTest("Cant manipulate time in server mode")
# After requesting a certificate, it should then auto-validate after 1 minute
# Some sneaky programming for that ;-)
client = boto3.client("acm", region_name="eu-central-1")
with freeze_time("2012-01-01 12:00:00"):
resp = client.request_certificate(
IdempotencyToken="test_token",
DomainName="google.com",
SubjectAlternativeNames=["google.com", "www.google.com", "mail.google.com"],
)
original_arn = resp["CertificateArn"]
# Should be able to request a certificate multiple times in an hour
# after that it makes a new one
for time_intervals in (
"2012-01-01 12:15:00",
"2012-01-01 12:30:00",
"2012-01-01 12:45:00",
):
with freeze_time(time_intervals):
resp = client.request_certificate(
IdempotencyToken="test_token",
DomainName="google.com",
SubjectAlternativeNames=[
"google.com",
"www.google.com",
"mail.google.com",
],
)
arn = resp["CertificateArn"]
assert arn == original_arn
# Move time
with freeze_time("2012-01-01 13:01:00"):
resp = client.request_certificate(
IdempotencyToken="test_token",
DomainName="google.com",
SubjectAlternativeNames=["google.com", "www.google.com", "mail.google.com"],
)
arn = resp["CertificateArn"]
assert arn != original_arn
@mock_aws
def test_elb_acm_in_use_by():
acm_client = boto3.client("acm", region_name="us-west-2")
elb_client = boto3.client("elb", region_name="us-west-2")
acm_request_response = acm_client.request_certificate(
DomainName="fake.domain.com",
DomainValidationOptions=[
{"DomainName": "fake.domain.com", "ValidationDomain": "domain.com"}
],
)
certificate_arn = acm_request_response["CertificateArn"]
create_load_balancer_request = elb_client.create_load_balancer(
LoadBalancerName=str(uuid.uuid4()),
Listeners=[
{
"Protocol": "https",
"LoadBalancerPort": 443,
"InstanceProtocol": "http",
"InstancePort": 80,
"SSLCertificateId": certificate_arn,
}
],
)
response = acm_client.describe_certificate(CertificateArn=certificate_arn)
assert response["Certificate"]["InUseBy"] == [
create_load_balancer_request["DNSName"]
]
certificates = acm_client.list_certificates()["CertificateSummaryList"]
cert = [
_cert for _cert in certificates if _cert["CertificateArn"] == certificate_arn
][0]
assert cert["InUse"]
@mock_aws
def test_elbv2_acm_in_use_by():
acm_client = boto3.client("acm", region_name="us-east-1")
certificate_arn = acm_client.request_certificate(
DomainName="fake.domain.com",
DomainValidationOptions=[
{"DomainName": "fake.domain.com", "ValidationDomain": "domain.com"}
],
)["CertificateArn"]
response, _, _, _, _, elbv2_client = create_load_balancer()
load_balancer_arn = response["LoadBalancers"][0]["LoadBalancerArn"]
create_listener_resp = elbv2_client.create_listener(
LoadBalancerArn=load_balancer_arn,
Protocol="HTTP",
Port=443,
DefaultActions=[],
Certificates=[{"CertificateArn": certificate_arn}],
AlpnPolicy=["pol1", "pol2"],
)
response = acm_client.describe_certificate(CertificateArn=certificate_arn)
assert response["Certificate"]["InUseBy"] == [
create_listener_resp["Listeners"][0]["ListenerArn"]
]
certificates = acm_client.list_certificates()["CertificateSummaryList"]
cert = [
_cert for _cert in certificates if _cert["CertificateArn"] == certificate_arn
][0]
assert cert["InUse"]
@mock_aws
def test_certificate_expiration_status():
if not settings.TEST_DECORATOR_MODE:
raise SkipTest("Cant manipulate time in server mode")
client = boto3.client("acm", region_name="eu-central-1")
arn = _import_cert(client)
resp = client.describe_certificate(CertificateArn=arn)
assert resp["Certificate"]["Status"] == "ISSUED"
expiry_time = resp["Certificate"]["NotAfter"]
# Test before expiry (1 second before)
with freeze_time(expiry_time - datetime.timedelta(seconds=1)):
resp = client.describe_certificate(CertificateArn=arn)
assert resp["Certificate"]["Status"] == "ISSUED"
# Test after expiry
with freeze_time(expiry_time + datetime.timedelta(days=1)): # 1 day after
resp = client.describe_certificate(CertificateArn=arn)
assert resp["Certificate"]["Status"] == "EXPIRED"
@mock_aws
def test_account_configuration():
client = boto3.client("acm", region_name="eu-central-1")
# Test default configuration
response = client.get_account_configuration()
assert response["ExpiryEvents"]["DaysBeforeExpiry"] == 45
# Test successful update
response = client.put_account_configuration(
ExpiryEvents={"DaysBeforeExpiry": 30}, IdempotencyToken="test-token"
)
# Verify the update was successful
response = client.get_account_configuration()
assert response["ExpiryEvents"]["DaysBeforeExpiry"] == 30
# Test idempotency token - trying to update with same token but different value
response = client.put_account_configuration(
ExpiryEvents={"DaysBeforeExpiry": 60}, IdempotencyToken="test-token"
)
# Should still be 30 due to idempotency token
response = client.get_account_configuration()
assert response["ExpiryEvents"]["DaysBeforeExpiry"] == 30
|