Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
Add KMS service (#82)
Luke Duttond82e9f2843d4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 67062439..86cafde8 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -31,7 +31,7 @@ jobs:cache: "pip"- name: Install dependencies- run: pip install -r requirements.txt boto3 pytest duckdb docker cbor2 pyyaml+ run: pip install -r requirements.txt boto3 pytest duckdb docker cbor2 pyyaml cryptography- name: Start MiniStackrun: |diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 433f987c..9b24f840 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,13 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [Unreleased]++### Added+- **KMS service** — CreateKey (RSA_2048, RSA_4096, SYMMETRIC_DEFAULT), ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateDataKey, GenerateDataKeyWithoutPlaintext. In-memory key storage with RSA signing via the `cryptography` package (optional dependency, guarded import). Supports JWT signing flows and S3 SSE-KMS encryption patterns.++---+## [1.1.22] — 2026-04-03### Addeddiff --git a/README.md b/README.mdindex f6d5deac..243c7670 100644--- a/README.md+++ b/README.md@@ -225,6 +225,8 @@ subnet = ec2.create_subnet(| **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost`; resource tree with `{param}` and `{proxy+}` path matching; JSON Patch for all PATCH operations; state persistence || **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, RegisterTargets, DeregisterTargets, DescribeTargetHealth, AddTags, RemoveTags, DescribeTags | Control plane + data plane; ALB→Lambda live traffic routing; `path-pattern`, `host-header`, `http-method`, `query-string`, `http-header` rule conditions; `forward`, `redirect`, `fixed-response` actions; data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix |+| **KMS** | CreateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateDataKey, GenerateDataKeyWithoutPlaintext | RSA (2048/4096) and symmetric keys; PKCS1v15 and PSS signing; envelope encryption; requires `cryptography` package (optional) |+### CloudFormation| Feature | Details |@@ -513,7 +515,7 @@ Layers that ship npm packages work too — MiniStack resolves the `nodejs/node_m│ │ Athena Firehose Route53 │ ││ │ Cognito EC2 EMR EBS EFS │ ││ │ ALB/ELBv2 ACM WAF v2 │ │- │ │ CloudFormation │ │+ │ │ CloudFormation KMS │ ││ └────────────────────────────────────┘ ││ ││ In-Memory Storage + Optional Docker │@@ -667,6 +669,7 @@ See [`examples/java-testcontainers`](examples/java-testcontainers) and [`example| **SES v2** | ✅ | ✅ | ✅ || **WAF v2** | ✅ | Paid | ✅ || **CloudFormation** | **partial** | partial | ✅ Free |+| **KMS** | ✅ | Paid | ✅ Free || Cost | **Free** | Was free, now paid | $35+/mo || Docker image size | ~150MB | ~1GB | ~1GB || Memory at idle | ~30MB | ~500MB | ~500MB |diff --git a/ministack/app.py b/ministack/app.pyindex 1cb573c0..1c553612 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -52,6 +52,7 @@ from ministack.services import (firehose,glue,kinesis,+ kms,lambda_svc,rds,route53,@@ -108,6 +109,7 @@ SERVICE_HANDLERS = {"elasticmapreduce": emr.handle_request,"elasticloadbalancing": alb.handle_request,"elasticfilesystem": efs.handle_request,+ "kms": kms.handle_request,}SERVICE_NAME_ALIASES = {@@ -160,7 +162,7 @@ BANNER = r"""Services: S3, SQS, SNS, DynamoDB, Lambda, IAM, STS, SecretsManager, CloudWatch Logs,SSM, EventBridge, Kinesis, CloudWatch, SES, SES v2, ACM, WAF v2, Step Functions,ECS, RDS, ElastiCache, Glue, Athena, API Gateway, Firehose, Route53,- Cognito, EC2, EMR, EBS, EFS, ALB/ELBv2, CloudFormation+ Cognito, EC2, EMR, EBS, EFS, ALB/ELBv2, CloudFormation, KMS"""@@ -600,6 +602,7 @@ def _reset_all_state():(waf, waf.reset),(efs, efs.reset),(cloudformation, cloudformation.reset),+ (kms, kms.reset),]:try:fn()diff --git a/ministack/core/router.py b/ministack/core/router.pyindex 346f64d3..f8dc03e9 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -148,6 +148,10 @@ SERVICE_PATTERNS = {"cloudformation": {"host_patterns": [r"cloudformation\."],},+ "kms": {+ "target_prefixes": ["TrentService"],+ "host_patterns": [r"kms\."],+ },}@@ -196,6 +200,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"elasticloadbalancing": "elasticloadbalancing","elasticfilesystem": "elasticfilesystem","cloudformation": "cloudformation",+ "kms": "kms",}if svc_name in scope_map:return scope_map[svc_name]diff --git a/ministack/services/kms.py b/ministack/services/kms.pynew file mode 100644index 00000000..42331263--- /dev/null+++ b/ministack/services/kms.py@@ -0,0 +1,577 @@+"""+KMS (Key Management Service) Emulator.+JSON-based API via X-Amz-Target (prefix: TrentService).+Supports: CreateKey, ListKeys, DescribeKey, Sign, Verify,+ Encrypt, Decrypt, GenerateDataKey,+ GenerateDataKeyWithoutPlaintext.+"""++import base64+import hashlib+import json+import logging+import os+import time++from ministack.core.responses import error_response_json, json_response, new_uuid++logger = logging.getLogger("kms")++try:+ from cryptography.exceptions import InvalidSignature+ from cryptography.hazmat.primitives import hashes, serialization+ from cryptography.hazmat.primitives.asymmetric import padding, rsa, utils+ HAS_CRYPTO = True+except ImportError:+ InvalidSignature = Exception+ HAS_CRYPTO = False+ logger.warning(+ "cryptography package not installed; "+ "KMS Sign/Verify will return errors. "+ "Install with: pip install cryptography"+ )++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++_keys: dict = {}+# key_id -> {+# KeyId, Arn, KeyState, KeyUsage, KeySpec, Description,+# CreationDate, Enabled, Origin,+# _private_key (rsa private key object, RSA only),+# _public_key_der (bytes, RSA only),+# _symmetric_key (bytes, SYMMETRIC_DEFAULT only),+# }+++def _arn(key_id):+ return f"arn:aws:kms:{REGION}:{ACCOUNT_ID}:key/{key_id}"+++def _key_metadata(rec):+ return {+ "KeyId": rec["KeyId"],+ "Arn": rec["Arn"],+ "CreationDate": rec["CreationDate"],+ "Enabled": rec["Enabled"],+ "Description": rec.get("Description", ""),+ "KeyUsage": rec["KeyUsage"],+ "KeyState": rec["KeyState"],+ "Origin": rec["Origin"],+ "KeyManager": "CUSTOMER",+ "CustomerMasterKeySpec": rec["KeySpec"],+ "KeySpec": rec["KeySpec"],+ "EncryptionAlgorithms": rec.get("EncryptionAlgorithms", []),+ "SigningAlgorithms": rec.get("SigningAlgorithms", []),+ }+++def _resolve_key(key_id_or_arn):+ if not key_id_or_arn:+ return None+ if key_id_or_arn in _keys:+ return _keys[key_id_or_arn]+ for rec in _keys.values():+ if rec["Arn"] == key_id_or_arn:+ return rec+ return None+++def _require_crypto(operation):+ if not HAS_CRYPTO:+ return error_response_json(+ "KMSInternalException",+ f"{operation} requires the cryptography package. "+ "Install with: pip install cryptography",+ 500,+ )+ return None+++# ---- Operations ----+++def _create_key(data):+ key_id = new_uuid()+ key_spec = data.get("KeySpec", data.get("CustomerMasterKeySpec", "SYMMETRIC_DEFAULT"))+ key_usage = data.get("KeyUsage", "ENCRYPT_DECRYPT")+ description = data.get("Description", "")++ rec = {+ "KeyId": key_id,+ "Arn": _arn(key_id),+ "KeyState": "Enabled",+ "Enabled": True,+ "KeySpec": key_spec,+ "KeyUsage": key_usage,+ "Description": description,+ "CreationDate": time.time(),+ "Origin": "AWS_KMS",+ }++ if key_spec == "SYMMETRIC_DEFAULT":+ rec["_symmetric_key"] = os.urandom(32)+ rec["EncryptionAlgorithms"] = ["SYMMETRIC_DEFAULT"]+ rec["SigningAlgorithms"] = []+ elif key_spec in ("RSA_2048", "RSA_4096"):+ err = _require_crypto("CreateKey")+ if err:+ return err+ bits = 2048 if key_spec == "RSA_2048" else 4096+ private_key = rsa.generate_private_key(+ public_exponent=65537, key_size=bits+ )+ rec["_private_key"] = private_key+ rec["_public_key_der"] = private_key.public_key().public_bytes(+ serialization.Encoding.DER,+ serialization.PublicFormat.SubjectPublicKeyInfo,+ )+ if key_usage == "SIGN_VERIFY":+ rec["SigningAlgorithms"] = [+ "RSASSA_PKCS1_V1_5_SHA_256",+ "RSASSA_PKCS1_V1_5_SHA_384",+ "RSASSA_PKCS1_V1_5_SHA_512",+ "RSASSA_PSS_SHA_256",+ "RSASSA_PSS_SHA_384",+ "RSASSA_PSS_SHA_512",+ ]+ rec["EncryptionAlgorithms"] = []+ else:+ rec["EncryptionAlgorithms"] = [+ "RSAES_OAEP_SHA_1",+ "RSAES_OAEP_SHA_256",+ ]+ rec["SigningAlgorithms"] = []+ else:+ return error_response_json(+ "UnsupportedOperationException",+ f"KeySpec {key_spec} is not supported in this emulator",+ 400,+ )++ _keys[key_id] = rec+ logger.info("Created key %s (%s, %s)", key_id, key_spec, key_usage)+ return json_response({"KeyMetadata": _key_metadata(rec)})+++def _list_keys(data):+ limit = data.get("Limit", 1000)+ keys = [{"KeyId": r["KeyId"], "KeyArn": r["Arn"]} for r in _keys.values()]+ return json_response({+ "Keys": keys[:limit],+ "Truncated": len(keys) > limit,+ })+++def _describe_key(data):+ key_id = data.get("KeyId", "")+ rec = _resolve_key(key_id)+ if not rec:+ return error_response_json("NotFoundException", f"Key {key_id} not found", 400)+ return json_response({"KeyMetadata": _key_metadata(rec)})+++def _get_public_key(data):+ key_id = data.get("KeyId", "")+ rec = _resolve_key(key_id)+ if not rec:+ return error_response_json("NotFoundException", f"Key {key_id} not found", 400)+ if "_public_key_der" not in rec:+ return error_response_json(+ "UnsupportedOperationException",+ "GetPublicKey is only valid for asymmetric keys",+ 400,+ )+ return json_response({+ "KeyId": rec["KeyId"],+ "KeyUsage": rec["KeyUsage"],+ "KeySpec": rec["KeySpec"],+ "PublicKey": base64.b64encode(rec["_public_key_der"]).decode(),+ "SigningAlgorithms": rec.get("SigningAlgorithms", []),+ "EncryptionAlgorithms": rec.get("EncryptionAlgorithms", []),+ })+++def _sign(data):+ err = _require_crypto("Sign")+ if err:+ return err++ key_id = data.get("KeyId", "")+ rec = _resolve_key(key_id)+ if not rec:+ return error_response_json("NotFoundException", f"Key {key_id} not found", 400)+ if "_private_key" not in rec:+ return error_response_json(+ "UnsupportedOperationException",+ "Sign is only valid for asymmetric SIGN_VERIFY keys",+ 400,+ )++ message_b64 = data.get("Message", "")+ message_type = data.get("MessageType", "RAW")+ algorithm = data.get("SigningAlgorithm", "RSASSA_PKCS1_V1_5_SHA_256")++ if isinstance(message_b64, str):+ message = base64.b64decode(message_b64)+ else:+ message = message_b64++ pad, hash_algo = _signing_params(algorithm)+ if pad is None:+ return error_response_json(+ "UnsupportedOperationException",+ f"Signing algorithm {algorithm} is not supported",+ 400,+ )++ if message_type == "DIGEST":+ signature = rec["_private_key"].sign(+ message, pad, utils.Prehashed(hash_algo)+ )+ else:+ signature = rec["_private_key"].sign(message, pad, hash_algo)++ logger.debug("Signed %d bytes with key %s (%s)", len(message), key_id, algorithm)+ return json_response({+ "KeyId": rec["KeyId"],+ "Signature": base64.b64encode(signature).decode(),+ "SigningAlgorithm": algorithm,+ })+++def _verify(data):+ err = _require_crypto("Verify")+ if err:+ return err++ key_id = data.get("KeyId", "")+ rec = _resolve_key(key_id)+ if not rec:+ return error_response_json("NotFoundException", f"Key {key_id} not found", 400)+ if "_private_key" not in rec:+ return error_response_json(+ "UnsupportedOperationException",+ "Verify is only valid for asymmetric SIGN_VERIFY keys",+ 400,+ )++ message_b64 = data.get("Message", "")+ message_type = data.get("MessageType", "RAW")+ signature_b64 = data.get("Signature", "")+ algorithm = data.get("SigningAlgorithm", "RSASSA_PKCS1_V1_5_SHA_256")++ message = base64.b64decode(message_b64) if isinstance(message_b64, str) else message_b64+ signature = base64.b64decode(signature_b64) if isinstance(signature_b64, str) else signature_b64++ pad, hash_algo = _signing_params(algorithm, for_verify=True)+ if pad is None:+ return error_response_json(+ "UnsupportedOperationException",+ f"Signing algorithm {algorithm} is not supported",+ 400,+ )++ public_key = rec["_private_key"].public_key()+ try:+ if message_type == "DIGEST":+ public_key.verify(signature, message, pad, utils.Prehashed(hash_algo))+ else:+ public_key.verify(signature, message, pad, hash_algo)+ valid = True+ except InvalidSignature:+ valid = False++ return json_response({+ "KeyId": rec["KeyId"],+ "SignatureValid": valid,+ "SigningAlgorithm": algorithm,+ })+++def _signing_params(algorithm, for_verify=False):+ """Return (padding, hash_algorithm) for a signing algorithm."""+ if not HAS_CRYPTO:+ return None, None++ # PSS salt_length must be MAX_LENGTH for signing, AUTO for verification+ pss_salt = padding.PSS.AUTO if for_verify else padding.PSS.MAX_LENGTH++ algo_map = {+ "RSASSA_PKCS1_V1_5_SHA_256": (padding.PKCS1v15(), hashes.SHA256()),+ "RSASSA_PKCS1_V1_5_SHA_384": (padding.PKCS1v15(), hashes.SHA384()),+ "RSASSA_PKCS1_V1_5_SHA_512": (padding.PKCS1v15(), hashes.SHA512()),+ "RSASSA_PSS_SHA_256": (+ padding.PSS(+ mgf=padding.MGF1(hashes.SHA256()),+ salt_length=pss_salt,+ ),+ hashes.SHA256(),+ ),+ "RSASSA_PSS_SHA_384": (+ padding.PSS(+ mgf=padding.MGF1(hashes.SHA384()),+ salt_length=pss_salt,+ ),+ hashes.SHA384(),+ ),+ "RSASSA_PSS_SHA_512": (+ padding.PSS(+ mgf=padding.MGF1(hashes.SHA512()),+ salt_length=pss_salt,+ ),+ hashes.SHA512(),+ ),+ }+ return algo_map.get(algorithm, (None, None))+++def _encrypt(data):+ key_id = data.get("KeyId", "")+ rec = _resolve_key(key_id)+ if not rec:+ return error_response_json("NotFoundException", f"Key {key_id} not found", 400)++ plaintext_b64 = data.get("Plaintext", "")+ plaintext = base64.b64decode(plaintext_b64) if isinstance(plaintext_b64, str) else plaintext_b64+ enc_context = data.get("EncryptionContext", {})++ if "_symmetric_key" in rec:+ # Fake symmetric encryption: XOR with a key-derived pad.+ # This is NOT real AES, but sufficient for emulation. The+ # ciphertext is: key_id_bytes(36) + context_hash(32) + xor_encrypted_data.+ # EncryptionContext is mixed into key derivation so decrypt+ # must supply the same context or get different plaintext.+ key_bytes = _derive_with_context(rec["_symmetric_key"], enc_context)+ pad_stream = _expand_key(key_bytes, len(plaintext))+ encrypted = bytes(a ^ b for a, b in zip(plaintext, pad_stream))+ ctx_hash = hashlib.sha256(+ json.dumps(enc_context, sort_keys=True).encode()+ ).digest()+ ciphertext = rec["KeyId"].encode() + ctx_hash + encrypted+ elif "_private_key" in rec and rec["KeyUsage"] == "ENCRYPT_DECRYPT":+ if enc_context:+ return error_response_json(+ "UnsupportedOperationException",+ "EncryptionContext is not supported with asymmetric keys",+ 400,+ )+ err = _require_crypto("Encrypt")+ if err:+ return err+ public_key = rec["_private_key"].public_key()+ ciphertext = public_key.encrypt(+ plaintext,+ padding.OAEP(+ mgf=padding.MGF1(algorithm=hashes.SHA256()),+ algorithm=hashes.SHA256(),+ label=None,+ ),+ )+ else:+ return error_response_json(+ "UnsupportedOperationException",+ "This key cannot be used for encryption",+ 400,+ )++ return json_response({+ "KeyId": rec["KeyId"],+ "CiphertextBlob": base64.b64encode(ciphertext).decode(),+ "EncryptionAlgorithm": data.get(+ "EncryptionAlgorithm", "SYMMETRIC_DEFAULT"+ ),+ })+++def _decrypt(data):+ ciphertext_b64 = data.get("CiphertextBlob", "")+ ciphertext = base64.b64decode(ciphertext_b64) if isinstance(ciphertext_b64, str) else ciphertext_b64+ enc_context = data.get("EncryptionContext", {})++ # For symmetric keys the ciphertext is: key_id(36) + ctx_hash(32) + encrypted_data+ key_id_from_data = data.get("KeyId", "")+ rec = None++ if key_id_from_data:+ rec = _resolve_key(key_id_from_data)++ # Try extracting key ID from ciphertext prefix (symmetric)+ if not rec and len(ciphertext) > 68:+ embedded_id = ciphertext[:36].decode("utf-8", errors="ignore")+ rec = _resolve_key(embedded_id)++ if not rec:+ return error_response_json(+ "NotFoundException",+ "Unable to find the key for decryption",+ 400,+ )++ if "_symmetric_key" in rec:+ stored_ctx_hash = ciphertext[36:68]+ provided_ctx_hash = hashlib.sha256(+ json.dumps(enc_context, sort_keys=True).encode()+ ).digest()+ if stored_ctx_hash != provided_ctx_hash:+ return error_response_json(+ "InvalidCiphertextException",+ "EncryptionContext does not match",+ 400,+ )+ encrypted_data = ciphertext[68:]+ key_bytes = _derive_with_context(rec["_symmetric_key"], enc_context)+ pad_stream = _expand_key(key_bytes, len(encrypted_data))+ plaintext = bytes(a ^ b for a, b in zip(encrypted_data, pad_stream))+ elif "_private_key" in rec:+ if enc_context:+ return error_response_json(+ "UnsupportedOperationException",+ "EncryptionContext is not supported with asymmetric keys",+ 400,+ )+ err = _require_crypto("Decrypt")+ if err:+ return err+ try:+ plaintext = rec["_private_key"].decrypt(+ ciphertext,+ padding.OAEP(+ mgf=padding.MGF1(algorithm=hashes.SHA256()),+ algorithm=hashes.SHA256(),+ label=None,+ ),+ )+ except ValueError as e:+ return error_response_json(+ "InvalidCiphertextException",+ str(e),+ 400,+ )+ else:+ return error_response_json(+ "UnsupportedOperationException",+ "This key cannot be used for decryption",+ 400,+ )++ return json_response({+ "KeyId": rec["KeyId"],+ "Plaintext": base64.b64encode(plaintext).decode(),+ "EncryptionAlgorithm": data.get(+ "EncryptionAlgorithm", "SYMMETRIC_DEFAULT"+ ),+ })+++def _generate_data_key_common(data):+ """Shared logic for GenerateDataKey and GenerateDataKeyWithoutPlaintext."""+ key_id = data.get("KeyId", "")+ rec = _resolve_key(key_id)+ if not rec:+ return None, None, error_response_json(+ "NotFoundException", f"Key {key_id} not found", 400+ )+ if "_symmetric_key" not in rec:+ return None, None, error_response_json(+ "UnsupportedOperationException",+ "GenerateDataKey requires a symmetric key",+ 400,+ )++ spec = data.get("KeySpec", "AES_256")+ length = data.get("NumberOfBytes")+ if length:+ data_key = os.urandom(length)+ elif spec == "AES_256":+ data_key = os.urandom(32)+ elif spec == "AES_128":+ data_key = os.urandom(16)+ else:+ data_key = os.urandom(32)++ enc_context = data.get("EncryptionContext", {})+ cmk_bytes = _derive_with_context(rec["_symmetric_key"], enc_context)+ pad_stream = _expand_key(cmk_bytes, len(data_key))+ encrypted = bytes(a ^ b for a, b in zip(data_key, pad_stream))+ ctx_hash = hashlib.sha256(+ json.dumps(enc_context, sort_keys=True).encode()+ ).digest()+ ciphertext = rec["KeyId"].encode() + ctx_hash + encrypted++ return rec, data_key, ciphertext+++def _generate_data_key(data):+ rec, data_key, result = _generate_data_key_common(data)+ if rec is None:+ # result is an error response tuple+ return result+ return json_response({+ "KeyId": rec["KeyId"],+ "Plaintext": base64.b64encode(data_key).decode(),+ "CiphertextBlob": base64.b64encode(result).decode(),+ })+++def _generate_data_key_without_plaintext(data):+ rec, _data_key, result = _generate_data_key_common(data)+ if rec is None:+ return result+ return json_response({+ "KeyId": rec["KeyId"],+ "CiphertextBlob": base64.b64encode(result).decode(),+ })+++def _derive_with_context(key_bytes, enc_context):+ """Mix EncryptionContext into key material so decrypt requires the same context."""+ ctx_bytes = json.dumps(enc_context, sort_keys=True).encode()+ return hashlib.sha256(key_bytes + ctx_bytes).digest()+++def _expand_key(key_bytes, length):+ """Expand a key to the required length using SHA-256 chaining."""+ result = b""+ counter = 0+ while len(result) < length:+ result += hashlib.sha256(key_bytes + counter.to_bytes(4, "big")).digest()+ counter += 1+ return result[:length]+++# ---- Request handler ----++async def handle_request(method, path, headers, body, query_params):+ target = headers.get("x-amz-target", "")+ action = target.split(".")[-1] if "." in target else ""++ try:+ data = json.loads(body) if body else {}+ except json.JSONDecodeError:+ return error_response_json("SerializationException", "Invalid JSON", 400)++ handlers = {+ "CreateKey": _create_key,+ "ListKeys": _list_keys,+ "DescribeKey": _describe_key,+ "GetPublicKey": _get_public_key,+ "Sign": _sign,+ "Verify": _verify,+ "Encrypt": _encrypt,+ "Decrypt": _decrypt,+ "GenerateDataKey": _generate_data_key,+ "GenerateDataKeyWithoutPlaintext": _generate_data_key_without_plaintext,+ }++ handler = handlers.get(action)+ if not handler:+ logger.warning("Unknown KMS action: %s", action)+ return error_response_json(+ "InvalidAction", f"Unknown action: {action}", 400+ )+ return handler(data)+++def reset():+ _keys.clear()diff --git a/pyproject.toml b/pyproject.tomlindex 0ed6076b..fcd217b0 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "ministack"-version = "1.1.22"+version = "1.1.23"description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"readme = "README.md"license = { file = "LICENSE" }@@ -31,6 +31,7 @@ dependencies = [full = ["duckdb>=0.10.0","docker>=7.0.0",+ "cryptography>=41.0",]dev = ["boto3>=1.34",@@ -38,6 +39,7 @@ dev = ["pytest-cov>=5.0","duckdb>=0.10.0","docker>=7.0.0",+ "cryptography>=41.0","ruff>=0.4",]diff --git a/tests/conftest.py b/tests/conftest.pyindex 4316a9fb..1bbec075 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -191,6 +191,10 @@ def sesv2():def cfn():return make_client("cloudformation")[email protected](scope="session")+def kms_client():+ return make_client("kms")+@pytest.fixture(scope="session")def sfn_sync():"""SFN client for StartSyncExecution — forces same endpoint (boto3 normally prefixes sync-)."""diff --git a/tests/test_services.py b/tests/test_services.pyindex 3b58d03d..9b496526 100644--- a/tests/test_services.py+++ b/tests/test_services.py@@ -16451,3 +16451,300 @@ def test_cfn_explicit_name_not_overridden(cfn, s3):cfn.delete_stack(StackName="cfn-explicit-name")_wait_stack(cfn, "cfn-explicit-name")+++# ═══════════════════════════════════════════════════════════════════════════════+# KMS+# ═══════════════════════════════════════════════════════════════════════════════++def test_kms_create_symmetric_key(kms_client):+ resp = kms_client.create_key(+ KeySpec="SYMMETRIC_DEFAULT",+ KeyUsage="ENCRYPT_DECRYPT",+ Description="test symmetric key",+ )+ meta = resp["KeyMetadata"]+ assert meta["KeyId"]+ assert meta["Arn"].startswith("arn:aws:kms:")+ assert meta["KeySpec"] == "SYMMETRIC_DEFAULT"+ assert meta["KeyUsage"] == "ENCRYPT_DECRYPT"+ assert meta["Enabled"] is True+ assert meta["KeyState"] == "Enabled"+++def test_kms_create_rsa_2048_sign_key(kms_client):+ resp = kms_client.create_key(+ KeySpec="RSA_2048",+ KeyUsage="SIGN_VERIFY",+ Description="test RSA signing key",+ )+ meta = resp["KeyMetadata"]+ assert meta["KeySpec"] == "RSA_2048"+ assert meta["KeyUsage"] == "SIGN_VERIFY"+ assert "RSASSA_PKCS1_V1_5_SHA_256" in meta["SigningAlgorithms"]+++def test_kms_create_rsa_4096_encrypt_key(kms_client):+ resp = kms_client.create_key(+ KeySpec="RSA_4096",+ KeyUsage="ENCRYPT_DECRYPT",+ )+ meta = resp["KeyMetadata"]+ assert meta["KeySpec"] == "RSA_4096"+ assert "RSAES_OAEP_SHA_256" in meta["EncryptionAlgorithms"]+++def test_kms_list_keys(kms_client):+ created = kms_client.create_key(KeySpec="SYMMETRIC_DEFAULT")+ key_id = created["KeyMetadata"]["KeyId"]+ resp = kms_client.list_keys()+ key_ids = [k["KeyId"] for k in resp["Keys"]]+ assert key_id in key_ids+++def test_kms_describe_key(kms_client):+ created = kms_client.create_key(+ KeySpec="SYMMETRIC_DEFAULT", Description="describe me"+ )+ key_id = created["KeyMetadata"]["KeyId"]+ resp = kms_client.describe_key(KeyId=key_id)+ assert resp["KeyMetadata"]["Description"] == "describe me"+ assert resp["KeyMetadata"]["KeyId"] == key_id+++def test_kms_describe_key_by_arn(kms_client):+ created = kms_client.create_key(KeySpec="SYMMETRIC_DEFAULT")+ arn = created["KeyMetadata"]["Arn"]+ resp = kms_client.describe_key(KeyId=arn)+ assert resp["KeyMetadata"]["Arn"] == arn+++def test_kms_describe_nonexistent_key(kms_client):+ with pytest.raises(ClientError) as exc_info:+ kms_client.describe_key(KeyId="nonexistent-key-id")+ assert "NotFoundException" in str(exc_info.value)+++def test_kms_sign_and_verify_pkcs1(kms_client):+ key = kms_client.create_key(KeySpec="RSA_2048", KeyUsage="SIGN_VERIFY")+ key_id = key["KeyMetadata"]["KeyId"]+ message = b"header.payload"++ sign_resp = kms_client.sign(+ KeyId=key_id,+ Message=message,+ MessageType="RAW",+ SigningAlgorithm="RSASSA_PKCS1_V1_5_SHA_256",+ )+ assert sign_resp["KeyId"] == key_id+ assert sign_resp["SigningAlgorithm"] == "RSASSA_PKCS1_V1_5_SHA_256"+ assert len(sign_resp["Signature"]) > 0++ verify_resp = kms_client.verify(+ KeyId=key_id,+ Message=message,+ MessageType="RAW",+ Signature=sign_resp["Signature"],+ SigningAlgorithm="RSASSA_PKCS1_V1_5_SHA_256",+ )+ assert verify_resp["SignatureValid"] is True+++def test_kms_sign_and_verify_pss(kms_client):+ key = kms_client.create_key(KeySpec="RSA_2048", KeyUsage="SIGN_VERIFY")+ key_id = key["KeyMetadata"]["KeyId"]+ message = b"test-pss-message"++ sign_resp = kms_client.sign(+ KeyId=key_id,+ Message=message,+ MessageType="RAW",+ SigningAlgorithm="RSASSA_PSS_SHA_256",+ )+ verify_resp = kms_client.verify(+ KeyId=key_id,+ Message=message,+ MessageType="RAW",+ Signature=sign_resp["Signature"],+ SigningAlgorithm="RSASSA_PSS_SHA_256",+ )+ assert verify_resp["SignatureValid"] is True+++def test_kms_verify_wrong_message(kms_client):+ key = kms_client.create_key(KeySpec="RSA_2048", KeyUsage="SIGN_VERIFY")+ key_id = key["KeyMetadata"]["KeyId"]++ sign_resp = kms_client.sign(+ KeyId=key_id,+ Message=b"original",+ MessageType="RAW",+ SigningAlgorithm="RSASSA_PKCS1_V1_5_SHA_256",+ )+ verify_resp = kms_client.verify(+ KeyId=key_id,+ Message=b"tampered",+ MessageType="RAW",+ Signature=sign_resp["Signature"],+ SigningAlgorithm="RSASSA_PKCS1_V1_5_SHA_256",+ )+ assert verify_resp["SignatureValid"] is False+++def test_kms_jwt_signing_flow(kms_client):+ """Sign a JWT-style header.payload string and verify the signature."""+ import base64+ key = kms_client.create_key(KeySpec="RSA_2048", KeyUsage="SIGN_VERIFY")+ key_id = key["KeyMetadata"]["KeyId"]++ header = base64.urlsafe_b64encode(+ b'{"alg":"RS256","typ":"JWT"}'+ ).rstrip(b"=").decode()+ payload = base64.urlsafe_b64encode(+ b'{"sub":"user-2001","iss":"auth-service"}'+ ).rstrip(b"=").decode()+ signing_input = f"{header}.{payload}"++ sign_resp = kms_client.sign(+ KeyId=key_id,+ Message=signing_input.encode(),+ MessageType="RAW",+ SigningAlgorithm="RSASSA_PKCS1_V1_5_SHA_256",+ )+ assert sign_resp["Signature"]++ verify_resp = kms_client.verify(+ KeyId=key_id,+ Message=signing_input.encode(),+ MessageType="RAW",+ Signature=sign_resp["Signature"],+ SigningAlgorithm="RSASSA_PKCS1_V1_5_SHA_256",+ )+ assert verify_resp["SignatureValid"] is True+++def test_kms_encrypt_decrypt_roundtrip(kms_client):+ key = kms_client.create_key(+ KeySpec="SYMMETRIC_DEFAULT", KeyUsage="ENCRYPT_DECRYPT"+ )+ key_id = key["KeyMetadata"]["KeyId"]+ plaintext = b"sensitive document content"++ enc_resp = kms_client.encrypt(KeyId=key_id, Plaintext=plaintext)+ assert enc_resp["KeyId"] == key_id++ dec_resp = kms_client.decrypt(CiphertextBlob=enc_resp["CiphertextBlob"])+ assert dec_resp["Plaintext"] == plaintext+++def test_kms_encrypt_decrypt_with_explicit_key(kms_client):+ key = kms_client.create_key(+ KeySpec="SYMMETRIC_DEFAULT", KeyUsage="ENCRYPT_DECRYPT"+ )+ key_id = key["KeyMetadata"]["KeyId"]+ plaintext = b"another secret"++ enc_resp = kms_client.encrypt(KeyId=key_id, Plaintext=plaintext)+ dec_resp = kms_client.decrypt(+ KeyId=key_id, CiphertextBlob=enc_resp["CiphertextBlob"]+ )+ assert dec_resp["Plaintext"] == plaintext+++def test_kms_generate_data_key_aes_256(kms_client):+ key = kms_client.create_key(+ KeySpec="SYMMETRIC_DEFAULT", KeyUsage="ENCRYPT_DECRYPT"+ )+ key_id = key["KeyMetadata"]["KeyId"]++ resp = kms_client.generate_data_key(KeyId=key_id, KeySpec="AES_256")+ assert resp["KeyId"] == key_id+ assert len(resp["Plaintext"]) == 32+ assert resp["CiphertextBlob"]+++def test_kms_generate_data_key_aes_128(kms_client):+ key = kms_client.create_key(+ KeySpec="SYMMETRIC_DEFAULT", KeyUsage="ENCRYPT_DECRYPT"+ )+ key_id = key["KeyMetadata"]["KeyId"]++ resp = kms_client.generate_data_key(KeyId=key_id, KeySpec="AES_128")+ assert len(resp["Plaintext"]) == 16+++def test_kms_generate_data_key_decrypt_roundtrip(kms_client):+ """Encrypted data key should be decryptable back to the plaintext."""+ key = kms_client.create_key(+ KeySpec="SYMMETRIC_DEFAULT", KeyUsage="ENCRYPT_DECRYPT"+ )+ key_id = key["KeyMetadata"]["KeyId"]++ gen_resp = kms_client.generate_data_key(KeyId=key_id, KeySpec="AES_256")+ dec_resp = kms_client.decrypt(CiphertextBlob=gen_resp["CiphertextBlob"])+ assert dec_resp["Plaintext"] == gen_resp["Plaintext"]+++def test_kms_generate_data_key_without_plaintext(kms_client):+ key = kms_client.create_key(+ KeySpec="SYMMETRIC_DEFAULT", KeyUsage="ENCRYPT_DECRYPT"+ )+ key_id = key["KeyMetadata"]["KeyId"]++ resp = kms_client.generate_data_key_without_plaintext(+ KeyId=key_id, KeySpec="AES_256"+ )+ assert resp["KeyId"] == key_id+ assert resp["CiphertextBlob"]+ assert "Plaintext" not in resp+++def test_kms_get_public_key(kms_client):+ key = kms_client.create_key(KeySpec="RSA_2048", KeyUsage="SIGN_VERIFY")+ key_id = key["KeyMetadata"]["KeyId"]++ resp = kms_client.get_public_key(KeyId=key_id)+ assert resp["KeyId"] == key_id+ assert resp["KeySpec"] == "RSA_2048"+ assert resp["PublicKey"]+++def test_kms_encrypt_decrypt_with_encryption_context(kms_client):+ """EncryptionContext must match between encrypt and decrypt."""+ key = kms_client.create_key(+ KeySpec="SYMMETRIC_DEFAULT", KeyUsage="ENCRYPT_DECRYPT"+ )+ key_id = key["KeyMetadata"]["KeyId"]+ plaintext = b"context-sensitive data"+ context = {"service": "storage", "bucket": "documents"}++ enc_resp = kms_client.encrypt(+ KeyId=key_id, Plaintext=plaintext, EncryptionContext=context+ )++ dec_resp = kms_client.decrypt(+ CiphertextBlob=enc_resp["CiphertextBlob"],+ EncryptionContext=context,+ )+ assert dec_resp["Plaintext"] == plaintext+++def test_kms_decrypt_wrong_context_fails(kms_client):+ """Decrypt with wrong EncryptionContext should fail."""+ key = kms_client.create_key(+ KeySpec="SYMMETRIC_DEFAULT", KeyUsage="ENCRYPT_DECRYPT"+ )+ key_id = key["KeyMetadata"]["KeyId"]++ enc_resp = kms_client.encrypt(+ KeyId=key_id,+ Plaintext=b"secret",+ EncryptionContext={"env": "prod"},+ )++ with pytest.raises(ClientError) as exc_info:+ kms_client.decrypt(+ CiphertextBlob=enc_resp["CiphertextBlob"],+ EncryptionContext={"env": "dev"},+ )+ assert "InvalidCiphertextException" in str(exc_info.value)