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

localstack / localstack / 20514610129

23 Dec 2025 06:23PM UTC coverage: 86.914% (-0.005%) from 86.919%
20514610129

push

github

web-flow
Fix KMS model annotations (#13563)

2 of 2 new or added lines in 1 file covered. (100.0%)

11 existing lines in 3 files now uncovered.

70049 of 80596 relevant lines covered (86.91%)

0.87 hits per line

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

98.71
/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 typing
1✔
11
import uuid
1✔
12
from collections import namedtuple
1✔
13
from dataclasses import dataclass
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.serialization import load_der_public_key
1✔
25

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

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

61
PATTERN_UUID = re.compile(
1✔
62
    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}$"
63
)
64
MULTI_REGION_PATTERN = re.compile(r"^mrk-[a-fA-F0-9]{32}$")
1✔
65

66
SYMMETRIC_DEFAULT_MATERIAL_LENGTH = 32
1✔
67

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

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

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

88
ON_DEMAND_ROTATION_LIMIT = 10
1✔
89
KEY_ID_LEN = 36
1✔
90
# 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.
91
IV_LEN = 16
1✔
92
TAG_LEN = 16
1✔
93
CIPHERTEXT_HEADER_FORMAT = f">{KEY_ID_LEN}s{IV_LEN}s{TAG_LEN}s"
1✔
94
HEADER_LEN = KEY_ID_LEN + IV_LEN + TAG_LEN
1✔
95
Ciphertext = namedtuple("Ciphertext", ("key_id", "iv", "ciphertext", "tag"))
1✔
96

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

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

117
# special tag name to allow specifying a custom key material for created keys
118
TAG_KEY_CUSTOM_KEY_MATERIAL = "_custom_key_material_"
1✔
119

120

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

130

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

137

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

150

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

162

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

173
    public_key: bytes | None
1✔
174
    private_key: bytes | None
1✔
175
    key_material: bytes
1✔
176
    pending_key_material: bytes | None
1✔
177
    key_spec: str
1✔
178

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

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

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

198
        if key_spec == "SYMMETRIC_DEFAULT":
1✔
199
            return
1✔
200

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

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

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

216
        raise UnsupportedOperationException(f"KeySpec {key_spec} is not supported")
1✔
217

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

229
        KmsCryptoKey.assert_valid(key_spec)
1✔
230

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

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

253
        self._serialize_key(key)
1✔
254

255
    def load_key_material(self, material: bytes):
1✔
256
        if self.key_spec == KeySpec.SYMMETRIC_DEFAULT:
1✔
257
            self.pending_key_material = material
1✔
258
        elif self.key_spec in [
1✔
259
            KeySpec.HMAC_224,
260
            KeySpec.HMAC_256,
261
            KeySpec.HMAC_384,
262
            KeySpec.HMAC_512,
263
        ]:
264
            self.key_material = material
1✔
265
        else:
266
            key = crypto_serialization.load_der_private_key(material, password=None)
1✔
267
            self._serialize_key(key)
1✔
268

269
    def _serialize_key(self, key: ec.EllipticCurvePrivateKey | rsa.RSAPrivateKey):
1✔
270
        self.public_key = key.public_key().public_bytes(
1✔
271
            crypto_serialization.Encoding.DER,
272
            crypto_serialization.PublicFormat.SubjectPublicKeyInfo,
273
        )
274
        self.private_key = key.private_bytes(
1✔
275
            crypto_serialization.Encoding.DER,
276
            crypto_serialization.PrivateFormat.PKCS8,
277
            crypto_serialization.NoEncryption(),
278
        )
279

280
    @property
1✔
281
    def key(self) -> RSAPrivateKey | EllipticCurvePrivateKey:
1✔
282
        return crypto_serialization.load_der_private_key(
1✔
283
            self.private_key,
284
            password=None,
285
            backend=default_backend(),
286
        )
287

288

289
class KmsKey:
1✔
290
    metadata: KeyMetadata
1✔
291
    crypto_key: KmsCryptoKey
1✔
292
    tags: dict[str, str]
1✔
293
    policy: str
1✔
294
    is_key_rotation_enabled: bool
1✔
295
    rotation_period_in_days: int
1✔
296
    next_rotation_date: datetime.datetime | None
1✔
297
    previous_keys: list[str]
1✔
298
    _internal_key_id: uuid.UUID
1✔
299

300
    def __init__(
1✔
301
        self,
302
        create_key_request: CreateKeyRequest = None,
303
        account_id: str = None,
304
        region: str = None,
305
    ):
306
        create_key_request = create_key_request or CreateKeyRequest()
1✔
307
        self.previous_keys = []
1✔
308

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

325
        self._populate_metadata(create_key_request, account_id, region)
1✔
326
        custom_key_material = None
1✔
327
        if TAG_KEY_CUSTOM_KEY_MATERIAL in self.tags:
1✔
328
            # check if the _custom_key_material_ tag is specified, to use a custom key material for this key
329
            custom_key_material = base64.b64decode(self.tags[TAG_KEY_CUSTOM_KEY_MATERIAL])
1✔
330
            # remove the _custom_key_material_ tag from the tags to not readily expose the custom key material
331
            del self.tags[TAG_KEY_CUSTOM_KEY_MATERIAL]
1✔
332
        self.crypto_key = KmsCryptoKey(self.metadata.get("KeySpec"), custom_key_material)
1✔
333
        self._internal_key_id = uuid.uuid4()
1✔
334

335
        # The KMS implementation always provides a crypto key with key material which doesn't suit scenarios where a
336
        # KMS Key may have no key material e.g. for external keys. Don't expose the CurrentKeyMaterialId in those cases.
337
        if custom_key_material or (
1✔
338
            self.metadata["Origin"] == "AWS_KMS"
339
            and self.metadata["KeySpec"] == KeySpec.SYMMETRIC_DEFAULT
340
        ):
341
            self.metadata["CurrentKeyMaterialId"] = self.generate_key_material_id(
1✔
342
                self.crypto_key.key_material
343
            )
344

345
        self.rotation_period_in_days = 365
1✔
346
        self.next_rotation_date = None
1✔
347

348
    def generate_key_material_id(self, key_material: bytes) -> str:
1✔
349
        # The KeyMaterialId depends on the key material and the KeyId. Use an internal ID to prevent brute forcing
350
        # the value of the key material from the public KeyId and KeyMaterialId.
351
        # https://docs.aws.amazon.com/kms/latest/APIReference/API_ImportKeyMaterial.html
352
        key_material_id_hex = uuid.uuid5(self._internal_key_id, key_material).hex
1✔
353
        return str(key_material_id_hex) * 2
1✔
354

355
    def calculate_and_set_arn(self, account_id, region):
1✔
356
        self.metadata["Arn"] = kms_key_arn(self.metadata.get("KeyId"), account_id, region)
1✔
357

358
    def generate_mac(self, msg: bytes, mac_algorithm: MacAlgorithmSpec) -> bytes:
1✔
359
        h = self._get_hmac_context(mac_algorithm)
1✔
360
        h.update(msg)
1✔
361
        return h.finalize()
1✔
362

363
    def verify_mac(self, msg: bytes, mac: bytes, mac_algorithm: MacAlgorithmSpec) -> bool:
1✔
364
        h = self._get_hmac_context(mac_algorithm)
1✔
365
        h.update(msg)
1✔
366
        try:
1✔
367
            h.verify(mac)
1✔
368
            return True
1✔
369
        except InvalidSignature:
1✔
370
            raise KMSInvalidMacException()
1✔
371

372
    # Encrypt is a method of KmsKey and not of KmsCryptoKey only because it requires KeyId, and KmsCryptoKeys do not
373
    # hold KeyIds. Maybe it would be possible to remodel this better.
374
    def encrypt(self, plaintext: bytes, encryption_context: EncryptionContextType = None) -> bytes:
1✔
375
        iv = os.urandom(IV_LEN)
1✔
376
        aad = _serialize_encryption_context(encryption_context=encryption_context)
1✔
377
        ciphertext, tag = encrypt(self.crypto_key.key_material, plaintext, iv, aad)
1✔
378
        return _serialize_ciphertext_blob(
1✔
379
            ciphertext=Ciphertext(
380
                key_id=self.metadata.get("KeyId"), iv=iv, ciphertext=ciphertext, tag=tag
381
            )
382
        )
383

384
    # The ciphertext has to be deserialized before this call.
385
    def decrypt(
1✔
386
        self, ciphertext: Ciphertext, encryption_context: EncryptionContextType = None
387
    ) -> bytes:
388
        aad = _serialize_encryption_context(encryption_context=encryption_context)
1✔
389
        keys_to_try = [self.crypto_key.key_material] + self.previous_keys
1✔
390

391
        for key in keys_to_try:
1✔
392
            try:
1✔
393
                return decrypt(key, ciphertext.ciphertext, ciphertext.iv, ciphertext.tag, aad)
1✔
394
            except (InvalidTag, InvalidSignature):
1✔
395
                continue
1✔
396

397
        raise InvalidCiphertextException()
1✔
398

399
    def decrypt_rsa(self, encrypted: bytes) -> bytes:
1✔
400
        private_key = crypto_serialization.load_der_private_key(
1✔
401
            self.crypto_key.private_key, password=None, backend=default_backend()
402
        )
403
        decrypted = private_key.decrypt(
1✔
404
            encrypted,
405
            padding.OAEP(
406
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
407
                algorithm=hashes.SHA256(),
408
                label=None,
409
            ),
410
        )
411
        return decrypted
1✔
412

413
    def sign(
1✔
414
        self, data: bytes, message_type: MessageType, signing_algorithm: SigningAlgorithmSpec
415
    ) -> bytes:
416
        hasher, wrapped_hasher = self._construct_sign_verify_hasher(signing_algorithm, message_type)
1✔
417
        try:
1✔
418
            if signing_algorithm.startswith("ECDSA"):
1✔
419
                return self.crypto_key.key.sign(data, ec.ECDSA(wrapped_hasher))
1✔
420
            else:
421
                padding = self._construct_sign_verify_padding(signing_algorithm, hasher)
1✔
422
                return self.crypto_key.key.sign(data, padding, wrapped_hasher)
1✔
423
        except ValueError as exc:
1✔
424
            raise ValidationException(str(exc))
1✔
425

426
    def verify(
1✔
427
        self,
428
        data: bytes,
429
        message_type: MessageType,
430
        signing_algorithm: SigningAlgorithmSpec,
431
        signature: bytes,
432
    ) -> bool:
433
        hasher, wrapped_hasher = self._construct_sign_verify_hasher(signing_algorithm, message_type)
1✔
434
        try:
1✔
435
            if signing_algorithm.startswith("ECDSA"):
1✔
436
                self.crypto_key.key.public_key().verify(signature, data, ec.ECDSA(wrapped_hasher))
1✔
437
            else:
438
                padding = self._construct_sign_verify_padding(signing_algorithm, hasher)
1✔
439
                self.crypto_key.key.public_key().verify(signature, data, padding, wrapped_hasher)
1✔
440
            return True
1✔
441
        except ValueError as exc:
1✔
442
            raise ValidationException(str(exc))
1✔
443
        except InvalidSignature:
1✔
444
            # AWS itself raises this exception without any additional message.
445
            raise KMSInvalidSignatureException()
1✔
446

447
    def derive_shared_secret(self, public_key: bytes) -> bytes:
1✔
448
        key_spec = self.metadata.get("KeySpec")
1✔
449
        if key_spec not in (
1✔
450
            KeySpec.ECC_NIST_P256,
451
            KeySpec.ECC_SECG_P256K1,
452
            KeySpec.ECC_NIST_P384,
453
            KeySpec.ECC_NIST_P521,
454
        ):
UNCOV
455
            raise InvalidKeyUsageException(
×
456
                f"{self.metadata['Arn']} key usage is {self.metadata['KeyUsage']} which is not valid for DeriveSharedSecret."
457
            )
458

459
        # Deserialize public key from DER encoded data to EllipticCurvePublicKey.
460
        try:
1✔
461
            pub_key = load_der_public_key(public_key)
1✔
462
        except (UnsupportedAlgorithm, ValueError):
1✔
463
            raise ValidationException("")
1✔
464
        shared_secret = self.crypto_key.key.exchange(ec.ECDH(), pub_key)
1✔
465
        return shared_secret
1✔
466

467
    # This method gets called when a key is replicated to another region. It's meant to populate the required metadata
468
    # fields in a new replica key.
469
    def replicate_metadata(
1✔
470
        self, replicate_key_request: ReplicateKeyRequest, account_id: str, replica_region: str
471
    ) -> None:
472
        self.metadata["Description"] = replicate_key_request.get("Description") or ""
1✔
473
        primary_key_arn = self.metadata["Arn"]
1✔
474
        # Multi region keys have the same key ID for all replicas, but ARNs differ, as they include actual regions of
475
        # replicas.
476
        self.calculate_and_set_arn(account_id, replica_region)
1✔
477

478
        current_replica_keys = self.metadata.get("MultiRegionConfiguration", {}).get(
1✔
479
            "ReplicaKeys", []
480
        )
481
        current_replica_keys.append(MultiRegionKey(Arn=self.metadata["Arn"], Region=replica_region))
1✔
482
        primary_key_region = (
1✔
483
            self.metadata.get("MultiRegionConfiguration", {}).get("PrimaryKey", {}).get("Region")
484
        )
485

486
        self.metadata["MultiRegionConfiguration"] = MultiRegionConfiguration(
1✔
487
            MultiRegionKeyType=MultiRegionKeyType.REPLICA,
488
            PrimaryKey=MultiRegionKey(
489
                Arn=primary_key_arn,
490
                Region=primary_key_region,
491
            ),
492
            ReplicaKeys=current_replica_keys,
493
        )
494

495
    def _get_hmac_context(self, mac_algorithm: MacAlgorithmSpec) -> hmac.HMAC:
1✔
496
        if mac_algorithm == "HMAC_SHA_224":
1✔
497
            h = hmac.HMAC(self.crypto_key.key_material, hashes.SHA224())
1✔
498
        elif mac_algorithm == "HMAC_SHA_256":
1✔
499
            h = hmac.HMAC(self.crypto_key.key_material, hashes.SHA256())
1✔
500
        elif mac_algorithm == "HMAC_SHA_384":
1✔
501
            h = hmac.HMAC(self.crypto_key.key_material, hashes.SHA384())
1✔
502
        elif mac_algorithm == "HMAC_SHA_512":
1✔
503
            h = hmac.HMAC(self.crypto_key.key_material, hashes.SHA512())
1✔
504
        else:
UNCOV
505
            raise ValidationException(
×
506
                f"1 validation error detected: Value '{mac_algorithm}' at 'macAlgorithm' "
507
                f"failed to satisfy constraint: Member must satisfy enum value set: "
508
                f"[HMAC_SHA_384, HMAC_SHA_256, HMAC_SHA_224, HMAC_SHA_512]"
509
            )
510
        return h
1✔
511

512
    def _construct_sign_verify_hasher(
1✔
513
        self, signing_algorithm: SigningAlgorithmSpec, message_type: MessageType
514
    ) -> (
515
        Prehashed | hashes.SHA256 | hashes.SHA384 | hashes.SHA512,
516
        Prehashed | hashes.SHA256 | hashes.SHA384 | hashes.SHA512,
517
    ):
518
        if "SHA_256" in signing_algorithm:
1✔
519
            hasher = hashes.SHA256()
1✔
520
        elif "SHA_384" in signing_algorithm:
1✔
521
            hasher = hashes.SHA384()
1✔
522
        elif "SHA_512" in signing_algorithm:
1✔
523
            hasher = hashes.SHA512()
1✔
524
        else:
UNCOV
525
            raise ValidationException(
×
526
                f"Unsupported hash type in SigningAlgorithm '{signing_algorithm}'"
527
            )
528

529
        wrapped_hasher = hasher
1✔
530
        if message_type == MessageType.DIGEST:
1✔
531
            wrapped_hasher = utils.Prehashed(hasher)
1✔
532
        return hasher, wrapped_hasher
1✔
533

534
    def _construct_sign_verify_padding(
1✔
535
        self,
536
        signing_algorithm: SigningAlgorithmSpec,
537
        hasher: Prehashed | hashes.SHA256 | hashes.SHA384 | hashes.SHA512,
538
    ) -> PKCS1v15 | PSS:
539
        if signing_algorithm.startswith("RSA"):
1✔
540
            if "PKCS" in signing_algorithm:
1✔
541
                return padding.PKCS1v15()
1✔
542
            elif "PSS" in signing_algorithm:
1✔
543
                return padding.PSS(mgf=padding.MGF1(hasher), salt_length=padding.PSS.DIGEST_LENGTH)
1✔
544
            else:
UNCOV
545
                LOG.warning("Unsupported padding in SigningAlgorithm '%s'", signing_algorithm)
×
546

547
    # Not a comment, rather some possibly relevant links for the future.
548
    # https://docs.aws.amazon.com/kms/latest/developerguide/asymm-create-key.html
549
    # "You cannot create an elliptic curve key pair for encryption and decryption."
550
    # https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#asymmetric-keys-concept
551
    # "You can create asymmetric KMS keys that represent RSA key pairs for public key encryption or signing and
552
    # verification, or elliptic curve key pairs for signing and verification."
553
    #
554
    # A useful link with a cheat-sheet of what operations are supported by what types of keys:
555
    # https://docs.aws.amazon.com/kms/latest/developerguide/symm-asymm-compare.html
556
    #
557
    # https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-keys
558
    # "AWS KMS generates the data key. Then it encrypts a copy of the data key under a symmetric encryption KMS key that
559
    # you specify."
560
    #
561
    # Data keys are symmetric, data key pairs are asymmetric.
562
    def _populate_metadata(
1✔
563
        self, create_key_request: CreateKeyRequest, account_id: str, region: str
564
    ) -> None:
565
        self.metadata = KeyMetadata()
1✔
566
        # Metadata fields coming from a creation request
567
        #
568
        # We do not include tags into the metadata. Tags might be present in a key creation request, but our metadata
569
        # only contains data displayed by DescribeKey. And tags are not there:
570
        # https://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html
571
        # "DescribeKey does not return the following information: ... Tags on the KMS key."
572

573
        self.metadata["Description"] = create_key_request.get("Description") or ""
1✔
574
        self.metadata["MultiRegion"] = create_key_request.get("MultiRegion") or False
1✔
575
        self.metadata["Origin"] = create_key_request.get("Origin") or "AWS_KMS"
1✔
576
        # https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html#KMS-CreateKey-request-CustomerMasterKeySpec
577
        # CustomerMasterKeySpec has been deprecated, still used for compatibility. Is replaced by KeySpec.
578
        # The meaning is the same, just the name differs.
579
        self.metadata["KeySpec"] = (
1✔
580
            create_key_request.get("KeySpec")
581
            or create_key_request.get("CustomerMasterKeySpec")
582
            or "SYMMETRIC_DEFAULT"
583
        )
584
        self.metadata["CustomerMasterKeySpec"] = self.metadata.get("KeySpec")
1✔
585
        self.metadata["KeyUsage"] = self._get_key_usage(
1✔
586
            create_key_request.get("KeyUsage"), self.metadata.get("KeySpec")
587
        )
588

589
        # Metadata fields AWS introduces automatically
590
        self.metadata["AWSAccountId"] = account_id
1✔
591
        self.metadata["CreationDate"] = datetime.datetime.now()
1✔
592
        self.metadata["Enabled"] = create_key_request.get("Origin") != OriginType.EXTERNAL
1✔
593
        self.metadata["KeyManager"] = "CUSTOMER"
1✔
594
        self.metadata["KeyState"] = (
1✔
595
            KeyState.Enabled
596
            if create_key_request.get("Origin") != OriginType.EXTERNAL
597
            else KeyState.PendingImport
598
        )
599

600
        if TAG_KEY_CUSTOM_ID in self.tags:
1✔
601
            # check if the _custom_id_ tag is specified, to set a user-defined KeyId for this key
602
            self.metadata["KeyId"] = self.tags[TAG_KEY_CUSTOM_ID].strip()
1✔
603
        elif self.metadata.get("MultiRegion"):
1✔
604
            # https://docs.aws.amazon.com/kms/latest/developerguide/multi-region-keys-overview.html
605
            # "Notice that multi-Region keys have a distinctive key ID that begins with mrk-. You can use the mrk- prefix to
606
            # identify MRKs programmatically."
607
            # The ID for MultiRegion keys also do not have dashes.
608
            self.metadata["KeyId"] = "mrk-" + str(uuid.uuid4().hex)
1✔
609
        else:
610
            self.metadata["KeyId"] = str(uuid.uuid4())
1✔
611
        self.calculate_and_set_arn(account_id, region)
1✔
612

613
        self._populate_encryption_algorithms(
1✔
614
            self.metadata.get("KeyUsage"), self.metadata.get("KeySpec")
615
        )
616
        self._populate_signing_algorithms(
1✔
617
            self.metadata.get("KeyUsage"), self.metadata.get("KeySpec")
618
        )
619
        self._populate_mac_algorithms(self.metadata.get("KeyUsage"), self.metadata.get("KeySpec"))
1✔
620

621
        if self.metadata["MultiRegion"]:
1✔
622
            self.metadata["MultiRegionConfiguration"] = MultiRegionConfiguration(
1✔
623
                MultiRegionKeyType=MultiRegionKeyType.PRIMARY,
624
                PrimaryKey=MultiRegionKey(Arn=self.metadata["Arn"], Region=region),
625
                ReplicaKeys=[],
626
            )
627

628
    def add_tags(self, tags: TagList) -> None:
1✔
629
        # Just in case we get None from somewhere.
630
        if not tags:
1✔
631
            return
1✔
632

633
        unique_tag_keys = {tag["TagKey"] for tag in tags}
1✔
634
        if len(unique_tag_keys) < len(tags):
1✔
635
            raise TagException("Duplicate tag keys")
1✔
636

637
        if len(tags) > 50:
1✔
638
            raise TagException("Too many tags")
1✔
639

640
        # Do not care if we overwrite an existing tag:
641
        # https://docs.aws.amazon.com/kms/latest/APIReference/API_TagResource.html
642
        # "To edit a tag, specify an existing tag key and a new tag value."
643
        for i, tag in enumerate(tags, start=1):
1✔
644
            if tag.get("TagKey") != TAG_KEY_CUSTOM_KEY_MATERIAL:
1✔
645
                validate_tag(i, tag)
1✔
646
            self.tags[tag.get("TagKey")] = tag.get("TagValue")
1✔
647

648
    def schedule_key_deletion(self, pending_window_in_days: int) -> None:
1✔
649
        self.metadata["Enabled"] = False
1✔
650
        # TODO For MultiRegion keys, the status of replicas get set to "PendingDeletion", while the primary key
651
        #  becomes "PendingReplicaDeletion". Here we just set all keys to "PendingDeletion", as we do not have any
652
        #  notion of a primary key in LocalStack. Might be useful to improve it.
653
        #  https://docs.aws.amazon.com/kms/latest/developerguide/multi-region-keys-delete.html#primary-delete
654
        self.metadata["KeyState"] = "PendingDeletion"
1✔
655
        self.metadata["DeletionDate"] = datetime.datetime.now() + datetime.timedelta(
1✔
656
            days=pending_window_in_days
657
        )
658

659
    def _update_key_rotation_date(self) -> None:
1✔
660
        if not self.next_rotation_date or self.next_rotation_date < datetime.datetime.now():
1✔
661
            self.next_rotation_date = datetime.datetime.now() + datetime.timedelta(
1✔
662
                days=self.rotation_period_in_days
663
            )
664

665
    # An example of how the whole policy should look like:
666
    # https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-overview.html
667
    # The default statement is here:
668
    # https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-default.html#key-policy-default-allow-root-enable-iam
669
    def _get_default_key_policy(self, account_id: str, region: str) -> str:
1✔
670
        return json.dumps(
1✔
671
            {
672
                "Version": "2012-10-17",
673
                "Id": "key-default-1",
674
                "Statement": [
675
                    {
676
                        "Sid": "Enable IAM User Permissions",
677
                        "Effect": "Allow",
678
                        "Principal": {"AWS": f"arn:{get_partition(region)}:iam::{account_id}:root"},
679
                        "Action": "kms:*",
680
                        "Resource": "*",
681
                    }
682
                ],
683
            }
684
        )
685

686
    def _populate_encryption_algorithms(self, key_usage: str, key_spec: str) -> None:
1✔
687
        # The two main usages for KMS keys are encryption/decryption and signing/verification.
688
        # Doesn't make sense to populate fields related to encryption/decryption unless the key is created with that
689
        # goal in mind.
690
        if key_usage != "ENCRYPT_DECRYPT":
1✔
691
            return
1✔
692
        if key_spec == "SYMMETRIC_DEFAULT":
1✔
693
            self.metadata["EncryptionAlgorithms"] = ["SYMMETRIC_DEFAULT"]
1✔
694
        else:
695
            self.metadata["EncryptionAlgorithms"] = ["RSAES_OAEP_SHA_1", "RSAES_OAEP_SHA_256"]
1✔
696

697
    def _populate_signing_algorithms(self, key_usage: str, key_spec: str) -> None:
1✔
698
        # The two main usages for KMS keys are encryption/decryption and signing/verification.
699
        # Doesn't make sense to populate fields related to signing/verification unless the key is created with that
700
        # goal in mind.
701
        if key_usage != "SIGN_VERIFY":
1✔
702
            return
1✔
703
        if key_spec in ["ECC_NIST_P256", "ECC_SECG_P256K1"]:
1✔
704
            self.metadata["SigningAlgorithms"] = ["ECDSA_SHA_256"]
1✔
705
        elif key_spec == "ECC_NIST_P384":
1✔
706
            self.metadata["SigningAlgorithms"] = ["ECDSA_SHA_384"]
1✔
707
        elif key_spec == "ECC_NIST_P521":
1✔
708
            self.metadata["SigningAlgorithms"] = ["ECDSA_SHA_512"]
1✔
709
        else:
710
            self.metadata["SigningAlgorithms"] = [
1✔
711
                "RSASSA_PKCS1_V1_5_SHA_256",
712
                "RSASSA_PKCS1_V1_5_SHA_384",
713
                "RSASSA_PKCS1_V1_5_SHA_512",
714
                "RSASSA_PSS_SHA_256",
715
                "RSASSA_PSS_SHA_384",
716
                "RSASSA_PSS_SHA_512",
717
            ]
718

719
    def _populate_mac_algorithms(self, key_usage: str, key_spec: str) -> None:
1✔
720
        if key_usage != "GENERATE_VERIFY_MAC":
1✔
721
            return
1✔
722
        if key_spec == "HMAC_224":
1✔
723
            self.metadata["MacAlgorithms"] = ["HMAC_SHA_224"]
1✔
724
        elif key_spec == "HMAC_256":
1✔
725
            self.metadata["MacAlgorithms"] = ["HMAC_SHA_256"]
1✔
726
        elif key_spec == "HMAC_384":
1✔
727
            self.metadata["MacAlgorithms"] = ["HMAC_SHA_384"]
1✔
728
        elif key_spec == "HMAC_512":
1✔
729
            self.metadata["MacAlgorithms"] = ["HMAC_SHA_512"]
1✔
730

731
    def _get_key_usage(self, request_key_usage: str, key_spec: str) -> str:
1✔
732
        if key_spec in HMAC_RANGE_KEY_LENGTHS:
1✔
733
            if request_key_usage is None:
1✔
734
                raise ValidationException(
1✔
735
                    "You must specify a KeyUsage value for all KMS keys except for symmetric encryption keys."
736
                )
737
            elif request_key_usage != KeyUsageType.GENERATE_VERIFY_MAC:
1✔
738
                raise ValidationException(
1✔
739
                    f"1 validation error detected: Value '{request_key_usage}' at 'keyUsage' "
740
                    f"failed to satisfy constraint: Member must satisfy enum value set: "
741
                    f"[ENCRYPT_DECRYPT, SIGN_VERIFY, GENERATE_VERIFY_MAC]"
742
                )
743
            else:
744
                return KeyUsageType.GENERATE_VERIFY_MAC
1✔
745
        elif request_key_usage == KeyUsageType.KEY_AGREEMENT:
1✔
746
            if key_spec not in [
1✔
747
                KeySpec.ECC_NIST_P256,
748
                KeySpec.ECC_NIST_P384,
749
                KeySpec.ECC_NIST_P521,
750
                KeySpec.ECC_SECG_P256K1,
751
                KeySpec.SM2,
752
            ]:
753
                raise ValidationException(
1✔
754
                    f"KeyUsage {request_key_usage} is not compatible with KeySpec {key_spec}"
755
                )
756
            else:
757
                return request_key_usage
1✔
758
        else:
759
            return request_key_usage or "ENCRYPT_DECRYPT"
1✔
760

761
    def rotate_key_on_demand(self):
1✔
762
        if len(self.previous_keys) >= ON_DEMAND_ROTATION_LIMIT:
1✔
763
            raise LimitExceededException(
1✔
764
                f"The on-demand rotations limit has been reached for the given keyId. "
765
                f"No more on-demand rotations can be performed for this key: {self.metadata['Arn']}"
766
            )
767
        current_key_material = self.crypto_key.key_material
1✔
768
        pending_key_material = self.crypto_key.pending_key_material
1✔
769

770
        self.previous_keys.append(current_key_material)
1✔
771

772
        # If there is no pending material stored on the key, then key material will be generated.
773
        self.crypto_key = KmsCryptoKey(KeySpec.SYMMETRIC_DEFAULT, pending_key_material)
1✔
774
        self.metadata["CurrentKeyMaterialId"] = self.generate_key_material_id(
1✔
775
            self.crypto_key.key_material
776
        )
777

778

779
class KmsGrant:
1✔
780
    # AWS documentation doesn't seem to mention any metadata object for grants like it does mention KeyMetadata for
781
    # keys. But, based on our understanding of AWS documentation for CreateGrant, ListGrants operations etc,
782
    # AWS has some set of fields for grants like it has for keys. So we are going to call them `metadata` here for
783
    # consistency.
784
    metadata: dict[str, typing.Any]  # dumped to JSON for persistence serialization
1✔
785
    # Tokens are not a part of metadata, as their use is more limited and specific than for the rest of the
786
    # metadata: https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#using-grant-token
787
    # Tokens are used to refer to a grant in a short period right after the grant gets created. Normally it might
788
    # take KMS up to 5 minutes to make a new grant available. In that time window referring to a grant by its
789
    # GrantId might not work, so tokens are supposed to be used. The tokens could possibly be used even
790
    # afterwards. But since the only way to get a token is through a CreateGrant operation (see below), the chances
791
    # of someone storing a token and using it later are slim.
792
    #
793
    # https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#grant_token
794
    # "CreateGrant is the only operation that returns a grant token. You cannot get a grant token from any other
795
    # AWS KMS operation or from the CloudTrail log event for the CreateGrant operation. The ListGrants and
796
    # ListRetirableGrants operations return the grant ID, but not a grant token."
797
    #
798
    # Usually a grant might have multiple unique tokens. But here we just model it with a single token for
799
    # simplicity.
800
    token: str
1✔
801

802
    def __init__(self, create_grant_request: CreateGrantRequest, account_id: str, region_name: str):
1✔
803
        self.metadata = dict(create_grant_request)
1✔
804

805
        if is_valid_key_arn(self.metadata["KeyId"]):
1✔
UNCOV
806
            self.metadata["KeyArn"] = self.metadata["KeyId"]
×
807
        else:
808
            self.metadata["KeyArn"] = kms_key_arn(self.metadata["KeyId"], account_id, region_name)
1✔
809

810
        self.metadata["GrantId"] = long_uid()
1✔
811
        self.metadata["CreationDate"] = datetime.datetime.now()
1✔
812
        # https://docs.aws.amazon.com/kms/latest/APIReference/API_GrantListEntry.html
813
        # "If a name was provided in the CreateGrant request, that name is returned. Otherwise this value is null."
814
        # According to the examples in AWS docs
815
        # https://docs.aws.amazon.com/kms/latest/APIReference/API_ListGrants.html#API_ListGrants_Examples
816
        # The Name field is present with just an empty string value.
817
        self.metadata.setdefault("Name", "")
1✔
818

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

825

826
class KmsAlias:
1✔
827
    # Like with grants (see comment for KmsGrant), there is no mention of some specific object modeling metadata
828
    # for KMS aliases. But there is data that is some metadata, so we model it in a way similar to KeyMetadata for keys.
829
    metadata: dict[str, typing.Any]  # dumped to JSON for persistence serialization
1✔
830

831
    def __init__(
1✔
832
        self,
833
        create_alias_request: CreateAliasRequest | None = None,
834
        account_id: str | None = None,
835
        region: str | None = None,
836
    ):
837
        create_alias_request = create_alias_request or CreateAliasRequest()
1✔
838
        self.metadata = {
1✔
839
            "AliasName": create_alias_request.get("AliasName"),
840
            "TargetKeyId": create_alias_request.get("TargetKeyId"),
841
        }
842
        self.update_date_of_last_update()
1✔
843
        self.metadata["CreationDate"] = self.metadata["LastUpdateDate"]
1✔
844
        self.metadata["AliasArn"] = kms_alias_arn(self.metadata["AliasName"], account_id, region)
1✔
845

846
    def update_date_of_last_update(self):
1✔
847
        self.metadata["LastUpdateDate"] = datetime.datetime.now()
1✔
848

849

850
@dataclass
1✔
851
class KeyImportState:
1✔
852
    key_id: str
1✔
853
    import_token: str
1✔
854
    wrapping_algo: str
1✔
855
    key: KmsKey
1✔
856

857

858
class KmsStore(BaseStore):
1✔
859
    # maps key ids to keys
860
    keys: dict[str, KmsKey] = LocalAttribute(default=dict)
1✔
861

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

865
    # maps grant ids to grants
866
    # TODO: KmsKey might hold the grant
867
    grants: dict[str, KmsGrant] = LocalAttribute(default=dict)
1✔
868

869
    # maps grant tokens to grant ids
870
    grant_tokens: dict[str, str] = LocalAttribute(default=dict)
1✔
871

872
    # maps key alias names to aliases
873
    aliases: dict[str, KmsAlias] = LocalAttribute(default=dict)
1✔
874

875
    # maps import tokens to import data
876
    imports: dict[str, KeyImportState] = LocalAttribute(default=dict)
1✔
877

878

879
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