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

localstack / localstack / 22334798432

23 Feb 2026 06:42PM UTC coverage: 86.956% (-0.02%) from 86.973%
22334798432

push

github

web-flow
S3: regenerate test snapshots & parity fixes (#13824)

69831 of 80306 relevant lines covered (86.96%)

0.87 hits per line

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

98.64
/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
    UnsupportedOperationException,
49
)
50
from localstack.services.kms.exceptions import ValidationException
1✔
51
from localstack.services.kms.utils import is_valid_key_arn
1✔
52
from localstack.services.stores import AccountRegionBundle, BaseStore, LocalAttribute
1✔
53
from localstack.utils.aws.arns import get_partition, kms_alias_arn, kms_key_arn
1✔
54
from localstack.utils.crypto import decrypt, encrypt
1✔
55
from localstack.utils.strings import long_uid, to_bytes, to_str
1✔
56
from localstack.utils.tagging import Tags
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

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

126

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

133

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

146

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

158

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

169
    public_key: bytes | None
1✔
170
    private_key: bytes | None
1✔
171
    key_material: bytes | None
1✔
172
    pending_key_material: bytes | None
1✔
173
    key_spec: str
1✔
174

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

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

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

194
        if key_spec == "SYMMETRIC_DEFAULT":
1✔
195
            return
1✔
196

197
        if key_spec.startswith("RSA"):
1✔
198
            if key_spec not in RSA_CRYPTO_KEY_LENGTHS:
1✔
199
                raise_validation()
1✔
200
            return
1✔
201

202
        if key_spec.startswith("ECC"):
1✔
203
            if key_spec not in ECC_CURVES:
1✔
204
                raise_validation()
1✔
205
            return
1✔
206

207
        if key_spec.startswith("HMAC"):
1✔
208
            if key_spec not in HMAC_RANGE_KEY_LENGTHS:
1✔
209
                raise_validation()
1✔
210
            return
1✔
211

212
        raise UnsupportedOperationException(f"KeySpec {key_spec} is not supported")
1✔
213

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

225
        KmsCryptoKey.assert_valid(key_spec)
1✔
226

227
        if key_spec == "SYMMETRIC_DEFAULT":
1✔
228
            return
1✔
229

230
        if key_spec.startswith("RSA"):
1✔
231
            key_size = RSA_CRYPTO_KEY_LENGTHS.get(key_spec)
1✔
232
            if key_material:
1✔
233
                key = crypto_serialization.load_der_private_key(key_material, password=None)
1✔
234
            else:
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
    policy: str
1✔
289
    is_key_rotation_enabled: bool
1✔
290
    rotation_period_in_days: int
1✔
291
    next_rotation_date: datetime.datetime | None
1✔
292
    previous_keys: list[bytes | None]
1✔
293
    _internal_key_id: uuid.UUID
1✔
294

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

306
        # Policy 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, custom_key_id=custom_key_id)
1✔
316
        self.crypto_key = KmsCryptoKey(self.metadata.get("KeySpec"), custom_key_material)
1✔
317
        self._internal_key_id = uuid.uuid4()
1✔
318

319
        # The KMS implementation always provides a crypto key with key material which doesn't suit scenarios where a
320
        # KMS Key may have no key material e.g. for external keys. Don't expose the CurrentKeyMaterialId in those cases.
321
        if custom_key_material or (
1✔
322
            self.metadata["Origin"] == "AWS_KMS"
323
            and self.metadata["KeySpec"] == KeySpec.SYMMETRIC_DEFAULT
324
        ):
325
            self.metadata["CurrentKeyMaterialId"] = self.generate_key_material_id(
1✔
326
                self.crypto_key.key_material
327
            )
328

329
        self.rotation_period_in_days = 365
1✔
330
        self.next_rotation_date = None
1✔
331

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

339
    def calculate_and_set_arn(self, account_id, region):
1✔
340
        self.metadata["Arn"] = kms_key_arn(self.metadata.get("KeyId"), account_id, region)
1✔
341

342
    def generate_mac(self, msg: bytes, mac_algorithm: MacAlgorithmSpec) -> bytes:
1✔
343
        h = self._get_hmac_context(mac_algorithm)
1✔
344
        h.update(msg)
1✔
345
        return h.finalize()
1✔
346

347
    def verify_mac(self, msg: bytes, mac: bytes, mac_algorithm: MacAlgorithmSpec) -> bool:
1✔
348
        h = self._get_hmac_context(mac_algorithm)
1✔
349
        h.update(msg)
1✔
350
        try:
1✔
351
            h.verify(mac)
1✔
352
            return True
1✔
353
        except InvalidSignature:
1✔
354
            raise KMSInvalidMacException()
1✔
355

356
    # Encrypt is a method of KmsKey and not of KmsCryptoKey only because it requires KeyId, and KmsCryptoKeys do not
357
    # hold KeyIds. Maybe it would be possible to remodel this better.
358
    def encrypt(self, plaintext: bytes, encryption_context: EncryptionContextType = None) -> bytes:
1✔
359
        iv = os.urandom(IV_LEN)
1✔
360
        aad = _serialize_encryption_context(encryption_context=encryption_context)
1✔
361
        ciphertext, tag = encrypt(self.crypto_key.key_material, plaintext, iv, aad)
1✔
362
        return _serialize_ciphertext_blob(
1✔
363
            ciphertext=Ciphertext(
364
                key_id=self.metadata.get("KeyId"), iv=iv, ciphertext=ciphertext, tag=tag
365
            )
366
        )
367

368
    # The ciphertext has to be deserialized before this call.
369
    def decrypt(
1✔
370
        self, ciphertext: Ciphertext, encryption_context: EncryptionContextType = None
371
    ) -> bytes:
372
        aad = _serialize_encryption_context(encryption_context=encryption_context)
1✔
373
        keys_to_try = [self.crypto_key.key_material] + self.previous_keys
1✔
374

375
        for key in keys_to_try:
1✔
376
            try:
1✔
377
                return decrypt(key, ciphertext.ciphertext, ciphertext.iv, ciphertext.tag, aad)
1✔
378
            except (InvalidTag, InvalidSignature):
1✔
379
                continue
1✔
380

381
        raise InvalidCiphertextException()
1✔
382

383
    def decrypt_rsa(self, encrypted: bytes) -> bytes:
1✔
384
        private_key = crypto_serialization.load_der_private_key(
1✔
385
            self.crypto_key.private_key, password=None, backend=default_backend()
386
        )
387
        decrypted = private_key.decrypt(
1✔
388
            encrypted,
389
            padding.OAEP(
390
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
391
                algorithm=hashes.SHA256(),
392
                label=None,
393
            ),
394
        )
395
        return decrypted
1✔
396

397
    def sign(
1✔
398
        self, data: bytes, message_type: MessageType, signing_algorithm: SigningAlgorithmSpec
399
    ) -> bytes:
400
        hasher, wrapped_hasher = self._construct_sign_verify_hasher(signing_algorithm, message_type)
1✔
401
        try:
1✔
402
            if signing_algorithm.startswith("ECDSA"):
1✔
403
                return self.crypto_key.key.sign(data, ec.ECDSA(wrapped_hasher))
1✔
404
            else:
405
                padding = self._construct_sign_verify_padding(signing_algorithm, hasher)
1✔
406
                return self.crypto_key.key.sign(data, padding, wrapped_hasher)
1✔
407
        except ValueError as exc:
1✔
408
            raise ValidationException(str(exc))
1✔
409

410
    def verify(
1✔
411
        self,
412
        data: bytes,
413
        message_type: MessageType,
414
        signing_algorithm: SigningAlgorithmSpec,
415
        signature: bytes,
416
    ) -> bool:
417
        hasher, wrapped_hasher = self._construct_sign_verify_hasher(signing_algorithm, message_type)
1✔
418
        try:
1✔
419
            if signing_algorithm.startswith("ECDSA"):
1✔
420
                self.crypto_key.key.public_key().verify(signature, data, ec.ECDSA(wrapped_hasher))
1✔
421
            else:
422
                padding = self._construct_sign_verify_padding(signing_algorithm, hasher)
1✔
423
                self.crypto_key.key.public_key().verify(signature, data, padding, wrapped_hasher)
1✔
424
            return True
1✔
425
        except ValueError as exc:
1✔
426
            raise ValidationException(str(exc))
1✔
427
        except InvalidSignature:
1✔
428
            # AWS itself raises this exception without any additional message.
429
            raise KMSInvalidSignatureException()
1✔
430

431
    def derive_shared_secret(self, public_key: bytes) -> bytes:
1✔
432
        key_spec = self.metadata.get("KeySpec")
1✔
433
        if key_spec not in (
1✔
434
            KeySpec.ECC_NIST_P256,
435
            KeySpec.ECC_SECG_P256K1,
436
            KeySpec.ECC_NIST_P384,
437
            KeySpec.ECC_NIST_P521,
438
        ):
439
            raise InvalidKeyUsageException(
×
440
                f"{self.metadata['Arn']} key usage is {self.metadata['KeyUsage']} which is not valid for DeriveSharedSecret."
441
            )
442

443
        # Deserialize public key from DER encoded data to EllipticCurvePublicKey.
444
        try:
1✔
445
            pub_key = load_der_public_key(public_key)
1✔
446
        except (UnsupportedAlgorithm, ValueError):
1✔
447
            raise ValidationException("")
1✔
448
        shared_secret = self.crypto_key.key.exchange(ec.ECDH(), pub_key)
1✔
449
        return shared_secret
1✔
450

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

462
        current_replica_keys = self.metadata.get("MultiRegionConfiguration", {}).get(
1✔
463
            "ReplicaKeys", []
464
        )
465
        current_replica_keys.append(MultiRegionKey(Arn=self.metadata["Arn"], Region=replica_region))
1✔
466
        primary_key_region = (
1✔
467
            self.metadata.get("MultiRegionConfiguration", {}).get("PrimaryKey", {}).get("Region")
468
        )
469

470
        self.metadata["MultiRegionConfiguration"] = MultiRegionConfiguration(
1✔
471
            MultiRegionKeyType=MultiRegionKeyType.REPLICA,
472
            PrimaryKey=MultiRegionKey(
473
                Arn=primary_key_arn,
474
                Region=primary_key_region,
475
            ),
476
            ReplicaKeys=current_replica_keys,
477
        )
478

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

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

513
        wrapped_hasher = hasher
1✔
514
        if message_type == MessageType.DIGEST:
1✔
515
            wrapped_hasher = utils.Prehashed(hasher)
1✔
516
        return hasher, wrapped_hasher
1✔
517

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

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

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

577
        # Metadata fields AWS introduces automatically
578
        self.metadata["AWSAccountId"] = account_id
1✔
579
        self.metadata["CreationDate"] = datetime.datetime.now()
1✔
580
        self.metadata["Enabled"] = create_key_request.get("Origin") != OriginType.EXTERNAL
1✔
581
        self.metadata["KeyManager"] = "CUSTOMER"
1✔
582
        self.metadata["KeyState"] = (
1✔
583
            KeyState.Enabled
584
            if create_key_request.get("Origin") != OriginType.EXTERNAL
585
            else KeyState.PendingImport
586
        )
587

588
        if custom_key_id:
1✔
589
            self.metadata["KeyId"] = custom_key_id
1✔
590
        elif self.metadata.get("MultiRegion"):
1✔
591
            # https://docs.aws.amazon.com/kms/latest/developerguide/multi-region-keys-overview.html
592
            # "Notice that multi-Region keys have a distinctive key ID that begins with mrk-. You can use the mrk- prefix to
593
            # identify MRKs programmatically."
594
            # The ID for MultiRegion keys also do not have dashes.
595
            self.metadata["KeyId"] = "mrk-" + str(uuid.uuid4().hex)
1✔
596
        else:
597
            self.metadata["KeyId"] = str(uuid.uuid4())
1✔
598
        self.calculate_and_set_arn(account_id, region)
1✔
599

600
        self._populate_encryption_algorithms(
1✔
601
            self.metadata.get("KeyUsage"), self.metadata.get("KeySpec")
602
        )
603
        self._populate_signing_algorithms(
1✔
604
            self.metadata.get("KeyUsage"), self.metadata.get("KeySpec")
605
        )
606
        self._populate_mac_algorithms(self.metadata.get("KeyUsage"), self.metadata.get("KeySpec"))
1✔
607

608
        if self.metadata["MultiRegion"]:
1✔
609
            self.metadata["MultiRegionConfiguration"] = MultiRegionConfiguration(
1✔
610
                MultiRegionKeyType=MultiRegionKeyType.PRIMARY,
611
                PrimaryKey=MultiRegionKey(Arn=self.metadata["Arn"], Region=region),
612
                ReplicaKeys=[],
613
            )
614

615
    def schedule_key_deletion(self, pending_window_in_days: int) -> None:
1✔
616
        self.metadata["Enabled"] = False
1✔
617
        # TODO For MultiRegion keys, the status of replicas get set to "PendingDeletion", while the primary key
618
        #  becomes "PendingReplicaDeletion". Here we just set all keys to "PendingDeletion", as we do not have any
619
        #  notion of a primary key in LocalStack. Might be useful to improve it.
620
        #  https://docs.aws.amazon.com/kms/latest/developerguide/multi-region-keys-delete.html#primary-delete
621
        self.metadata["KeyState"] = "PendingDeletion"
1✔
622
        self.metadata["DeletionDate"] = datetime.datetime.now() + datetime.timedelta(
1✔
623
            days=pending_window_in_days
624
        )
625

626
    def _update_key_rotation_date(self) -> None:
1✔
627
        if not self.next_rotation_date or self.next_rotation_date < datetime.datetime.now():
1✔
628
            self.next_rotation_date = datetime.datetime.now() + datetime.timedelta(
1✔
629
                days=self.rotation_period_in_days
630
            )
631

632
    # An example of how the whole policy should look like:
633
    # https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-overview.html
634
    # The default statement is here:
635
    # https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-default.html#key-policy-default-allow-root-enable-iam
636
    def _get_default_key_policy(self, account_id: str, region: str) -> str:
1✔
637
        return json.dumps(
1✔
638
            {
639
                "Version": "2012-10-17",
640
                "Id": "key-default-1",
641
                "Statement": [
642
                    {
643
                        "Sid": "Enable IAM User Permissions",
644
                        "Effect": "Allow",
645
                        "Principal": {"AWS": f"arn:{get_partition(region)}:iam::{account_id}:root"},
646
                        "Action": "kms:*",
647
                        "Resource": "*",
648
                    }
649
                ],
650
            }
651
        )
652

653
    def _populate_encryption_algorithms(self, key_usage: str, key_spec: str) -> None:
1✔
654
        # The two main usages for KMS keys are encryption/decryption and signing/verification.
655
        # Doesn't make sense to populate fields related to encryption/decryption unless the key is created with that
656
        # goal in mind.
657
        if key_usage != "ENCRYPT_DECRYPT":
1✔
658
            return
1✔
659
        if key_spec == "SYMMETRIC_DEFAULT":
1✔
660
            self.metadata["EncryptionAlgorithms"] = ["SYMMETRIC_DEFAULT"]
1✔
661
        else:
662
            self.metadata["EncryptionAlgorithms"] = ["RSAES_OAEP_SHA_1", "RSAES_OAEP_SHA_256"]
1✔
663

664
    def _populate_signing_algorithms(self, key_usage: str, key_spec: str) -> None:
1✔
665
        # The two main usages for KMS keys are encryption/decryption and signing/verification.
666
        # Doesn't make sense to populate fields related to signing/verification unless the key is created with that
667
        # goal in mind.
668
        if key_usage != "SIGN_VERIFY":
1✔
669
            return
1✔
670
        if key_spec in ["ECC_NIST_P256", "ECC_SECG_P256K1"]:
1✔
671
            self.metadata["SigningAlgorithms"] = ["ECDSA_SHA_256"]
1✔
672
        elif key_spec == "ECC_NIST_P384":
1✔
673
            self.metadata["SigningAlgorithms"] = ["ECDSA_SHA_384"]
1✔
674
        elif key_spec == "ECC_NIST_P521":
1✔
675
            self.metadata["SigningAlgorithms"] = ["ECDSA_SHA_512"]
1✔
676
        else:
677
            self.metadata["SigningAlgorithms"] = [
1✔
678
                "RSASSA_PKCS1_V1_5_SHA_256",
679
                "RSASSA_PKCS1_V1_5_SHA_384",
680
                "RSASSA_PKCS1_V1_5_SHA_512",
681
                "RSASSA_PSS_SHA_256",
682
                "RSASSA_PSS_SHA_384",
683
                "RSASSA_PSS_SHA_512",
684
            ]
685

686
    def _populate_mac_algorithms(self, key_usage: str, key_spec: str) -> None:
1✔
687
        if key_usage != "GENERATE_VERIFY_MAC":
1✔
688
            return
1✔
689
        if key_spec == "HMAC_224":
1✔
690
            self.metadata["MacAlgorithms"] = ["HMAC_SHA_224"]
1✔
691
        elif key_spec == "HMAC_256":
1✔
692
            self.metadata["MacAlgorithms"] = ["HMAC_SHA_256"]
1✔
693
        elif key_spec == "HMAC_384":
1✔
694
            self.metadata["MacAlgorithms"] = ["HMAC_SHA_384"]
1✔
695
        elif key_spec == "HMAC_512":
1✔
696
            self.metadata["MacAlgorithms"] = ["HMAC_SHA_512"]
1✔
697

698
    def _get_key_usage(self, request_key_usage: str, key_spec: str) -> str:
1✔
699
        if key_spec in HMAC_RANGE_KEY_LENGTHS:
1✔
700
            if request_key_usage is None:
1✔
701
                raise ValidationException(
1✔
702
                    "You must specify a KeyUsage value for all KMS keys except for symmetric encryption keys."
703
                )
704
            elif request_key_usage != KeyUsageType.GENERATE_VERIFY_MAC:
1✔
705
                raise ValidationException(
1✔
706
                    f"1 validation error detected: Value '{request_key_usage}' at 'keyUsage' "
707
                    f"failed to satisfy constraint: Member must satisfy enum value set: "
708
                    f"[ENCRYPT_DECRYPT, SIGN_VERIFY, GENERATE_VERIFY_MAC]"
709
                )
710
            else:
711
                return KeyUsageType.GENERATE_VERIFY_MAC
1✔
712
        elif request_key_usage == KeyUsageType.KEY_AGREEMENT:
1✔
713
            if key_spec not in [
1✔
714
                KeySpec.ECC_NIST_P256,
715
                KeySpec.ECC_NIST_P384,
716
                KeySpec.ECC_NIST_P521,
717
                KeySpec.ECC_SECG_P256K1,
718
                KeySpec.SM2,
719
            ]:
720
                raise ValidationException(
1✔
721
                    f"KeyUsage {request_key_usage} is not compatible with KeySpec {key_spec}"
722
                )
723
            else:
724
                return request_key_usage
1✔
725
        else:
726
            return request_key_usage or "ENCRYPT_DECRYPT"
1✔
727

728
    def rotate_key_on_demand(self):
1✔
729
        if len(self.previous_keys) >= ON_DEMAND_ROTATION_LIMIT:
1✔
730
            raise LimitExceededException(
1✔
731
                f"The on-demand rotations limit has been reached for the given keyId. "
732
                f"No more on-demand rotations can be performed for this key: {self.metadata['Arn']}"
733
            )
734
        current_key_material = self.crypto_key.key_material
1✔
735
        pending_key_material = self.crypto_key.pending_key_material
1✔
736

737
        self.previous_keys.append(current_key_material)
1✔
738

739
        # If there is no pending material stored on the key, then key material will be generated.
740
        self.crypto_key = KmsCryptoKey(KeySpec.SYMMETRIC_DEFAULT, pending_key_material)
1✔
741
        self.metadata["CurrentKeyMaterialId"] = self.generate_key_material_id(
1✔
742
            self.crypto_key.key_material
743
        )
744

745

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

769
    def __init__(self, create_grant_request: CreateGrantRequest, account_id: str, region_name: str):
1✔
770
        self.metadata = dict(create_grant_request)
1✔
771

772
        if is_valid_key_arn(self.metadata["KeyId"]):
1✔
773
            self.metadata["KeyArn"] = self.metadata["KeyId"]
×
774
        else:
775
            self.metadata["KeyArn"] = kms_key_arn(self.metadata["KeyId"], account_id, region_name)
1✔
776

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

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

792

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

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

813
    def update_date_of_last_update(self):
1✔
814
        self.metadata["LastUpdateDate"] = datetime.datetime.now()
1✔
815

816

817
@dataclass
1✔
818
class KeyImportState:
1✔
819
    key_id: str
1✔
820
    import_token: str
1✔
821
    wrapping_algo: str
1✔
822
    key: KmsKey
1✔
823

824

825
class KmsStore(BaseStore):
1✔
826
    # maps key ids to keys
827
    keys: dict[str, KmsKey] = LocalAttribute(default=dict)
1✔
828

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

832
    # maps grant ids to grants
833
    # TODO: KmsKey might hold the grant
834
    grants: dict[str, KmsGrant] = LocalAttribute(default=dict)
1✔
835

836
    # maps grant tokens to grant ids
837
    grant_tokens: dict[str, str] = LocalAttribute(default=dict)
1✔
838

839
    # maps key alias names to aliases
840
    aliases: dict[str, KmsAlias] = LocalAttribute(default=dict)
1✔
841

842
    # maps import tokens to import data
843
    imports: dict[str, KeyImportState] = LocalAttribute(default=dict)
1✔
844

845
    # maps key arn to tags
846
    tags: Tags = LocalAttribute(default=Tags)
1✔
847

848

849
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