File: models.py

package info (click to toggle)
python-moto 5.1.18-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 116,520 kB
  • sloc: python: 636,725; javascript: 181; makefile: 39; sh: 3
file content (534 lines) | stat: -rw-r--r-- 20,265 bytes parent folder | download
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
"""ACMPCABackend class with methods for supported APIs."""

import base64
import contextlib
import datetime
from typing import Any, Optional, cast

from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa

from moto.core.base_backend import BackendDict, BaseBackend
from moto.core.common_models import BaseModel
from moto.core.utils import unix_time, utcnow
from moto.moto_api._internal import mock_random
from moto.utilities.paginator import paginate
from moto.utilities.tagging_service import TaggingService
from moto.utilities.utils import get_partition

from .exceptions import (
    InvalidS3ObjectAclInCrlConfiguration,
    InvalidStateException,
    MalformedCertificateAuthorityException,
    ResourceNotFoundException,
)


class CertificateAuthority(BaseModel):
    def __init__(
        self,
        region: str,
        account_id: str,
        certificate_authority_configuration: dict[str, Any],
        certificate_authority_type: str,
        revocation_configuration: dict[str, Any],
        security_standard: Optional[str],
    ):
        self.id = mock_random.uuid4()
        self.arn = f"arn:{get_partition(region)}:acm-pca:{region}:{account_id}:certificate-authority/{self.id}"
        self.account_id = account_id
        self.region_name = region
        self.certificate_authority_configuration = certificate_authority_configuration
        self.certificate_authority_type = certificate_authority_type
        self.revocation_configuration: dict[str, Any] = {
            "CrlConfiguration": {"Enabled": False}
        }
        self.set_revocation_configuration(revocation_configuration)
        self.created_at = unix_time()
        self.updated_at: Optional[float] = None
        self.status = "PENDING_CERTIFICATE"
        self.usage_mode = "SHORT_LIVED_CERTIFICATE"
        self.security_standard = security_standard or "FIPS_140_2_LEVEL_3_OR_HIGHER"
        self.policy: Optional[str] = None

        self.password = str(mock_random.uuid4()).encode("utf-8")

        private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
        self.private_bytes = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.BestAvailableEncryption(self.password),
        )

        self.certificate_bytes: bytes = b""
        self.certificate_chain: Optional[bytes] = None
        self.issued_certificates: dict[str, bytes] = {}
        self.issued_certificates_certificate_chains: dict[str, bytes] = {}

        self.subject = self.certificate_authority_configuration.get("Subject", {})

    def generate_cert(
        self,
        subject: x509.Name,
        public_key: rsa.RSAPublicKey,
        extensions: list[tuple[x509.ExtensionType, bool]],
    ) -> bytes:
        builder = (
            x509.CertificateBuilder()
            .subject_name(subject)
            .issuer_name(self.issuer)
            .public_key(public_key)
            .serial_number(x509.random_serial_number())
            .not_valid_before(utcnow())
            .not_valid_after(utcnow() + datetime.timedelta(days=365))
        )

        for extension, critical in extensions:
            builder = builder.add_extension(extension, critical)

        cert = builder.sign(self.key, hashes.SHA512(), default_backend())

        return cert.public_bytes(serialization.Encoding.PEM)

    @property
    def key(self) -> rsa.RSAPrivateKey:
        private_key = serialization.load_pem_private_key(
            self.private_bytes,
            password=self.password,
        )
        return cast(rsa.RSAPrivateKey, private_key)

    @property
    def certificate(self) -> Optional[x509.Certificate]:
        if self.certificate_bytes:
            return x509.load_pem_x509_certificate(self.certificate_bytes)
        return None

    @property
    def issuer(self) -> x509.Name:
        name_attributes = []
        if "Country" in self.subject:
            name_attributes.append(
                x509.NameAttribute(x509.NameOID.COUNTRY_NAME, self.subject["Country"])
            )
        if "State" in self.subject:
            name_attributes.append(
                x509.NameAttribute(
                    x509.NameOID.STATE_OR_PROVINCE_NAME, self.subject["State"]
                )
            )
        if "Organization" in self.subject:
            name_attributes.append(
                x509.NameAttribute(
                    x509.NameOID.ORGANIZATION_NAME, self.subject["Organization"]
                )
            )
        if "OrganizationalUnit" in self.subject:
            name_attributes.append(
                x509.NameAttribute(
                    x509.NameOID.ORGANIZATIONAL_UNIT_NAME,
                    self.subject["OrganizationalUnit"],
                )
            )
        if "CommonName" in self.subject:
            name_attributes.append(
                x509.NameAttribute(x509.NameOID.COMMON_NAME, self.subject["CommonName"])
            )
        return x509.Name(name_attributes)

    @property
    def csr(self) -> bytes:
        csr = (
            x509.CertificateSigningRequestBuilder()
            .subject_name(self.issuer)
            .add_extension(
                x509.BasicConstraints(ca=True, path_length=None),
                critical=True,
            )
            .sign(self.key, hashes.SHA256())
        )
        return csr.public_bytes(serialization.Encoding.PEM)

    def issue_certificate(self, csr_bytes: bytes, template_arn: Optional[str]) -> str:
        csr = x509.load_pem_x509_csr(base64.b64decode(csr_bytes))
        extensions = self._x509_extensions(csr, template_arn)
        new_cert = self.generate_cert(
            subject=csr.subject,
            public_key=csr.public_key(),  # type: ignore[arg-type]
            extensions=extensions,
        )

        cert_id = str(mock_random.uuid4()).replace("-", "")
        cert_arn = f"arn:{get_partition(self.region_name)}:acm-pca:{self.region_name}:{self.account_id}:certificate-authority/{self.id}/certificate/{cert_id}"
        self.issued_certificates[cert_arn] = new_cert

        # Store certificate with its chain
        # For root CA certificates, chain is empty; for others, include CA certificate
        is_root_cert = template_arn == "arn:aws:acm-pca:::template/RootCACertificate/V1"
        if not is_root_cert:
            self.issued_certificates_certificate_chains[cert_arn] = (
                self.certificate_bytes
            )

        return cert_arn

    def _x509_extensions(
        self, csr: x509.CertificateSigningRequest, template_arn: Optional[str]
    ) -> list[tuple[x509.ExtensionType, bool]]:
        """
        Uses a PCA certificate template ARN to return a list of X.509 extensions.
        These extensions are part of the constructed certificate.

        See https://docs.aws.amazon.com/privateca/latest/userguide/UsingTemplates.html
        """
        extensions = []

        if template_arn == "arn:aws:acm-pca:::template/RootCACertificate/V1":
            extensions.extend(
                [
                    (
                        x509.BasicConstraints(ca=True, path_length=None),
                        True,
                    ),
                    (
                        x509.KeyUsage(
                            crl_sign=True,
                            key_cert_sign=True,
                            digital_signature=True,
                            content_commitment=False,
                            key_encipherment=False,
                            data_encipherment=False,
                            key_agreement=False,
                            encipher_only=False,
                            decipher_only=False,
                        ),
                        True,
                    ),
                    (
                        x509.SubjectKeyIdentifier.from_public_key(csr.public_key()),
                        False,
                    ),
                ]
            )

        elif template_arn in (
            "arn:aws:acm-pca:::template/EndEntityCertificate/V1",
            None,
        ):
            extensions.extend(
                [
                    (
                        x509.BasicConstraints(ca=False, path_length=None),
                        True,
                    ),
                    (
                        x509.AuthorityKeyIdentifier.from_issuer_public_key(
                            self.key.public_key()
                        ),
                        False,
                    ),
                    (
                        x509.SubjectKeyIdentifier.from_public_key(csr.public_key()),
                        False,
                    ),
                    (
                        x509.KeyUsage(
                            crl_sign=False,
                            key_cert_sign=False,
                            digital_signature=True,
                            content_commitment=False,
                            key_encipherment=True,
                            data_encipherment=False,
                            key_agreement=False,
                            encipher_only=False,
                            decipher_only=False,
                        ),
                        True,
                    ),
                    (
                        x509.ExtendedKeyUsage(
                            [
                                x509.ExtendedKeyUsageOID.SERVER_AUTH,
                                x509.ExtendedKeyUsageOID.CLIENT_AUTH,
                            ]
                        ),
                        False,
                    ),
                ]
            )

        # Subject Alternative Name passthrough from CSR to the new certificate
        with contextlib.suppress(x509.ExtensionNotFound):
            san = csr.extensions.get_extension_for_oid(
                x509.ExtensionOID.SUBJECT_ALTERNATIVE_NAME
            )
            extensions.append(
                (
                    san.value,
                    san.critical,
                )
            )

        return extensions

    def get_certificate(self, certificate_arn: str) -> tuple[bytes, bytes]:
        certificate = self.issued_certificates[certificate_arn]
        certificate_chain = self.issued_certificates_certificate_chains.get(
            certificate_arn, b""
        )
        return certificate, certificate_chain

    def set_revocation_configuration(
        self, revocation_configuration: Optional[dict[str, Any]]
    ) -> None:
        if revocation_configuration is not None:
            self.revocation_configuration = revocation_configuration
            if "CrlConfiguration" in self.revocation_configuration:
                acl = self.revocation_configuration["CrlConfiguration"].get(
                    "S3ObjectAcl", None
                )
                if acl is None:
                    self.revocation_configuration["CrlConfiguration"]["S3ObjectAcl"] = (
                        "PUBLIC_READ"
                    )
                else:
                    if acl not in ["PUBLIC_READ", "BUCKET_OWNER_FULL_CONTROL"]:
                        raise InvalidS3ObjectAclInCrlConfiguration(acl)

    @property
    def not_valid_after(self) -> Optional[float]:
        if self.certificate is None:
            return None
        try:
            return unix_time(self.certificate.not_valid_after_utc.replace(tzinfo=None))
        except AttributeError:
            return unix_time(self.certificate.not_valid_after)

    @property
    def not_valid_before(self) -> Optional[float]:
        if self.certificate is None:
            return None
        try:
            return unix_time(self.certificate.not_valid_before_utc.replace(tzinfo=None))
        except AttributeError:
            return unix_time(self.certificate.not_valid_before)

    def import_certificate_authority_certificate(
        self, certificate: bytes, certificate_chain: Optional[bytes]
    ) -> None:
        try:
            x509.load_pem_x509_certificate(certificate)
        except ValueError:
            raise MalformedCertificateAuthorityException()

        self.certificate_bytes = certificate
        self.certificate_chain = certificate_chain
        self.status = "ACTIVE"
        self.updated_at = unix_time()

    def to_json(self) -> dict[str, Any]:
        dct = {
            "Arn": self.arn,
            "OwnerAccount": self.account_id,
            "CertificateAuthorityConfiguration": self.certificate_authority_configuration,
            "Type": self.certificate_authority_type,
            "RevocationConfiguration": self.revocation_configuration,
            "CreatedAt": self.created_at,
            "Status": self.status,
            "UsageMode": self.usage_mode,
            "KeyStorageSecurityStandard": self.security_standard,
        }
        if self.updated_at:
            dct["LastStateChangeAt"] = self.updated_at
        if self.certificate:
            dct.update(
                {
                    "NotBefore": self.not_valid_before,
                    "NotAfter": self.not_valid_after,
                }
            )
        return dct


class ACMPCABackend(BaseBackend):
    """Implementation of ACMPCA APIs."""

    PAGINATION_MODEL = {
        "list_certificate_authorities": {
            "input_token": "next_token",
            "limit_key": "max_results",
            "limit_default": 100,
            "unique_attribute": "arn",
        }
    }

    def __init__(self, region_name: str, account_id: str):
        super().__init__(region_name, account_id)
        self.certificate_authorities: dict[str, CertificateAuthority] = {}
        self.tagger = TaggingService()

    def create_certificate_authority(
        self,
        certificate_authority_configuration: dict[str, Any],
        revocation_configuration: dict[str, Any],
        certificate_authority_type: str,
        security_standard: Optional[str],
        tags: list[dict[str, str]],
    ) -> str:
        """
        The following parameters are not yet implemented: IdempotencyToken, KeyStorageSecurityStandard, UsageMode
        """
        authority = CertificateAuthority(
            region=self.region_name,
            account_id=self.account_id,
            certificate_authority_configuration=certificate_authority_configuration,
            certificate_authority_type=certificate_authority_type,
            revocation_configuration=revocation_configuration,
            security_standard=security_standard,
        )
        self.certificate_authorities[authority.arn] = authority
        if tags:
            self.tagger.tag_resource(authority.arn, tags)
        return authority.arn

    def describe_certificate_authority(
        self, certificate_authority_arn: str
    ) -> CertificateAuthority:
        if certificate_authority_arn not in self.certificate_authorities:
            raise ResourceNotFoundException(certificate_authority_arn)
        return self.certificate_authorities[certificate_authority_arn]

    def get_certificate_authority_certificate(
        self, certificate_authority_arn: str
    ) -> tuple[bytes, Optional[bytes]]:
        ca = self.describe_certificate_authority(certificate_authority_arn)
        if ca.status != "ACTIVE":
            raise InvalidStateException(certificate_authority_arn)
        return ca.certificate_bytes, ca.certificate_chain

    def get_certificate_authority_csr(self, certificate_authority_arn: str) -> bytes:
        ca = self.describe_certificate_authority(certificate_authority_arn)
        return ca.csr

    def list_tags(
        self, certificate_authority_arn: str
    ) -> dict[str, list[dict[str, str]]]:
        """
        Pagination is not yet implemented
        """
        return self.tagger.list_tags_for_resource(certificate_authority_arn)

    def update_certificate_authority(
        self,
        certificate_authority_arn: str,
        revocation_configuration: dict[str, Any],
        status: str,
    ) -> None:
        ca = self.describe_certificate_authority(certificate_authority_arn)
        if status is not None:
            ca.status = status
        ca.set_revocation_configuration(revocation_configuration)
        ca.updated_at = unix_time()

    def delete_certificate_authority(self, certificate_authority_arn: str) -> None:
        ca = self.describe_certificate_authority(certificate_authority_arn)
        ca.status = "DELETED"

    def issue_certificate(
        self, certificate_authority_arn: str, csr: bytes, template_arn: Optional[str]
    ) -> str:
        """
        The following parameters are not yet implemented: ApiPassthrough, SigningAlgorithm, Validity, ValidityNotBefore, IdempotencyToken
        Some fields of the resulting certificate will have default values, instead of using the CSR
        """
        ca = self.describe_certificate_authority(certificate_authority_arn)
        certificate_arn = ca.issue_certificate(csr, template_arn)
        return certificate_arn

    def get_certificate(
        self, certificate_authority_arn: str, certificate_arn: str
    ) -> tuple[bytes, bytes]:
        """
        The CertificateChain will always return None for now
        """
        ca = self.describe_certificate_authority(certificate_authority_arn)
        certificate, certificate_chain = ca.get_certificate(certificate_arn)
        return certificate, certificate_chain

    def import_certificate_authority_certificate(
        self,
        certificate_authority_arn: str,
        certificate: bytes,
        certificate_chain: Optional[bytes],
    ) -> None:
        ca = self.describe_certificate_authority(certificate_authority_arn)
        ca.import_certificate_authority_certificate(certificate, certificate_chain)

    def revoke_certificate(
        self,
        certificate_authority_arn: str,
        certificate_serial: str,
        revocation_reason: str,
    ) -> None:
        """
        This is currently a NO-OP
        """

    def tag_certificate_authority(
        self, certificate_authority_arn: str, tags: list[dict[str, str]]
    ) -> None:
        self.tagger.tag_resource(certificate_authority_arn, tags)

    def untag_certificate_authority(
        self, certificate_authority_arn: str, tags: list[dict[str, str]]
    ) -> None:
        self.tagger.untag_resource_using_tags(certificate_authority_arn, tags)

    def put_policy(self, resource_arn: str, policy: str) -> None:
        """
        Attaches a resource-based policy to a private CA.
        """
        ca = self.describe_certificate_authority(resource_arn)
        if ca.status != "ACTIVE":
            raise InvalidStateException(resource_arn)
        ca.policy = policy

    def get_policy(self, resource_arn: str) -> str:
        """
        Retrieves the resource-based policy attached to a private CA.
        """
        ca = self.describe_certificate_authority(resource_arn)
        if ca.policy is None:
            raise ResourceNotFoundException(resource_arn)
        return ca.policy

    def delete_policy(self, resource_arn: str) -> None:
        """
        Deletes the resource-based policy attached to a private CA.
        """
        ca = self.describe_certificate_authority(resource_arn)
        ca.policy = None

    @paginate(pagination_model=PAGINATION_MODEL)
    def list_certificate_authorities(
        self,
        resource_owner: Optional[str] = None,
    ) -> list[CertificateAuthority]:
        """
        Lists the private certificate authorities that you created by using the CreateCertificateAuthority action.
        """
        cas = list(self.certificate_authorities.values())

        if resource_owner == "OTHER_ACCOUNTS":
            cas = [ca for ca in cas if ca.account_id != self.account_id]
        elif resource_owner == "SELF" or resource_owner is None:
            cas = [ca for ca in cas if ca.account_id == self.account_id]

        cas.sort(key=lambda x: x.created_at, reverse=True)

        return cas


acmpca_backends = BackendDict(ACMPCABackend, "acm-pca")