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

localstack / localstack / 19690651035

25 Nov 2025 03:57PM UTC coverage: 86.873% (+0.006%) from 86.867%
19690651035

push

github

web-flow
fix(lambda): updated error messages for deployment artifacts (#13417)

0 of 3 new or added lines in 1 file covered. (0.0%)

50 existing lines in 6 files now uncovered.

68873 of 79280 relevant lines covered (86.87%)

0.87 hits per line

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

98.7
/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

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

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

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

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

65
SYMMETRIC_DEFAULT_MATERIAL_LENGTH = 32
1✔
66

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

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

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

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

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

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

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

119

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

129

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

136

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

149

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

161

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

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

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

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

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

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

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

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

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

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

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

228
        KmsCryptoKey.assert_valid(key_spec)
1✔
229

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

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

249
        self._serialize_key(key)
1✔
250

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

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

276
    @property
1✔
277
    def key(self) -> RSAPrivateKey | EllipticCurvePrivateKey:
1✔
278
        return crypto_serialization.load_der_private_key(
1✔
279
            self.private_key,
280
            password=None,
281
            backend=default_backend(),
282
        )
283

284

285
class KmsKey:
1✔
286
    metadata: KeyMetadata
1✔
287
    crypto_key: KmsCryptoKey
1✔
288
    tags: dict[str, str]
1✔
289
    policy: str
1✔
290
    is_key_rotation_enabled: bool
1✔
291
    rotation_period_in_days: int
1✔
292
    next_rotation_date: datetime.datetime
1✔
293
    previous_keys = [str]
1✔
294

295
    def __init__(
1✔
296
        self,
297
        create_key_request: CreateKeyRequest = None,
298
        account_id: str = None,
299
        region: str = None,
300
    ):
301
        create_key_request = create_key_request or CreateKeyRequest()
1✔
302
        self.previous_keys = []
1✔
303

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

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

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

340
        self.rotation_period_in_days = 365
1✔
341
        self.next_rotation_date = None
1✔
342

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

350
    def calculate_and_set_arn(self, account_id, region):
1✔
351
        self.metadata["Arn"] = kms_key_arn(self.metadata.get("KeyId"), account_id, region)
1✔
352

353
    def generate_mac(self, msg: bytes, mac_algorithm: MacAlgorithmSpec) -> bytes:
1✔
354
        h = self._get_hmac_context(mac_algorithm)
1✔
355
        h.update(msg)
1✔
356
        return h.finalize()
1✔
357

358
    def verify_mac(self, msg: bytes, mac: bytes, mac_algorithm: MacAlgorithmSpec) -> bool:
1✔
359
        h = self._get_hmac_context(mac_algorithm)
1✔
360
        h.update(msg)
1✔
361
        try:
1✔
362
            h.verify(mac)
1✔
363
            return True
1✔
364
        except InvalidSignature:
1✔
365
            raise KMSInvalidMacException()
1✔
366

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

379
    # The ciphertext has to be deserialized before this call.
380
    def decrypt(
1✔
381
        self, ciphertext: Ciphertext, encryption_context: EncryptionContextType = None
382
    ) -> bytes:
383
        aad = _serialize_encryption_context(encryption_context=encryption_context)
1✔
384
        keys_to_try = [self.crypto_key.key_material] + self.previous_keys
1✔
385

386
        for key in keys_to_try:
1✔
387
            try:
1✔
388
                return decrypt(key, ciphertext.ciphertext, ciphertext.iv, ciphertext.tag, aad)
1✔
389
            except (InvalidTag, InvalidSignature):
1✔
390
                continue
1✔
391

392
        raise InvalidCiphertextException()
1✔
393

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

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

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

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

454
        # Deserialize public key from DER encoded data to EllipticCurvePublicKey.
455
        try:
1✔
456
            pub_key = load_der_public_key(public_key)
1✔
457
        except (UnsupportedAlgorithm, ValueError):
1✔
458
            raise ValidationException("")
1✔
459
        shared_secret = self.crypto_key.key.exchange(ec.ECDH(), pub_key)
1✔
460
        return shared_secret
1✔
461

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

473
        current_replica_keys = self.metadata.get("MultiRegionConfiguration", {}).get(
1✔
474
            "ReplicaKeys", []
475
        )
476
        current_replica_keys.append(MultiRegionKey(Arn=self.metadata["Arn"], Region=replica_region))
1✔
477
        primary_key_region = (
1✔
478
            self.metadata.get("MultiRegionConfiguration", {}).get("PrimaryKey", {}).get("Region")
479
        )
480

481
        self.metadata["MultiRegionConfiguration"] = MultiRegionConfiguration(
1✔
482
            MultiRegionKeyType=MultiRegionKeyType.REPLICA,
483
            PrimaryKey=MultiRegionKey(
484
                Arn=primary_key_arn,
485
                Region=primary_key_region,
486
            ),
487
            ReplicaKeys=current_replica_keys,
488
        )
489

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

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

524
        wrapped_hasher = hasher
1✔
525
        if message_type == MessageType.DIGEST:
1✔
526
            wrapped_hasher = utils.Prehashed(hasher)
1✔
527
        return hasher, wrapped_hasher
1✔
528

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

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

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

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

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

608
        self._populate_encryption_algorithms(
1✔
609
            self.metadata.get("KeyUsage"), self.metadata.get("KeySpec")
610
        )
611
        self._populate_signing_algorithms(
1✔
612
            self.metadata.get("KeyUsage"), self.metadata.get("KeySpec")
613
        )
614
        self._populate_mac_algorithms(self.metadata.get("KeyUsage"), self.metadata.get("KeySpec"))
1✔
615

616
        if self.metadata["MultiRegion"]:
1✔
617
            self.metadata["MultiRegionConfiguration"] = MultiRegionConfiguration(
1✔
618
                MultiRegionKeyType=MultiRegionKeyType.PRIMARY,
619
                PrimaryKey=MultiRegionKey(Arn=self.metadata["Arn"], Region=region),
620
                ReplicaKeys=[],
621
            )
622

623
    def add_tags(self, tags: TagList) -> None:
1✔
624
        # Just in case we get None from somewhere.
625
        if not tags:
1✔
626
            return
1✔
627

628
        unique_tag_keys = {tag["TagKey"] for tag in tags}
1✔
629
        if len(unique_tag_keys) < len(tags):
1✔
630
            raise TagException("Duplicate tag keys")
1✔
631

632
        if len(tags) > 50:
1✔
633
            raise TagException("Too many tags")
1✔
634

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

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

653
    def _update_key_rotation_date(self) -> None:
1✔
654
        if not self.next_rotation_date or self.next_rotation_date < datetime.datetime.now():
1✔
655
            self.next_rotation_date = datetime.datetime.now() + datetime.timedelta(
1✔
656
                days=self.rotation_period_in_days
657
            )
658

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

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

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

713
    def _populate_mac_algorithms(self, key_usage: str, key_spec: str) -> None:
1✔
714
        if key_usage != "GENERATE_VERIFY_MAC":
1✔
715
            return
1✔
716
        if key_spec == "HMAC_224":
1✔
717
            self.metadata["MacAlgorithms"] = ["HMAC_SHA_224"]
1✔
718
        elif key_spec == "HMAC_256":
1✔
719
            self.metadata["MacAlgorithms"] = ["HMAC_SHA_256"]
1✔
720
        elif key_spec == "HMAC_384":
1✔
721
            self.metadata["MacAlgorithms"] = ["HMAC_SHA_384"]
1✔
722
        elif key_spec == "HMAC_512":
1✔
723
            self.metadata["MacAlgorithms"] = ["HMAC_SHA_512"]
1✔
724

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

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

764
        self.previous_keys.append(current_key_material)
1✔
765

766
        # If there is no pending material stored on the key, then key material will be generated.
767
        self.crypto_key = KmsCryptoKey(KeySpec.SYMMETRIC_DEFAULT, pending_key_material)
1✔
768
        self.metadata["CurrentKeyMaterialId"] = self.generate_key_material_id(
1✔
769
            self.crypto_key.key_material
770
        )
771

772

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

796
    def __init__(self, create_grant_request: CreateGrantRequest, account_id: str, region_name: str):
1✔
797
        self.metadata = dict(create_grant_request)
1✔
798

799
        if is_valid_key_arn(self.metadata["KeyId"]):
1✔
UNCOV
800
            self.metadata["KeyArn"] = self.metadata["KeyId"]
×
801
        else:
802
            self.metadata["KeyArn"] = kms_key_arn(self.metadata["KeyId"], account_id, region_name)
1✔
803

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

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

819

820
class KmsAlias:
1✔
821
    # Like with grants (see comment for KmsGrant), there is no mention of some specific object modeling metadata
822
    # for KMS aliases. But there is data that is some metadata, so we model it in a way similar to KeyMetadata for keys.
823
    metadata: dict
1✔
824

825
    def __init__(
1✔
826
        self,
827
        create_alias_request: CreateAliasRequest = None,
828
        account_id: str = None,
829
        region: str = None,
830
    ):
831
        create_alias_request = create_alias_request or CreateAliasRequest()
1✔
832
        self.metadata = {}
1✔
833
        self.metadata["AliasName"] = create_alias_request.get("AliasName")
1✔
834
        self.metadata["TargetKeyId"] = create_alias_request.get("TargetKeyId")
1✔
835
        self.update_date_of_last_update()
1✔
836
        self.metadata["CreationDate"] = self.metadata["LastUpdateDate"]
1✔
837
        self.metadata["AliasArn"] = kms_alias_arn(self.metadata["AliasName"], account_id, region)
1✔
838

839
    def update_date_of_last_update(self):
1✔
840
        self.metadata["LastUpdateDate"] = datetime.datetime.now()
1✔
841

842

843
@dataclass
1✔
844
class KeyImportState:
1✔
845
    key_id: str
1✔
846
    import_token: str
1✔
847
    wrapping_algo: str
1✔
848
    key: KmsKey
1✔
849

850

851
class KmsStore(BaseStore):
1✔
852
    # maps key ids to keys
853
    keys: dict[str, KmsKey] = LocalAttribute(default=dict)
1✔
854

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

858
    # maps grant ids to grants
859
    grants: dict[str, KmsGrant] = LocalAttribute(default=dict)
1✔
860

861
    # maps from (grant names (used for idempotency), key id) to grant ids
862
    grant_names: dict[tuple[str, str], str] = LocalAttribute(default=dict)
1✔
863

864
    # maps grant tokens to grant ids
865
    grant_tokens: dict[str, str] = LocalAttribute(default=dict)
1✔
866

867
    # maps key alias names to aliases
868
    aliases: dict[str, KmsAlias] = LocalAttribute(default=dict)
1✔
869

870
    # maps import tokens to import data
871
    imports: dict[str, KeyImportState] = LocalAttribute(default=dict)
1✔
872

873

874
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