• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

localstack / localstack / 274ae585-9ad2-4b5f-8087-866ef08d3d6e

24 Apr 2025 05:15PM UTC coverage: 85.262% (-1.0%) from 86.266%
274ae585-9ad2-4b5f-8087-866ef08d3d6e

push

circleci

web-flow
CFn v2: support outputs (#12536)

10 of 29 new or added lines in 3 files covered. (34.48%)

1105 existing lines in 26 files now uncovered.

63256 of 74190 relevant lines covered (85.26%)

0.85 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.11
/localstack-core/localstack/services/kms/models.py
1
import base64
1✔
2
import datetime
1✔
3
import io
1✔
4
import json
1✔
5
import logging
1✔
6
import os
1✔
7
import random
1✔
8
import re
1✔
9
import struct
1✔
10
import uuid
1✔
11
from collections import namedtuple
1✔
12
from dataclasses import dataclass
1✔
13
from typing import Dict, Optional, Tuple
1✔
14

15
from cryptography.exceptions import InvalidSignature, InvalidTag, UnsupportedAlgorithm
1✔
16
from cryptography.hazmat.backends import default_backend
1✔
17
from cryptography.hazmat.primitives import hashes, hmac
1✔
18
from cryptography.hazmat.primitives import serialization as crypto_serialization
1✔
19
from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa, utils
1✔
20
from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePrivateKey
1✔
21
from cryptography.hazmat.primitives.asymmetric.padding import PSS, PKCS1v15
1✔
22
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
1✔
23
from cryptography.hazmat.primitives.asymmetric.utils import Prehashed
1✔
24
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
1✔
25
from cryptography.hazmat.primitives.serialization import load_der_public_key
1✔
26

27
from localstack.aws.api.kms import (
1✔
28
    CreateAliasRequest,
29
    CreateGrantRequest,
30
    CreateKeyRequest,
31
    EncryptionContextType,
32
    InvalidCiphertextException,
33
    InvalidKeyUsageException,
34
    KeyMetadata,
35
    KeySpec,
36
    KeyState,
37
    KeyUsageType,
38
    KMSInvalidMacException,
39
    KMSInvalidSignatureException,
40
    LimitExceededException,
41
    MacAlgorithmSpec,
42
    MessageType,
43
    MultiRegionConfiguration,
44
    MultiRegionKey,
45
    MultiRegionKeyType,
46
    OriginType,
47
    ReplicateKeyRequest,
48
    SigningAlgorithmSpec,
49
    TagList,
50
    UnsupportedOperationException,
51
)
52
from localstack.constants import TAG_KEY_CUSTOM_ID
1✔
53
from localstack.services.kms.exceptions import TagException, ValidationException
1✔
54
from localstack.services.kms.utils import is_valid_key_arn, validate_tag
1✔
55
from localstack.services.stores import AccountRegionBundle, BaseStore, LocalAttribute
1✔
56
from localstack.utils.aws.arns import get_partition, kms_alias_arn, kms_key_arn
1✔
57
from localstack.utils.crypto import decrypt, encrypt
1✔
58
from localstack.utils.strings import long_uid, to_bytes, to_str
1✔
59

60
LOG = logging.getLogger(__name__)
1✔
61

62
PATTERN_UUID = re.compile(
1✔
63
    r"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$"
64
)
65
MULTI_REGION_PATTERN = re.compile(r"^mrk-[a-fA-F0-9]{32}$")
1✔
66

67
SYMMETRIC_DEFAULT_MATERIAL_LENGTH = 32
1✔
68

69
RSA_CRYPTO_KEY_LENGTHS = {
1✔
70
    "RSA_2048": 2048,
71
    "RSA_3072": 3072,
72
    "RSA_4096": 4096,
73
}
74

75
ECC_CURVES = {
1✔
76
    "ECC_NIST_P256": ec.SECP256R1(),
77
    "ECC_NIST_P384": ec.SECP384R1(),
78
    "ECC_NIST_P521": ec.SECP521R1(),
79
    "ECC_SECG_P256K1": ec.SECP256K1(),
80
}
81

82
HMAC_RANGE_KEY_LENGTHS = {
1✔
83
    "HMAC_224": (28, 64),
84
    "HMAC_256": (32, 64),
85
    "HMAC_384": (48, 128),
86
    "HMAC_512": (64, 128),
87
}
88

89
ON_DEMAND_ROTATION_LIMIT = 10
1✔
90
KEY_ID_LEN = 36
1✔
91
# Moto uses IV_LEN of 12, as it is fine for GCM encryption mode, but we use CBC, so have to set it to 16.
92
IV_LEN = 16
1✔
93
TAG_LEN = 16
1✔
94
CIPHERTEXT_HEADER_FORMAT = ">{key_id_len}s{iv_len}s{tag_len}s".format(
1✔
95
    key_id_len=KEY_ID_LEN, iv_len=IV_LEN, tag_len=TAG_LEN
96
)
97
HEADER_LEN = KEY_ID_LEN + IV_LEN + TAG_LEN
1✔
98
Ciphertext = namedtuple("Ciphertext", ("key_id", "iv", "ciphertext", "tag"))
1✔
99

100
RESERVED_ALIASES = [
1✔
101
    "alias/aws/acm",
102
    "alias/aws/dynamodb",
103
    "alias/aws/ebs",
104
    "alias/aws/elasticfilesystem",
105
    "alias/aws/es",
106
    "alias/aws/glue",
107
    "alias/aws/kinesisvideo",
108
    "alias/aws/lambda",
109
    "alias/aws/rds",
110
    "alias/aws/redshift",
111
    "alias/aws/s3",
112
    "alias/aws/secretsmanager",
113
    "alias/aws/ssm",
114
    "alias/aws/xray",
115
]
116

117
# list of key names that should be skipped when serializing the encryption context
118
IGNORED_CONTEXT_KEYS = ["aws-crypto-public-key"]
1✔
119

120
# special tag name to allow specifying a custom key material for created keys
121
TAG_KEY_CUSTOM_KEY_MATERIAL = "_custom_key_material_"
1✔
122

123

124
def _serialize_ciphertext_blob(ciphertext: Ciphertext) -> bytes:
1✔
125
    header = struct.pack(
1✔
126
        CIPHERTEXT_HEADER_FORMAT,
127
        ciphertext.key_id.encode("utf-8"),
128
        ciphertext.iv,
129
        ciphertext.tag,
130
    )
131
    return header + ciphertext.ciphertext
1✔
132

133

134
def deserialize_ciphertext_blob(ciphertext_blob: bytes) -> Ciphertext:
1✔
135
    header = ciphertext_blob[:HEADER_LEN]
1✔
136
    ciphertext = ciphertext_blob[HEADER_LEN:]
1✔
137
    key_id, iv, tag = struct.unpack(CIPHERTEXT_HEADER_FORMAT, header)
1✔
138
    return Ciphertext(key_id=key_id.decode("utf-8"), iv=iv, ciphertext=ciphertext, tag=tag)
1✔
139

140

141
def _serialize_encryption_context(encryption_context: Optional[EncryptionContextType]) -> bytes:
1✔
142
    if encryption_context:
1✔
143
        aad = io.BytesIO()
1✔
144
        for key, value in sorted(encryption_context.items(), key=lambda x: x[0]):
1✔
145
            # remove the reserved key-value pair from additional authentication data
146
            if key not in IGNORED_CONTEXT_KEYS:
1✔
147
                aad.write(key.encode("utf-8"))
1✔
148
                aad.write(value.encode("utf-8"))
1✔
149
        return aad.getvalue()
1✔
150
    else:
151
        return b""
1✔
152

153

154
# Confusion alert!
155
# In KMS, there are two things that can be called "keys":
156
#   1. A cryptographic key, i.e. a string of characters, a private/public/symmetrical key for cryptographic encoding
157
#   and decoding etc. It is modeled here by KmsCryptoKey class.
158
#   2. An AWS object that stores both a cryptographic key and some relevant metadata, e.g. creation time, a unique ID,
159
#   some state. It is modeled by KmsKey class.
160
#
161
# While KmsKeys always contain KmsCryptoKeys, sometimes KmsCryptoKeys exist without corresponding KmsKeys,
162
# e.g. GenerateDataKeyPair API call returns contents of a new KmsCryptoKey that is not associated with any KmsKey,
163
# but is partially encrypted by some pre-existing KmsKey.
164

165

166
class KmsCryptoKey:
1✔
167
    """
168
    KmsCryptoKeys used to model both of the two cases where AWS generates keys:
169
    1. Keys that are created to be used inside of AWS. For such a key, its key material / private key are not to
170
    leave AWS unencrypted. If they have to leave AWS, a different KmsCryptoKey is used to encrypt the data first.
171
    2. Keys that AWS creates for customers for some external use. Such a key might be returned to a customer with its
172
    key material or public key unencrypted - see KMS GenerateDataKey / GenerateDataKeyPair. But such a key is not stored
173
    by AWS and is not used by AWS.
174
    """
175

176
    public_key: Optional[bytes]
1✔
177
    private_key: Optional[bytes]
1✔
178
    key_material: bytes
1✔
179
    key_spec: str
1✔
180

181
    @staticmethod
1✔
182
    def assert_valid(key_spec: str):
1✔
183
        """
184
        Validates that the given ``key_spec`` is supported in the current context.
185

186
        :param key_spec: The key specification to validate.
187
        :type key_spec: str
188
        :raises ValidationException: If ``key_spec`` is not a known valid spec.
189
        :raises UnsupportedOperationException: If ``key_spec`` is entirely unsupported.
190
        """
191

192
        def raise_validation():
1✔
193
            raise ValidationException(
1✔
194
                f"1 validation error detected: Value '{key_spec}' at 'keySpec' "
195
                f"failed to satisfy constraint: Member must satisfy enum value set: "
196
                f"[RSA_2048, ECC_NIST_P384, ECC_NIST_P256, ECC_NIST_P521, HMAC_384, RSA_3072, "
197
                f"ECC_SECG_P256K1, RSA_4096, SYMMETRIC_DEFAULT, HMAC_256, HMAC_224, HMAC_512]"
198
            )
199

200
        if key_spec == "SYMMETRIC_DEFAULT":
1✔
201
            return
1✔
202

203
        if key_spec.startswith("RSA"):
1✔
204
            if key_spec not in RSA_CRYPTO_KEY_LENGTHS:
1✔
205
                raise_validation()
1✔
206
            return
1✔
207

208
        if key_spec.startswith("ECC"):
1✔
209
            if key_spec not in ECC_CURVES:
1✔
210
                raise_validation()
1✔
211
            return
1✔
212

213
        if key_spec.startswith("HMAC"):
1✔
214
            if key_spec not in HMAC_RANGE_KEY_LENGTHS:
1✔
215
                raise_validation()
1✔
216
            return
1✔
217

218
        raise UnsupportedOperationException(f"KeySpec {key_spec} is not supported")
1✔
219

220
    def __init__(self, key_spec: str, key_material: Optional[bytes] = None):
1✔
221
        self.private_key = None
1✔
222
        self.public_key = None
1✔
223
        # Technically, key_material, being a symmetric encryption key, is only relevant for
224
        #   key_spec == SYMMETRIC_DEFAULT.
225
        # But LocalStack uses symmetric encryption with this key_material even for other specs. Asymmetric keys are
226
        # generated, but are not actually used for encryption. Signing is different.
227
        self.key_material = key_material or os.urandom(SYMMETRIC_DEFAULT_MATERIAL_LENGTH)
1✔
228
        self.key_spec = key_spec
1✔
229

230
        KmsCryptoKey.assert_valid(key_spec)
1✔
231

232
        if key_spec == "SYMMETRIC_DEFAULT":
1✔
233
            return
1✔
234

235
        if key_spec.startswith("RSA"):
1✔
236
            key_size = RSA_CRYPTO_KEY_LENGTHS.get(key_spec)
1✔
237
            key = rsa.generate_private_key(public_exponent=65537, key_size=key_size)
1✔
238
        elif key_spec.startswith("ECC"):
1✔
239
            curve = ECC_CURVES.get(key_spec)
1✔
240
            if key_material:
1✔
241
                key = crypto_serialization.load_der_private_key(key_material, password=None)
1✔
242
            else:
243
                key = ec.generate_private_key(curve)
1✔
244
        elif key_spec.startswith("HMAC"):
1✔
245
            minimum_length, maximum_length = HMAC_RANGE_KEY_LENGTHS.get(key_spec)
1✔
246
            self.key_material = key_material or os.urandom(
1✔
247
                random.randint(minimum_length, maximum_length)
248
            )
249
            return
1✔
250

251
        self._serialize_key(key)
1✔
252

253
    def load_key_material(self, material: bytes):
1✔
254
        if self.key_spec == "SYMMETRIC_DEFAULT":
1✔
255
            self.key_material = material
1✔
256
        else:
257
            key = crypto_serialization.load_der_private_key(material, password=None)
1✔
258
            self._serialize_key(key)
1✔
259

260
    def _serialize_key(self, key: ec.EllipticCurvePrivateKey | rsa.RSAPrivateKey):
1✔
261
        self.public_key = key.public_key().public_bytes(
1✔
262
            crypto_serialization.Encoding.DER,
263
            crypto_serialization.PublicFormat.SubjectPublicKeyInfo,
264
        )
265
        self.private_key = key.private_bytes(
1✔
266
            crypto_serialization.Encoding.DER,
267
            crypto_serialization.PrivateFormat.PKCS8,
268
            crypto_serialization.NoEncryption(),
269
        )
270

271
    @property
1✔
272
    def key(self) -> RSAPrivateKey | EllipticCurvePrivateKey:
1✔
273
        return crypto_serialization.load_der_private_key(
1✔
274
            self.private_key,
275
            password=None,
276
            backend=default_backend(),
277
        )
278

279

280
class KmsKey:
1✔
281
    metadata: KeyMetadata
1✔
282
    crypto_key: KmsCryptoKey
1✔
283
    tags: Dict[str, str]
1✔
284
    policy: str
1✔
285
    is_key_rotation_enabled: bool
1✔
286
    rotation_period_in_days: int
1✔
287
    next_rotation_date: datetime.datetime
1✔
288
    previous_keys = [str]
1✔
289

290
    def __init__(
1✔
291
        self,
292
        create_key_request: CreateKeyRequest = None,
293
        account_id: str = None,
294
        region: str = None,
295
    ):
296
        create_key_request = create_key_request or CreateKeyRequest()
1✔
297
        self.previous_keys = []
1✔
298

299
        # Please keep in mind that tags of a key could be present in the request, they are not a part of metadata. At
300
        # least in the sense of DescribeKey not returning them with the rest of the metadata. Instead, tags are more
301
        # like aliases:
302
        # https://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html
303
        # "DescribeKey does not return the following information: ... Tags on the KMS key."
304
        self.tags = {}
1✔
305
        self.add_tags(create_key_request.get("Tags"))
1✔
306
        # Same goes for the policy. It is in the request, but not in the metadata.
307
        self.policy = create_key_request.get("Policy") or self._get_default_key_policy(
1✔
308
            account_id, region
309
        )
310
        # https://docs.aws.amazon.com/kms/latest/developerguide/rotate-keys.html
311
        # "Automatic key rotation is disabled by default on customer managed keys but authorized users can enable and
312
        # disable it."
313
        self.is_key_rotation_enabled = False
1✔
314

315
        self._populate_metadata(create_key_request, account_id, region)
1✔
316
        custom_key_material = None
1✔
317
        if TAG_KEY_CUSTOM_KEY_MATERIAL in self.tags:
1✔
318
            # check if the _custom_key_material_ tag is specified, to use a custom key material for this key
319
            custom_key_material = base64.b64decode(self.tags[TAG_KEY_CUSTOM_KEY_MATERIAL])
1✔
320
            # remove the _custom_key_material_ tag from the tags to not readily expose the custom key material
321
            del self.tags[TAG_KEY_CUSTOM_KEY_MATERIAL]
1✔
322
        self.crypto_key = KmsCryptoKey(self.metadata.get("KeySpec"), custom_key_material)
1✔
323
        self.rotation_period_in_days = 365
1✔
324
        self.next_rotation_date = None
1✔
325

326
    def calculate_and_set_arn(self, account_id, region):
1✔
327
        self.metadata["Arn"] = kms_key_arn(self.metadata.get("KeyId"), account_id, region)
1✔
328

329
    def generate_mac(self, msg: bytes, mac_algorithm: MacAlgorithmSpec) -> bytes:
1✔
330
        h = self._get_hmac_context(mac_algorithm)
1✔
331
        h.update(msg)
1✔
332
        return h.finalize()
1✔
333

334
    def verify_mac(self, msg: bytes, mac: bytes, mac_algorithm: MacAlgorithmSpec) -> bool:
1✔
335
        h = self._get_hmac_context(mac_algorithm)
1✔
336
        h.update(msg)
1✔
337
        try:
1✔
338
            h.verify(mac)
1✔
339
            return True
1✔
340
        except InvalidSignature:
1✔
341
            raise KMSInvalidMacException()
1✔
342

343
    # Encrypt is a method of KmsKey and not of KmsCryptoKey only because it requires KeyId, and KmsCryptoKeys do not
344
    # hold KeyIds. Maybe it would be possible to remodel this better.
345
    def encrypt(self, plaintext: bytes, encryption_context: EncryptionContextType = None) -> bytes:
1✔
346
        iv = os.urandom(IV_LEN)
1✔
347
        aad = _serialize_encryption_context(encryption_context=encryption_context)
1✔
348
        ciphertext, tag = encrypt(self.crypto_key.key_material, plaintext, iv, aad)
1✔
349
        return _serialize_ciphertext_blob(
1✔
350
            ciphertext=Ciphertext(
351
                key_id=self.metadata.get("KeyId"), iv=iv, ciphertext=ciphertext, tag=tag
352
            )
353
        )
354

355
    # The ciphertext has to be deserialized before this call.
356
    def decrypt(
1✔
357
        self, ciphertext: Ciphertext, encryption_context: EncryptionContextType = None
358
    ) -> bytes:
359
        aad = _serialize_encryption_context(encryption_context=encryption_context)
1✔
360
        keys_to_try = [self.crypto_key.key_material] + self.previous_keys
1✔
361

362
        for key in keys_to_try:
1✔
363
            try:
1✔
364
                return decrypt(key, ciphertext.ciphertext, ciphertext.iv, ciphertext.tag, aad)
1✔
365
            except (InvalidTag, InvalidSignature):
1✔
366
                continue
1✔
367

368
        raise InvalidCiphertextException()
1✔
369

370
    def decrypt_rsa(self, encrypted: bytes) -> bytes:
1✔
371
        private_key = crypto_serialization.load_der_private_key(
1✔
372
            self.crypto_key.private_key, password=None, backend=default_backend()
373
        )
374
        decrypted = private_key.decrypt(
1✔
375
            encrypted,
376
            padding.OAEP(
377
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
378
                algorithm=hashes.SHA256(),
379
                label=None,
380
            ),
381
        )
382
        return decrypted
1✔
383

384
    def sign(
1✔
385
        self, data: bytes, message_type: MessageType, signing_algorithm: SigningAlgorithmSpec
386
    ) -> bytes:
387
        hasher, wrapped_hasher = self._construct_sign_verify_hasher(signing_algorithm, message_type)
1✔
388
        try:
1✔
389
            if signing_algorithm.startswith("ECDSA"):
1✔
390
                return self.crypto_key.key.sign(data, ec.ECDSA(wrapped_hasher))
1✔
391
            else:
392
                padding = self._construct_sign_verify_padding(signing_algorithm, hasher)
1✔
393
                return self.crypto_key.key.sign(data, padding, wrapped_hasher)
1✔
394
        except ValueError as exc:
1✔
395
            raise ValidationException(str(exc))
1✔
396

397
    def verify(
1✔
398
        self,
399
        data: bytes,
400
        message_type: MessageType,
401
        signing_algorithm: SigningAlgorithmSpec,
402
        signature: bytes,
403
    ) -> bool:
404
        hasher, wrapped_hasher = self._construct_sign_verify_hasher(signing_algorithm, message_type)
1✔
405
        try:
1✔
406
            if signing_algorithm.startswith("ECDSA"):
1✔
407
                self.crypto_key.key.public_key().verify(signature, data, ec.ECDSA(wrapped_hasher))
1✔
408
            else:
409
                padding = self._construct_sign_verify_padding(signing_algorithm, hasher)
1✔
410
                self.crypto_key.key.public_key().verify(signature, data, padding, wrapped_hasher)
1✔
411
            return True
1✔
412
        except ValueError as exc:
1✔
413
            raise ValidationException(str(exc))
1✔
414
        except InvalidSignature:
1✔
415
            # AWS itself raises this exception without any additional message.
416
            raise KMSInvalidSignatureException()
1✔
417

418
    def derive_shared_secret(self, public_key: bytes) -> bytes:
1✔
419
        key_spec = self.metadata.get("KeySpec")
1✔
420
        match key_spec:
1✔
421
            case KeySpec.ECC_NIST_P256 | KeySpec.ECC_SECG_P256K1:
1✔
422
                algorithm = hashes.SHA256()
1✔
UNCOV
423
            case KeySpec.ECC_NIST_P384:
×
UNCOV
424
                algorithm = hashes.SHA384()
×
UNCOV
425
            case KeySpec.ECC_NIST_P521:
×
UNCOV
426
                algorithm = hashes.SHA512()
×
UNCOV
427
            case _:
×
UNCOV
428
                raise InvalidKeyUsageException(
×
429
                    f"{self.metadata['Arn']} key usage is {self.metadata['KeyUsage']} which is not valid for DeriveSharedSecret."
430
                )
431

432
        # Deserialize public key from DER encoded data to EllipticCurvePublicKey.
433
        try:
1✔
434
            pub_key = load_der_public_key(public_key)
1✔
435
        except (UnsupportedAlgorithm, ValueError):
1✔
436
            raise ValidationException("")
1✔
437
        shared_secret = self.crypto_key.key.exchange(ec.ECDH(), pub_key)
1✔
438
        # Perform shared secret derivation.
439
        return HKDF(
1✔
440
            algorithm=algorithm,
441
            salt=None,
442
            info=b"",
443
            length=algorithm.digest_size,
444
            backend=default_backend(),
445
        ).derive(shared_secret)
446

447
    # This method gets called when a key is replicated to another region. It's meant to populate the required metadata
448
    # fields in a new replica key.
449
    def replicate_metadata(
1✔
450
        self, replicate_key_request: ReplicateKeyRequest, account_id: str, replica_region: str
451
    ) -> None:
452
        self.metadata["Description"] = replicate_key_request.get("Description") or ""
1✔
453
        primary_key_arn = self.metadata["Arn"]
1✔
454
        # Multi region keys have the same key ID for all replicas, but ARNs differ, as they include actual regions of
455
        # replicas.
456
        self.calculate_and_set_arn(account_id, replica_region)
1✔
457

458
        current_replica_keys = self.metadata.get("MultiRegionConfiguration", {}).get(
1✔
459
            "ReplicaKeys", []
460
        )
461
        current_replica_keys.append(MultiRegionKey(Arn=self.metadata["Arn"], Region=replica_region))
1✔
462
        primary_key_region = (
1✔
463
            self.metadata.get("MultiRegionConfiguration", {}).get("PrimaryKey", {}).get("Region")
464
        )
465

466
        self.metadata["MultiRegionConfiguration"] = MultiRegionConfiguration(
1✔
467
            MultiRegionKeyType=MultiRegionKeyType.REPLICA,
468
            PrimaryKey=MultiRegionKey(
469
                Arn=primary_key_arn,
470
                Region=primary_key_region,
471
            ),
472
            ReplicaKeys=current_replica_keys,
473
        )
474

475
    def _get_hmac_context(self, mac_algorithm: MacAlgorithmSpec) -> hmac.HMAC:
1✔
476
        if mac_algorithm == "HMAC_SHA_224":
1✔
477
            h = hmac.HMAC(self.crypto_key.key_material, hashes.SHA224())
1✔
478
        elif mac_algorithm == "HMAC_SHA_256":
1✔
479
            h = hmac.HMAC(self.crypto_key.key_material, hashes.SHA256())
1✔
480
        elif mac_algorithm == "HMAC_SHA_384":
1✔
481
            h = hmac.HMAC(self.crypto_key.key_material, hashes.SHA384())
1✔
482
        elif mac_algorithm == "HMAC_SHA_512":
1✔
483
            h = hmac.HMAC(self.crypto_key.key_material, hashes.SHA512())
1✔
484
        else:
UNCOV
485
            raise ValidationException(
×
486
                f"1 validation error detected: Value '{mac_algorithm}' at 'macAlgorithm' "
487
                f"failed to satisfy constraint: Member must satisfy enum value set: "
488
                f"[HMAC_SHA_384, HMAC_SHA_256, HMAC_SHA_224, HMAC_SHA_512]"
489
            )
490
        return h
1✔
491

492
    def _construct_sign_verify_hasher(
1✔
493
        self, signing_algorithm: SigningAlgorithmSpec, message_type: MessageType
494
    ) -> (
495
        Prehashed | hashes.SHA256 | hashes.SHA384 | hashes.SHA512,
496
        Prehashed | hashes.SHA256 | hashes.SHA384 | hashes.SHA512,
497
    ):
498
        if "SHA_256" in signing_algorithm:
1✔
499
            hasher = hashes.SHA256()
1✔
500
        elif "SHA_384" in signing_algorithm:
1✔
501
            hasher = hashes.SHA384()
1✔
502
        elif "SHA_512" in signing_algorithm:
1✔
503
            hasher = hashes.SHA512()
1✔
504
        else:
UNCOV
505
            raise ValidationException(
×
506
                f"Unsupported hash type in SigningAlgorithm '{signing_algorithm}'"
507
            )
508

509
        wrapped_hasher = hasher
1✔
510
        if message_type == MessageType.DIGEST:
1✔
511
            wrapped_hasher = utils.Prehashed(hasher)
1✔
512
        return hasher, wrapped_hasher
1✔
513

514
    def _construct_sign_verify_padding(
1✔
515
        self,
516
        signing_algorithm: SigningAlgorithmSpec,
517
        hasher: Prehashed | hashes.SHA256 | hashes.SHA384 | hashes.SHA512,
518
    ) -> PKCS1v15 | PSS:
519
        if signing_algorithm.startswith("RSA"):
1✔
520
            if "PKCS" in signing_algorithm:
1✔
521
                return padding.PKCS1v15()
1✔
522
            elif "PSS" in signing_algorithm:
1✔
523
                return padding.PSS(mgf=padding.MGF1(hasher), salt_length=padding.PSS.DIGEST_LENGTH)
1✔
524
            else:
UNCOV
525
                LOG.warning("Unsupported padding in SigningAlgorithm '%s'", signing_algorithm)
×
526

527
    # Not a comment, rather some possibly relevant links for the future.
528
    # https://docs.aws.amazon.com/kms/latest/developerguide/asymm-create-key.html
529
    # "You cannot create an elliptic curve key pair for encryption and decryption."
530
    # https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#asymmetric-keys-concept
531
    # "You can create asymmetric KMS keys that represent RSA key pairs for public key encryption or signing and
532
    # verification, or elliptic curve key pairs for signing and verification."
533
    #
534
    # A useful link with a cheat-sheet of what operations are supported by what types of keys:
535
    # https://docs.aws.amazon.com/kms/latest/developerguide/symm-asymm-compare.html
536
    #
537
    # https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-keys
538
    # "AWS KMS generates the data key. Then it encrypts a copy of the data key under a symmetric encryption KMS key that
539
    # you specify."
540
    #
541
    # Data keys are symmetric, data key pairs are asymmetric.
542
    def _populate_metadata(
1✔
543
        self, create_key_request: CreateKeyRequest, account_id: str, region: str
544
    ) -> None:
545
        self.metadata = KeyMetadata()
1✔
546
        # Metadata fields coming from a creation request
547
        #
548
        # We do not include tags into the metadata. Tags might be present in a key creation request, but our metadata
549
        # only contains data displayed by DescribeKey. And tags are not there:
550
        # https://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html
551
        # "DescribeKey does not return the following information: ... Tags on the KMS key."
552

553
        self.metadata["Description"] = create_key_request.get("Description") or ""
1✔
554
        self.metadata["MultiRegion"] = create_key_request.get("MultiRegion") or False
1✔
555
        self.metadata["Origin"] = create_key_request.get("Origin") or "AWS_KMS"
1✔
556
        # https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html#KMS-CreateKey-request-CustomerMasterKeySpec
557
        # CustomerMasterKeySpec has been deprecated, still used for compatibility. Is replaced by KeySpec.
558
        # The meaning is the same, just the name differs.
559
        self.metadata["KeySpec"] = (
1✔
560
            create_key_request.get("KeySpec")
561
            or create_key_request.get("CustomerMasterKeySpec")
562
            or "SYMMETRIC_DEFAULT"
563
        )
564
        self.metadata["CustomerMasterKeySpec"] = self.metadata.get("KeySpec")
1✔
565
        self.metadata["KeyUsage"] = self._get_key_usage(
1✔
566
            create_key_request.get("KeyUsage"), self.metadata.get("KeySpec")
567
        )
568

569
        # Metadata fields AWS introduces automatically
570
        self.metadata["AWSAccountId"] = account_id
1✔
571
        self.metadata["CreationDate"] = datetime.datetime.now()
1✔
572
        self.metadata["Enabled"] = create_key_request.get("Origin") != OriginType.EXTERNAL
1✔
573
        self.metadata["KeyManager"] = "CUSTOMER"
1✔
574
        self.metadata["KeyState"] = (
1✔
575
            KeyState.Enabled
576
            if create_key_request.get("Origin") != OriginType.EXTERNAL
577
            else KeyState.PendingImport
578
        )
579

580
        if TAG_KEY_CUSTOM_ID in self.tags:
1✔
581
            # check if the _custom_id_ tag is specified, to set a user-defined KeyId for this key
582
            self.metadata["KeyId"] = self.tags[TAG_KEY_CUSTOM_ID].strip()
1✔
583
        elif self.metadata.get("MultiRegion"):
1✔
584
            # https://docs.aws.amazon.com/kms/latest/developerguide/multi-region-keys-overview.html
585
            # "Notice that multi-Region keys have a distinctive key ID that begins with mrk-. You can use the mrk- prefix to
586
            # identify MRKs programmatically."
587
            # The ID for MultiRegion keys also do not have dashes.
588
            self.metadata["KeyId"] = "mrk-" + str(uuid.uuid4().hex)
1✔
589
        else:
590
            self.metadata["KeyId"] = str(uuid.uuid4())
1✔
591
        self.calculate_and_set_arn(account_id, region)
1✔
592

593
        self._populate_encryption_algorithms(
1✔
594
            self.metadata.get("KeyUsage"), self.metadata.get("KeySpec")
595
        )
596
        self._populate_signing_algorithms(
1✔
597
            self.metadata.get("KeyUsage"), self.metadata.get("KeySpec")
598
        )
599
        self._populate_mac_algorithms(self.metadata.get("KeyUsage"), self.metadata.get("KeySpec"))
1✔
600

601
        if self.metadata["MultiRegion"]:
1✔
602
            self.metadata["MultiRegionConfiguration"] = MultiRegionConfiguration(
1✔
603
                MultiRegionKeyType=MultiRegionKeyType.PRIMARY,
604
                PrimaryKey=MultiRegionKey(Arn=self.metadata["Arn"], Region=region),
605
                ReplicaKeys=[],
606
            )
607

608
    def add_tags(self, tags: TagList) -> None:
1✔
609
        # Just in case we get None from somewhere.
610
        if not tags:
1✔
611
            return
1✔
612

613
        unique_tag_keys = {tag["TagKey"] for tag in tags}
1✔
614
        if len(unique_tag_keys) < len(tags):
1✔
615
            raise TagException("Duplicate tag keys")
1✔
616

617
        if len(tags) > 50:
1✔
618
            raise TagException("Too many tags")
1✔
619

620
        # Do not care if we overwrite an existing tag:
621
        # https://docs.aws.amazon.com/kms/latest/APIReference/API_TagResource.html
622
        # "To edit a tag, specify an existing tag key and a new tag value."
623
        for i, tag in enumerate(tags, start=1):
1✔
624
            validate_tag(i, tag)
1✔
625
            self.tags[tag.get("TagKey")] = tag.get("TagValue")
1✔
626

627
    def schedule_key_deletion(self, pending_window_in_days: int) -> None:
1✔
628
        self.metadata["Enabled"] = False
1✔
629
        # TODO For MultiRegion keys, the status of replicas get set to "PendingDeletion", while the primary key
630
        #  becomes "PendingReplicaDeletion". Here we just set all keys to "PendingDeletion", as we do not have any
631
        #  notion of a primary key in LocalStack. Might be useful to improve it.
632
        #  https://docs.aws.amazon.com/kms/latest/developerguide/multi-region-keys-delete.html#primary-delete
633
        self.metadata["KeyState"] = "PendingDeletion"
1✔
634
        self.metadata["DeletionDate"] = datetime.datetime.now() + datetime.timedelta(
1✔
635
            days=pending_window_in_days
636
        )
637

638
    def _update_key_rotation_date(self) -> None:
1✔
639
        if not self.next_rotation_date or self.next_rotation_date < datetime.datetime.now():
1✔
640
            self.next_rotation_date = datetime.datetime.now() + datetime.timedelta(
1✔
641
                days=self.rotation_period_in_days
642
            )
643

644
    # An example of how the whole policy should look like:
645
    # https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-overview.html
646
    # The default statement is here:
647
    # https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-default.html#key-policy-default-allow-root-enable-iam
648
    def _get_default_key_policy(self, account_id: str, region: str) -> str:
1✔
649
        return json.dumps(
1✔
650
            {
651
                "Version": "2012-10-17",
652
                "Id": "key-default-1",
653
                "Statement": [
654
                    {
655
                        "Sid": "Enable IAM User Permissions",
656
                        "Effect": "Allow",
657
                        "Principal": {"AWS": f"arn:{get_partition(region)}:iam::{account_id}:root"},
658
                        "Action": "kms:*",
659
                        "Resource": "*",
660
                    }
661
                ],
662
            }
663
        )
664

665
    def _populate_encryption_algorithms(self, key_usage: str, key_spec: str) -> None:
1✔
666
        # The two main usages for KMS keys are encryption/decryption and signing/verification.
667
        # Doesn't make sense to populate fields related to encryption/decryption unless the key is created with that
668
        # goal in mind.
669
        if key_usage != "ENCRYPT_DECRYPT":
1✔
670
            return
1✔
671
        if key_spec == "SYMMETRIC_DEFAULT":
1✔
672
            self.metadata["EncryptionAlgorithms"] = ["SYMMETRIC_DEFAULT"]
1✔
673
        else:
674
            self.metadata["EncryptionAlgorithms"] = ["RSAES_OAEP_SHA_1", "RSAES_OAEP_SHA_256"]
1✔
675

676
    def _populate_signing_algorithms(self, key_usage: str, key_spec: str) -> None:
1✔
677
        # The two main usages for KMS keys are encryption/decryption and signing/verification.
678
        # Doesn't make sense to populate fields related to signing/verification unless the key is created with that
679
        # goal in mind.
680
        if key_usage != "SIGN_VERIFY":
1✔
681
            return
1✔
682
        if key_spec in ["ECC_NIST_P256", "ECC_SECG_P256K1"]:
1✔
683
            self.metadata["SigningAlgorithms"] = ["ECDSA_SHA_256"]
1✔
684
        elif key_spec == "ECC_NIST_P384":
1✔
685
            self.metadata["SigningAlgorithms"] = ["ECDSA_SHA_384"]
1✔
686
        elif key_spec == "ECC_NIST_P521":
1✔
UNCOV
687
            self.metadata["SigningAlgorithms"] = ["ECDSA_SHA_512"]
×
688
        else:
689
            self.metadata["SigningAlgorithms"] = [
1✔
690
                "RSASSA_PKCS1_V1_5_SHA_256",
691
                "RSASSA_PKCS1_V1_5_SHA_384",
692
                "RSASSA_PKCS1_V1_5_SHA_512",
693
                "RSASSA_PSS_SHA_256",
694
                "RSASSA_PSS_SHA_384",
695
                "RSASSA_PSS_SHA_512",
696
            ]
697

698
    def _populate_mac_algorithms(self, key_usage: str, key_spec: str) -> None:
1✔
699
        if key_usage != "GENERATE_VERIFY_MAC":
1✔
700
            return
1✔
701
        if key_spec == "HMAC_224":
1✔
702
            self.metadata["MacAlgorithms"] = ["HMAC_SHA_224"]
1✔
703
        elif key_spec == "HMAC_256":
1✔
704
            self.metadata["MacAlgorithms"] = ["HMAC_SHA_256"]
1✔
705
        elif key_spec == "HMAC_384":
1✔
706
            self.metadata["MacAlgorithms"] = ["HMAC_SHA_384"]
1✔
707
        elif key_spec == "HMAC_512":
1✔
708
            self.metadata["MacAlgorithms"] = ["HMAC_SHA_512"]
1✔
709

710
    def _get_key_usage(self, request_key_usage: str, key_spec: str) -> str:
1✔
711
        if key_spec in HMAC_RANGE_KEY_LENGTHS:
1✔
712
            if request_key_usage is None:
1✔
713
                raise ValidationException(
1✔
714
                    "You must specify a KeyUsage value for all KMS keys except for symmetric encryption keys."
715
                )
716
            elif request_key_usage != KeyUsageType.GENERATE_VERIFY_MAC:
1✔
717
                raise ValidationException(
1✔
718
                    f"1 validation error detected: Value '{request_key_usage}' at 'keyUsage' "
719
                    f"failed to satisfy constraint: Member must satisfy enum value set: "
720
                    f"[ENCRYPT_DECRYPT, SIGN_VERIFY, GENERATE_VERIFY_MAC]"
721
                )
722
            else:
723
                return KeyUsageType.GENERATE_VERIFY_MAC
1✔
724
        elif request_key_usage == KeyUsageType.KEY_AGREEMENT:
1✔
725
            if key_spec not in [
1✔
726
                KeySpec.ECC_NIST_P256,
727
                KeySpec.ECC_NIST_P384,
728
                KeySpec.ECC_NIST_P521,
729
                KeySpec.ECC_SECG_P256K1,
730
                KeySpec.SM2,
731
            ]:
732
                raise ValidationException(
1✔
733
                    f"KeyUsage {request_key_usage} is not compatible with KeySpec {key_spec}"
734
                )
735
            else:
736
                return request_key_usage
1✔
737
        else:
738
            return request_key_usage or "ENCRYPT_DECRYPT"
1✔
739

740
    def rotate_key_on_demand(self):
1✔
741
        if len(self.previous_keys) >= ON_DEMAND_ROTATION_LIMIT:
1✔
742
            raise LimitExceededException(
1✔
743
                f"The on-demand rotations limit has been reached for the given keyId. "
744
                f"No more on-demand rotations can be performed for this key: {self.metadata['Arn']}"
745
            )
746
        self.previous_keys.append(self.crypto_key.key_material)
1✔
747
        self.crypto_key = KmsCryptoKey(KeySpec.SYMMETRIC_DEFAULT)
1✔
748

749

750
class KmsGrant:
1✔
751
    # AWS documentation doesn't seem to mention any metadata object for grants like it does mention KeyMetadata for
752
    # keys. But, based on our understanding of AWS documentation for CreateGrant, ListGrants operations etc,
753
    # AWS has some set of fields for grants like it has for keys. So we are going to call them `metadata` here for
754
    # consistency.
755
    metadata: Dict
1✔
756
    # Tokens are not a part of metadata, as their use is more limited and specific than for the rest of the
757
    # metadata: https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#using-grant-token
758
    # Tokens are used to refer to a grant in a short period right after the grant gets created. Normally it might
759
    # take KMS up to 5 minutes to make a new grant available. In that time window referring to a grant by its
760
    # GrantId might not work, so tokens are supposed to be used. The tokens could possibly be used even
761
    # afterwards. But since the only way to get a token is through a CreateGrant operation (see below), the chances
762
    # of someone storing a token and using it later are slim.
763
    #
764
    # https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#grant_token
765
    # "CreateGrant is the only operation that returns a grant token. You cannot get a grant token from any other
766
    # AWS KMS operation or from the CloudTrail log event for the CreateGrant operation. The ListGrants and
767
    # ListRetirableGrants operations return the grant ID, but not a grant token."
768
    #
769
    # Usually a grant might have multiple unique tokens. But here we just model it with a single token for
770
    # simplicity.
771
    token: str
1✔
772

773
    def __init__(self, create_grant_request: CreateGrantRequest, account_id: str, region_name: str):
1✔
774
        self.metadata = dict(create_grant_request)
1✔
775

776
        if is_valid_key_arn(self.metadata["KeyId"]):
1✔
UNCOV
777
            self.metadata["KeyArn"] = self.metadata["KeyId"]
×
778
        else:
779
            self.metadata["KeyArn"] = kms_key_arn(self.metadata["KeyId"], account_id, region_name)
1✔
780

781
        self.metadata["GrantId"] = long_uid()
1✔
782
        self.metadata["CreationDate"] = datetime.datetime.now()
1✔
783
        # https://docs.aws.amazon.com/kms/latest/APIReference/API_GrantListEntry.html
784
        # "If a name was provided in the CreateGrant request, that name is returned. Otherwise this value is null."
785
        # According to the examples in AWS docs
786
        # https://docs.aws.amazon.com/kms/latest/APIReference/API_ListGrants.html#API_ListGrants_Examples
787
        # The Name field is present with just an empty string value.
788
        self.metadata.setdefault("Name", "")
1✔
789

790
        # Encode account ID and region in grant token.
791
        # This way the grant can be located when being retired by grant principal.
792
        # The token consists of account ID, region name and a UUID concatenated with ':' and encoded with base64
793
        decoded_token = account_id + ":" + region_name + ":" + long_uid()
1✔
794
        self.token = to_str(base64.b64encode(to_bytes(decoded_token)))
1✔
795

796

797
class KmsAlias:
1✔
798
    # Like with grants (see comment for KmsGrant), there is no mention of some specific object modeling metadata
799
    # for KMS aliases. But there is data that is some metadata, so we model it in a way similar to KeyMetadata for keys.
800
    metadata: Dict
1✔
801

802
    def __init__(
1✔
803
        self,
804
        create_alias_request: CreateAliasRequest = None,
805
        account_id: str = None,
806
        region: str = None,
807
    ):
808
        create_alias_request = create_alias_request or CreateAliasRequest()
1✔
809
        self.metadata = {}
1✔
810
        self.metadata["AliasName"] = create_alias_request.get("AliasName")
1✔
811
        self.metadata["TargetKeyId"] = create_alias_request.get("TargetKeyId")
1✔
812
        self.update_date_of_last_update()
1✔
813
        self.metadata["CreationDate"] = self.metadata["LastUpdateDate"]
1✔
814
        self.metadata["AliasArn"] = kms_alias_arn(self.metadata["AliasName"], account_id, region)
1✔
815

816
    def update_date_of_last_update(self):
1✔
817
        self.metadata["LastUpdateDate"] = datetime.datetime.now()
1✔
818

819

820
@dataclass
1✔
821
class KeyImportState:
1✔
822
    key_id: str
1✔
823
    import_token: str
1✔
824
    wrapping_algo: str
1✔
825
    key: KmsKey
1✔
826

827

828
class KmsStore(BaseStore):
1✔
829
    # maps key ids to keys
830
    keys: Dict[str, KmsKey] = LocalAttribute(default=dict)
1✔
831

832
    # According to AWS documentation on grants https://docs.aws.amazon.com/kms/latest/APIReference/API_RetireGrant.html
833
    # "Cross-account use: Yes. You can retire a grant on a KMS key in a different AWS account."
834

835
    # maps grant ids to grants
836
    grants: Dict[str, KmsGrant] = LocalAttribute(default=dict)
1✔
837

838
    # maps from (grant names (used for idempotency), key id) to grant ids
839
    grant_names: Dict[Tuple[str, str], str] = LocalAttribute(default=dict)
1✔
840

841
    # maps grant tokens to grant ids
842
    grant_tokens: Dict[str, str] = LocalAttribute(default=dict)
1✔
843

844
    # maps key alias names to aliases
845
    aliases: Dict[str, KmsAlias] = LocalAttribute(default=dict)
1✔
846

847
    # maps import tokens to import data
848
    imports: Dict[str, KeyImportState] = LocalAttribute(default=dict)
1✔
849

850

851
kms_stores = AccountRegionBundle("kms", KmsStore)
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc