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
feat(kms): add ECC key support for Sign/Verify (SECG_P256K1, NIST P-256/384/521) (#335)
Eli49eddeda2e88
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d43082f8..1718bc7b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [1.2.14] — 2026-04-15### Added+- **KMS ECC key support** — `CreateKey` now supports `ECC_SECG_P256K1`, `ECC_NIST_P256`, `ECC_NIST_P384`, and `ECC_NIST_P521` key specs with `ECDSA_SHA_256`, `ECDSA_SHA_384`, `ECDSA_SHA_512` signing algorithms. Sign/Verify works for both `RAW` and `DIGEST` message types. `GetPublicKey` returns DER-encoded EC public keys. Contributed by @dvrkn- **Cognito federated SAML/OIDC auth flow** — `GET /oauth2/authorize` (redirects to external SAML/OIDC IdP), `POST /saml2/idpresponse` (parses SAML assertion, creates federated user, issues authorization code), and `POST /oauth2/token` now supports `grant_type=authorization_code` for full SSO flow. Also adds `GetIdentityProviderByIdentifier`. Contributed by @prandogabriel (#329)- **EC2 AuthorizeSecurityGroup returns rules** — `AuthorizeSecurityGroupIngress` and `AuthorizeSecurityGroupEgress` now return `SecurityGroupRules` in the response with rule IDs, group ownership, protocol, port range, and CIDR details. Required by Terraform AWS provider v6. Reported by @mspiller (#325)diff --git a/README.md b/README.mdindex 4f541cca..ae3b3ad6 100644--- a/README.md+++ b/README.md@@ -359,7 +359,7 @@ subnet = ec2.create_subnet(| **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, TagResource, UntagResource, GetTags | HTTP API (v2) protocol; Lambda proxy (AWS_PROXY) and HTTP proxy (HTTP_PROXY) integrations; data plane via `{apiId}.execute-api.localhost`; `{param}` and `{proxy+}` path matching; JWT/Lambda authorizer CRUD || **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, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags | 27 actions; RSA (2048/4096) and symmetric keys; PKCS1v15 and PSS signing; envelope encryption; alias resolution; key rotation; key policies; tags; enable/disable/schedule deletion; full Terraform `aws_kms_key` compatible; `cryptography` package included in Docker image |+| **KMS** | CreateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateDataKey, GenerateDataKeyWithoutPlaintext, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags | 27 actions; RSA (2048/4096), ECC (SECG_P256K1, NIST P-256/384/521), and symmetric keys; PKCS1v15, PSS, and ECDSA signing; envelope encryption; alias resolution; key rotation; key policies; tags; enable/disable/schedule deletion; full Terraform `aws_kms_key` compatible; `cryptography` package included in Docker image || **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; field validation and name uniqueness enforcement |### CloudFormationdiff --git a/ministack/services/kms.py b/ministack/services/kms.pyindex e6a6ea62..fd363347 100644--- a/ministack/services/kms.py+++ b/ministack/services/kms.py@@ -20,7 +20,7 @@ logger = logging.getLogger("kms")try:from cryptography.exceptions import InvalidSignaturefrom cryptography.hazmat.primitives import hashes, serialization- from cryptography.hazmat.primitives.asymmetric import padding, rsa, utils+ from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa, utilsHAS_CRYPTO = Trueexcept ImportError:InvalidSignature = Exception@@ -39,8 +39,8 @@ _keys = AccountScopedDict()# 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),+# _private_key (asymmetric private key object, RSA/ECC only),+# _public_key_der (bytes, RSA/ECC only),# _symmetric_key (bytes, SYMMETRIC_DEFAULT only),# }_aliases = AccountScopedDict() # alias_name -> key_id (e.g. "alias/my-key" -> "uuid")@@ -226,6 +226,30 @@ def _create_key(data):"RSAES_OAEP_SHA_256",]rec["SigningAlgorithms"] = []+ elif key_spec in ("ECC_NIST_P256", "ECC_NIST_P384", "ECC_NIST_P521", "ECC_SECG_P256K1"):+ err = _require_crypto("CreateKey")+ if err:+ return err+ curve_map = {+ "ECC_NIST_P256": ec.SECP256R1(),+ "ECC_NIST_P384": ec.SECP384R1(),+ "ECC_NIST_P521": ec.SECP521R1(),+ "ECC_SECG_P256K1": ec.SECP256K1(),+ }+ private_key = ec.generate_private_key(curve_map[key_spec])+ rec["_private_key"] = private_key+ rec["_public_key_der"] = private_key.public_key().public_bytes(+ serialization.Encoding.DER,+ serialization.PublicFormat.SubjectPublicKeyInfo,+ )+ signing_algo_map = {+ "ECC_NIST_P256": ["ECDSA_SHA_256"],+ "ECC_NIST_P384": ["ECDSA_SHA_384"],+ "ECC_NIST_P521": ["ECDSA_SHA_512"],+ "ECC_SECG_P256K1": ["ECDSA_SHA_256"],+ }+ rec["SigningAlgorithms"] = signing_algo_map[key_spec]+ rec["EncryptionAlgorithms"] = []else:return error_response_json("UnsupportedOperationException",@@ -302,19 +326,29 @@ def _sign(data):message = message_b64pad, hash_algo = _signing_params(algorithm)- if pad is None:+ if hash_algo 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)- )+ if pad is None:+ # ECDSA – no padding; pass ec.ECDSA(hash) as the algorithm+ if message_type == "DIGEST":+ signature = rec["_private_key"].sign(+ message, ec.ECDSA(utils.Prehashed(hash_algo))+ )+ else:+ signature = rec["_private_key"].sign(message, ec.ECDSA(hash_algo))else:- signature = rec["_private_key"].sign(message, pad, hash_algo)+ # RSA+ 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({@@ -349,7 +383,7 @@ def _verify(data):signature = base64.b64decode(signature_b64) if isinstance(signature_b64, str) else signature_b64pad, hash_algo = _signing_params(algorithm, for_verify=True)- if pad is None:+ if hash_algo is None:return error_response_json("UnsupportedOperationException",f"Signing algorithm {algorithm} is not supported",@@ -358,10 +392,18 @@ def _verify(data):public_key = rec["_private_key"].public_key()try:- if message_type == "DIGEST":- public_key.verify(signature, message, pad, utils.Prehashed(hash_algo))+ if pad is None:+ # ECDSA+ if message_type == "DIGEST":+ public_key.verify(signature, message, ec.ECDSA(utils.Prehashed(hash_algo)))+ else:+ public_key.verify(signature, message, ec.ECDSA(hash_algo))else:- public_key.verify(signature, message, pad, hash_algo)+ # RSA+ if message_type == "DIGEST":+ public_key.verify(signature, message, pad, utils.Prehashed(hash_algo))+ else:+ public_key.verify(signature, message, pad, hash_algo)valid = Trueexcept InvalidSignature:valid = False@@ -374,7 +416,12 @@ def _verify(data):def _signing_params(algorithm, for_verify=False):- """Return (padding, hash_algorithm) for a signing algorithm."""+ """Return (padding, hash_algorithm) for a signing algorithm.++ For RSA algorithms, padding is a padding object.+ For ECDSA algorithms, padding is None (ECDSA uses ec.ECDSA() instead).+ If the algorithm is unknown, returns (None, None).+ """if not HAS_CRYPTO:return None, None@@ -406,6 +453,10 @@ def _signing_params(algorithm, for_verify=False):),hashes.SHA512(),),+ # ECDSA – padding is None; callers use ec.ECDSA(hash) instead+ "ECDSA_SHA_256": (None, hashes.SHA256()),+ "ECDSA_SHA_384": (None, hashes.SHA384()),+ "ECDSA_SHA_512": (None, hashes.SHA512()),}return algo_map.get(algorithm, (None, None))diff --git a/tests/test_kms.py b/tests/test_kms.pyindex b925eb87..29adee1b 100644--- a/tests/test_kms.py+++ b/tests/test_kms.py@@ -419,6 +419,187 @@ def test_kms_list_key_policies(kms_client):assert "default" in resp["PolicyNames"]kms_client.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)+def test_kms_create_ecc_secg_p256k1_key(kms_client):+ resp = kms_client.create_key(+ KeySpec="ECC_SECG_P256K1",+ KeyUsage="SIGN_VERIFY",+ Description="secp256k1 signing key",+ )+ meta = resp["KeyMetadata"]+ assert meta["KeySpec"] == "ECC_SECG_P256K1"+ assert meta["KeyUsage"] == "SIGN_VERIFY"+ assert "ECDSA_SHA_256" in meta["SigningAlgorithms"]+ assert meta["EncryptionAlgorithms"] == []++def test_kms_ecc_sign_and_verify(kms_client):+ key = kms_client.create_key(KeySpec="ECC_SECG_P256K1", KeyUsage="SIGN_VERIFY")+ key_id = key["KeyMetadata"]["KeyId"]+ message = b"hello secp256k1"++ sign_resp = kms_client.sign(+ KeyId=key_id,+ Message=message,+ MessageType="RAW",+ SigningAlgorithm="ECDSA_SHA_256",+ )+ assert sign_resp["KeyId"] == key_id+ assert sign_resp["SigningAlgorithm"] == "ECDSA_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="ECDSA_SHA_256",+ )+ assert verify_resp["SignatureValid"] is True++def test_kms_ecc_verify_wrong_message(kms_client):+ key = kms_client.create_key(KeySpec="ECC_SECG_P256K1", KeyUsage="SIGN_VERIFY")+ key_id = key["KeyMetadata"]["KeyId"]++ sign_resp = kms_client.sign(+ KeyId=key_id,+ Message=b"original",+ MessageType="RAW",+ SigningAlgorithm="ECDSA_SHA_256",+ )+ verify_resp = kms_client.verify(+ KeyId=key_id,+ Message=b"tampered",+ MessageType="RAW",+ Signature=sign_resp["Signature"],+ SigningAlgorithm="ECDSA_SHA_256",+ )+ assert verify_resp["SignatureValid"] is False++def test_kms_ecc_get_public_key(kms_client):+ key = kms_client.create_key(KeySpec="ECC_SECG_P256K1", 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"] == "ECC_SECG_P256K1"+ assert resp["PublicKey"]+ assert "ECDSA_SHA_256" in resp["SigningAlgorithms"]++def test_kms_ecc_nist_p256_sign_verify(kms_client):+ key = kms_client.create_key(KeySpec="ECC_NIST_P256", KeyUsage="SIGN_VERIFY")+ key_id = key["KeyMetadata"]["KeyId"]++ sign_resp = kms_client.sign(+ KeyId=key_id,+ Message=b"nist p256 message",+ MessageType="RAW",+ SigningAlgorithm="ECDSA_SHA_256",+ )+ verify_resp = kms_client.verify(+ KeyId=key_id,+ Message=b"nist p256 message",+ MessageType="RAW",+ Signature=sign_resp["Signature"],+ SigningAlgorithm="ECDSA_SHA_256",+ )+ assert verify_resp["SignatureValid"] is True++def test_kms_ecc_nist_p384_sign_verify(kms_client):+ key = kms_client.create_key(KeySpec="ECC_NIST_P384", KeyUsage="SIGN_VERIFY")+ meta = key["KeyMetadata"]+ assert "ECDSA_SHA_384" in meta["SigningAlgorithms"]++ sign_resp = kms_client.sign(+ KeyId=meta["KeyId"],+ Message=b"nist p384 message",+ MessageType="RAW",+ SigningAlgorithm="ECDSA_SHA_384",+ )+ verify_resp = kms_client.verify(+ KeyId=meta["KeyId"],+ Message=b"nist p384 message",+ MessageType="RAW",+ Signature=sign_resp["Signature"],+ SigningAlgorithm="ECDSA_SHA_384",+ )+ assert verify_resp["SignatureValid"] is True++def test_kms_ecc_nist_p521_sign_verify(kms_client):+ key = kms_client.create_key(KeySpec="ECC_NIST_P521", KeyUsage="SIGN_VERIFY")+ meta = key["KeyMetadata"]+ assert "ECDSA_SHA_512" in meta["SigningAlgorithms"]++ sign_resp = kms_client.sign(+ KeyId=meta["KeyId"],+ Message=b"nist p521 message",+ MessageType="RAW",+ SigningAlgorithm="ECDSA_SHA_512",+ )+ verify_resp = kms_client.verify(+ KeyId=meta["KeyId"],+ Message=b"nist p521 message",+ MessageType="RAW",+ Signature=sign_resp["Signature"],+ SigningAlgorithm="ECDSA_SHA_512",+ )+ assert verify_resp["SignatureValid"] is True++def test_kms_ecc_sign_verify_digest_mode(kms_client):+ """Sign/Verify with MessageType=DIGEST (pre-hashed message)."""+ import hashlib+ key = kms_client.create_key(KeySpec="ECC_SECG_P256K1", KeyUsage="SIGN_VERIFY")+ key_id = key["KeyMetadata"]["KeyId"]++ message_digest = hashlib.sha256(b"original message").digest()++ sign_resp = kms_client.sign(+ KeyId=key_id,+ Message=message_digest,+ MessageType="DIGEST",+ SigningAlgorithm="ECDSA_SHA_256",+ )+ assert sign_resp["SigningAlgorithm"] == "ECDSA_SHA_256"++ verify_resp = kms_client.verify(+ KeyId=key_id,+ Message=message_digest,+ MessageType="DIGEST",+ Signature=sign_resp["Signature"],+ SigningAlgorithm="ECDSA_SHA_256",+ )+ assert verify_resp["SignatureValid"] is True++ # Wrong digest should fail+ wrong_digest = hashlib.sha256(b"different message").digest()+ verify_resp = kms_client.verify(+ KeyId=key_id,+ Message=wrong_digest,+ MessageType="DIGEST",+ Signature=sign_resp["Signature"],+ SigningAlgorithm="ECDSA_SHA_256",+ )+ assert verify_resp["SignatureValid"] is False++def test_kms_ecc_sign_via_alias(kms_client):+ """Sign and verify using an alias instead of key ID."""+ key = kms_client.create_key(KeySpec="ECC_SECG_P256K1", KeyUsage="SIGN_VERIFY")+ key_id = key["KeyMetadata"]["KeyId"]+ kms_client.create_alias(AliasName="alias/ecc-sign-alias", TargetKeyId=key_id)++ sign_resp = kms_client.sign(+ KeyId="alias/ecc-sign-alias",+ Message=b"alias signing test",+ MessageType="RAW",+ SigningAlgorithm="ECDSA_SHA_256",+ )+ verify_resp = kms_client.verify(+ KeyId="alias/ecc-sign-alias",+ Message=b"alias signing test",+ MessageType="RAW",+ Signature=sign_resp["Signature"],+ SigningAlgorithm="ECDSA_SHA_256",+ )+ assert verify_resp["SignatureValid"] is True+def test_kms_key_rotation_with_period(kms_client):"""EnableKeyRotation with custom RotationPeriodInDays."""key = kms_client.create_key()