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): CreateGrant, RevokeGrant and RetireGrant; ListGrants returns them (#1847)
Davi Reis Vieira9a2698432612
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fb331dfe..270cabd1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added++- **KMS — grants** — `CreateGrant`, `RevokeGrant` and `RetireGrant`, and `ListGrants` returns the grants they create instead of always an empty list. `CreateGrant` returns a `GrantId` and a `GrantToken`, follows the key state (`DisabledException` for a disabled key, `KMSInvalidStateException` pending deletion, replica deletion or import), rejects operations the key cannot perform (`Sign` / `Verify` / `GenerateMac` / `VerifyMac` on a symmetric encryption key, data key operations on an asymmetric key, anything but `GenerateMac` / `VerifyMac` / `DescribeKey` / `CreateGrant` / `RetireGrant` on an HMAC key) with `ValidationException`, and with a `Name` a retry with identical parameters returns the original `GrantId` with a new token. `ListGrants` filters by `GrantId` and `GranteePrincipal` and pages with `Limit` (1 to 100, default 50) and `Marker`. `RetireGrant` takes a `GrantToken`, or a `KeyId` and `GrantId`. All three honour `DryRun`, and grants persist with the key. Grants are recorded but not evaluated when authorizing other calls, as with key policies. Contributed by @DaviReisVieira.### Fixed- **Lambda — VPC configuration includes `VpcId`** — `CreateFunction`, `GetFunction`, `GetFunctionConfiguration`, and `UpdateFunctionConfiguration` now report the VPC of the configured subnets. Previously, VPC-attached functions returned only subnet and security group IDs. Contributed by @jayjanssen.diff --git a/README.md b/README.mdindex 907db614..c042a53b 100644--- a/README.md+++ b/README.md@@ -441,7 +441,7 @@ subnet = ec2.create_subnet(| **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateRouteResponse, GetRouteResponse, GetRouteResponses, UpdateRouteResponse, DeleteRouteResponse, CreateIntegrationResponse, GetIntegrationResponse, GetIntegrationResponses, UpdateIntegrationResponse, DeleteIntegrationResponse, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, TagResource, UntagResource, GetTags, PostToConnection, GetConnection, DeleteConnection | **HTTP API** and **WebSocket API** (`protocolType=WEBSOCKET`); Lambda proxy (`AWS_PROXY`), HTTP proxy (`HTTP_PROXY`), and MOCK integrations; HTTP data plane via `{apiId}.execute-api.localhost` Host header or path-based `/_aws/execute-api/{apiId}/{stage}/{path}` (no DNS/Host override needed — works from browsers on macOS and strict clients); `$default` stage served from the URL root (no stage segment in the path); per-API `corsConfiguration` applied to preflights + dispatched responses; request parameter mapping for HTTP_PROXY (`append/overwrite/remove` for headers/querystring plus `overwrite:path`) with context variables including `$context.authorizer.jwt.claims`; JWT data-plane authorization for HTTP routes (issuer/audience/time/scope checks) and claim propagation to integrations; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; WebSocket data plane on the same two URL forms, with `$connect` / `$disconnect` / `$default` / custom-action routing, `$request.body.*` RouteSelectionExpression, `@connections` management API (PostToConnection / GetConnection / DeleteConnection), per-connection outbox for server-side push; `{param}` / `{proxy+}` matching; JWT/Lambda authorizer CRUD; pin `apiId` across runs with the `ms-custom-id` tag || **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, CreateDocumentationPart, GetDocumentationPart, GetDocumentationParts, UpdateDocumentationPart, DeleteDocumentationPart, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags, CreateRequestValidator, GetRequestValidators, GetRequestValidator, UpdateRequestValidator, DeleteRequestValidator | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), non-proxy Lambda (AWS — the handler's output is the response body, mapping templates not modeled), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost` Host header, path-based `/_aws/execute-api/{apiId}/{stage}/{path}`, or legacy `/restapis/{apiId}/{stage}/_user_request_/{path}`; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; resource tree with `{param}` and `{proxy+}` path matching; routing is on the resource+method pair, so a request the matched resource does not serve falls through to a `{proxy+}` elsewhere in the tree (a methodless intermediate, a CORS-preflight-only node, or any undeclared verb), as it does on AWS; TOKEN and REQUEST Lambda authorizers on the data plane, with the returned IAM policy evaluated against each request's own method ARN and `authorizerResultTtlInSeconds` caching the policy per stage and identity source; JSON Patch for all PATCH operations; state persistence; pin `id` across runs with the `ms-custom-id` tag || **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, SetSubnets, SetIpAddressType, SetSecurityGroups, 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`, `authenticate-oidc` actions; data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix |-| **KMS** | CreateKey, ReplicateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateMac, VerifyMac, GenerateDataKey, GenerateDataKeyWithoutPlaintext, GenerateDataKeyPair, GenerateDataKeyPairWithoutPlaintext, GenerateRandom, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, UpdateKeyDescription, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags, GetParametersForImport, ImportKeyMaterial, DeleteImportedKeyMaterial, ListGrants | 38 actions; multi-Region keys: `CreateKey` with `MultiRegion` mints an `mrk-` key and `ReplicateKey` creates a same-id replica in another region sharing the key material (ciphertext from the primary decrypts against the replica; a primary with live replicas waits in `PendingReplicaDeletion`); CMK specs: RSA (2048/3072/4096), ECC (SECG_P256K1, NIST P-256/384/521), Edwards25519 (`ECC_NIST_EDWARDS25519` — pure Ed25519 via `ED25519_SHA_512` with `MessageType=RAW`; `ED25519_PH_SHA_512` advertised in `SigningAlgorithms` but returns `UnsupportedOperationException` until Ed25519ph lands), HMAC (`HMAC_224`/`HMAC_256`/`HMAC_384`/`HMAC_512` with `KeyUsage=GENERATE_VERIFY_MAC`), and symmetric keys; PKCS1v15, PSS, and ECDSA signing; real RFC 2104 HMAC via `GenerateMac`/`VerifyMac` (4096-byte message cap, `KMSInvalidMacException` on mismatch, `DryRun` supported); envelope encryption, incl. asymmetric data key pairs (`KeyPairSpec` adds RSA_3072); 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, ReplicateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateMac, VerifyMac, GenerateDataKey, GenerateDataKeyWithoutPlaintext, GenerateDataKeyPair, GenerateDataKeyPairWithoutPlaintext, GenerateRandom, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, UpdateKeyDescription, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags, GetParametersForImport, ImportKeyMaterial, DeleteImportedKeyMaterial, CreateGrant, ListGrants, RevokeGrant, RetireGrant | 41 actions; multi-Region keys: `CreateKey` with `MultiRegion` mints an `mrk-` key and `ReplicateKey` creates a same-id replica in another region sharing the key material (ciphertext from the primary decrypts against the replica; a primary with live replicas waits in `PendingReplicaDeletion`); CMK specs: RSA (2048/3072/4096), ECC (SECG_P256K1, NIST P-256/384/521), Edwards25519 (`ECC_NIST_EDWARDS25519` — pure Ed25519 via `ED25519_SHA_512` with `MessageType=RAW`; `ED25519_PH_SHA_512` advertised in `SigningAlgorithms` but returns `UnsupportedOperationException` until Ed25519ph lands), HMAC (`HMAC_224`/`HMAC_256`/`HMAC_384`/`HMAC_512` with `KeyUsage=GENERATE_VERIFY_MAC`), and symmetric keys; PKCS1v15, PSS, and ECDSA signing; real RFC 2104 HMAC via `GenerateMac`/`VerifyMac` (4096-byte message cap, `KMSInvalidMacException` on mismatch, `DryRun` supported); envelope encryption, incl. asymmetric data key pairs (`KeyPairSpec` adds RSA_3072); alias resolution; key rotation; key policies; tags; enable/disable/schedule deletion; grants (stored and listed, not evaluated for authorization); 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, CreateFunction, DeleteFunction, DescribeFunction, GetFunction, ListFunctions, PublishFunction, UpdateFunction, **KeyValueStore (mgmt)**: CreateKeyValueStore, DescribeKeyValueStore, ListKeyValueStores, UpdateKeyValueStore, DeleteKeyValueStore, **Policies**: CreateCachePolicy, GetCachePolicy, GetCachePolicyConfig, UpdateCachePolicy, DeleteCachePolicy, ListDistributionsByCachePolicyId, CreateOriginRequestPolicy, GetOriginRequestPolicy, GetOriginRequestPolicyConfig, UpdateOriginRequestPolicy, DeleteOriginRequestPolicy, ListDistributionsByOriginRequestPolicyId, CreateResponseHeadersPolicy, GetResponseHeadersPolicy, GetResponseHeadersPolicyConfig, UpdateResponseHeadersPolicy, DeleteResponseHeadersPolicy, ListDistributionsByResponseHeadersPolicyId, **Public keys / key groups**: CreatePublicKey, GetPublicKey, GetPublicKeyConfig, UpdatePublicKey, DeletePublicKey, ListPublicKeys, CreateKeyGroup, GetKeyGroup, GetKeyGroupConfig, UpdateKeyGroup, DeleteKeyGroup, ListKeyGroups, **SaaS Manager**: CreateConnectionGroup, GetConnectionGroup, GetConnectionGroupByRoutingEndpoint, UpdateConnectionGroup, DeleteConnectionGroup, ListConnectionGroups, CreateDistributionTenant, GetDistributionTenant, GetDistributionTenantByDomain, UpdateDistributionTenant, DeleteDistributionTenant, ListDistributionTenants, ListDistributionTenantsByCustomization, AssociateDistributionTenantWebACL, DisassociateDistributionTenantWebACL, CreateInvalidationForDistributionTenant, GetInvalidationForDistributionTenant, ListInvalidationsForDistributionTenant, VerifyDnsConfiguration, GetManagedCertificateDetails, ListDomainConflicts, UpdateDomainAssociation, ListDistributionsByConnectionMode, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin config round-trip; cache / origin request / response headers policies round-trip their full config with `ETag` / `If-Match` optimistic concurrency; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; **CloudFront Functions** are API stubs (in-memory code + DEVELOPMENT/LIVE ETags for Terraform `aws_cloudfront_function`) with `KeyValueStoreAssociations` round-tripped — no `TestFunction`, no viewer-request JS execution at the edge; `UpdateFunction` clears the emulated LIVE stage until `PublishFunction` runs again; **SaaS Manager** multi-tenant distributions: `DistributionConfig` round-trips `ConnectionMode` / `TenantConfig`, tenants require a `tenant-only` distribution, CNAMEs are unique across tenants and distribution aliases, a tenant without an explicit connection group lazily gets the account default group, and MiniStack collapses async workflows (tenants deploy, domains activate, DNS verifies, managed certificates issue immediately); key groups validate `Items` against real public keys, and deleting either while still referenced (`PublicKeyInUse` / `ResourceInUse`) is rejected || **CloudFront KeyValueStore (data plane)** | DescribeKeyValueStore, ListKeys, GetKey, PutKey, DeleteKey, UpdateKeys | Separate `cloudfront-keyvaluestore` SDK service (REST/JSON, signing name `cloudfront-keyvaluestore`); ETag-based optimistic concurrency on every mutating op; `UpdateKeys` is atomic (validates whole batch, rejects on first invalid entry); `ListKeys` paginates with opaque `NextToken` capped at 50 results per AWS spec; bridges to the management plane via the shared KVS ARN || **CloudTrail** | LookupEvents, CreateTrail, DeleteTrail, GetTrail, DescribeTrails, ListTrails, UpdateTrail, GetTrailStatus, StartLogging, StopLogging, PutEventSelectors, GetEventSelectors, AddTags, ListTags, RemoveTags | In-memory audit log; recording opt-in via `CLOUDTRAIL_RECORDING=1` (or runtime config endpoint); per-account ring buffer (`CLOUDTRAIL_MAX_EVENTS=10000`); `LookupEvents` supports all 8 AWS `LookupAttributes`; `IsLogging` flips on Start/StopLogging; `CreateTrail`/`UpdateTrail` persist `KmsKeyId` (normalized to a key ARN; omitted when unset) so `aws_cloudtrail` converges without drift |diff --git a/ministack/services/kms.py b/ministack/services/kms.pyindex b03b78a3..8fe35c7f 100644--- a/ministack/services/kms.py+++ b/ministack/services/kms.py@@ -7,7 +7,7 @@ Supports: CreateKey, ListKeys, DescribeKey, Sign, Verify,Encrypt, Decrypt, GenerateDataKey,GenerateDataKeyWithoutPlaintext, GenerateDataKeyPair,GenerateDataKeyPairWithoutPlaintext, GenerateMac, VerifyMac,- GenerateRandom.+ GenerateRandom, CreateGrant, ListGrants, RevokeGrant, RetireGrant."""import base64@@ -61,6 +61,12 @@ _keys = AccountRegionScopedDict()# }_aliases = AccountRegionScopedDict() # alias ARN -> key_id_alias_dates = AccountRegionScopedDict() # alias ARN -> {CreationDate, LastUpdatedDate}+_grants = AccountRegionScopedDict()+# grant_id -> {+# GrantId, KeyId (key ARN), Name, CreationDate, GranteePrincipal,+# RetiringPrincipal, IssuingAccount, Operations, Constraints,+# _tokens (every GrantToken CreateGrant has returned for this grant),+# }_HMAC_KEY_SPECS = {"HMAC_224": ("HMAC_SHA_224", 28),@@ -139,7 +145,12 @@ def get_state():except Exception:passserializable_keys._data[scoped_key] = entry- return {"keys": serializable_keys, "aliases": _aliases, "alias_dates": _alias_dates}+ return {+ "keys": serializable_keys,+ "aliases": _aliases,+ "alias_dates": _alias_dates,+ "grants": _grants,+ }def load_persisted_state(data):@@ -228,6 +239,9 @@ def _restore_state(data):alias_dates = data.get("alias_dates")if isinstance(alias_dates, AccountRegionScopedDict):_alias_dates.update(alias_dates)+ grants = data.get("grants")+ if isinstance(grants, AccountRegionScopedDict):+ _grants.update(grants)@@ -1462,14 +1476,204 @@ def _stamp_alias(alias_arn, created):return dates+# ---- Grants ----+#+# Grants are stored and listed, but MiniStack does not evaluate them when+# authorizing other calls, the same way key policies are not evaluated.++_GRANT_OPERATIONS = {+ "Decrypt", "Encrypt", "GenerateDataKey", "GenerateDataKeyWithoutPlaintext",+ "ReEncryptFrom", "ReEncryptTo", "Sign", "Verify", "GetPublicKey",+ "CreateGrant", "RetireGrant", "DescribeKey", "GenerateDataKeyPair",+ "GenerateDataKeyPairWithoutPlaintext", "GenerateMac", "VerifyMac",+ "DeriveSharedSecret",+}+# From the Grants guide: grants for symmetric encryption keys cannot allow+# Sign, Verify, GenerateMac or VerifyMac, and grants for asymmetric keys cannot+# allow operations that generate data keys or data key pairs.+_NOT_FOR_SYMMETRIC = {"Sign", "Verify", "GenerateMac", "VerifyMac"}+_NOT_FOR_ASYMMETRIC = {+ "GenerateDataKey", "GenerateDataKeyWithoutPlaintext",+ "GenerateDataKeyPair", "GenerateDataKeyPairWithoutPlaintext",+}+# HMAC keys support only GenerateMac and VerifyMac as cryptographic+# operations (HMAC keys guide); DescribeKey, CreateGrant and RetireGrant apply+# to every key type (Grants guide).+_HMAC_GRANT_OPERATIONS = {"GenerateMac", "VerifyMac", "DescribeKey", "CreateGrant", "RetireGrant"}+_GRANTS_DEFAULT_LIMIT = 50+_GRANTS_MAX_LIMIT = 100+++def _grant_key(key_id):+ """Resolve a grant operation's KeyId. Grant operations take a key ID or key+ ARN, not an alias."""+ if not key_id or "alias/" in key_id:+ return None+ return _resolve_key(key_id)+++def _is_asymmetric(rec):+ return rec.get("KeySpec", "SYMMETRIC_DEFAULT") != "SYMMETRIC_DEFAULT" and not _is_hmac_key(rec)+++def _grant_operation_error(rec, operations):+ if not isinstance(operations, list) or not operations:+ return "Operations must contain at least one grant operation."+ unknown = sorted(set(operations) - _GRANT_OPERATIONS)+ if unknown:+ return f"{', '.join(unknown)} is not a valid grant operation."+ if _is_hmac_key(rec):+ blocked = sorted(set(operations) - _HMAC_GRANT_OPERATIONS)+ elif rec.get("KeySpec", "SYMMETRIC_DEFAULT") == "SYMMETRIC_DEFAULT":+ blocked = sorted(set(operations) & _NOT_FOR_SYMMETRIC)+ elif _is_asymmetric(rec):+ blocked = sorted(set(operations) & _NOT_FOR_ASYMMETRIC)+ else:+ blocked = []+ if blocked:+ return f"{', '.join(blocked)} is not supported on KMS key {rec['Arn']}."+ return None+++def _grant_entry(grant):+ return {k: v for k, v in grant.items() if not k.startswith("_") and v is not None}+++def _find_grant(rec, grant_id):+ grant = _grants.get(grant_id) if grant_id else None+ return grant if grant and grant["KeyId"] == rec["Arn"] else None+++def _create_grant(data):+ key_id = data.get("KeyId", "")+ rec = _grant_key(key_id)+ if not rec:+ return error_response_json("NotFoundException", f"Key {key_id} not found", 400)+ state_error = _check_key_state(rec)+ if state_error:+ return state_error+ if rec["KeyState"] == "PendingReplicaDeletion":+ # Key states table: CreateGrant fails in this state too.+ return error_response_json(+ "KMSInvalidStateException",+ f"{rec['Arn']} is pending replica deletion.",+ 400,+ )+ grantee = data.get("GranteePrincipal")+ if not grantee:+ return error_response_json("ValidationException", "GranteePrincipal is required.", 400)+ operations = data.get("Operations")+ message = _grant_operation_error(rec, operations)+ if message:+ return error_response_json("ValidationException", message, 400)+ if data.get("DryRun"):+ return _dry_run_error("CreateGrant")++ grant = {+ "KeyId": rec["Arn"],+ "Name": data.get("Name") or "",+ "GranteePrincipal": grantee,+ "RetiringPrincipal": data.get("RetiringPrincipal"),+ "IssuingAccount": f"arn:aws:iam::{get_account_id()}:root",+ "Operations": list(operations),+ "Constraints": data.get("Constraints") or None,+ }+ token = base64.urlsafe_b64encode(os.urandom(48)).decode().rstrip("=")++ # A retry with the same Name and identical parameters returns the original+ # GrantId, with a new token that works for the same grant.+ if grant["Name"]:+ for existing in _grants.values():+ if all(existing.get(k) == v for k, v in grant.items()):+ existing["_tokens"].append(token)+ return json_response({"GrantId": existing["GrantId"], "GrantToken": token})++ grant_id = hashlib.sha256(new_uuid().encode()).hexdigest()+ grant.update({"GrantId": grant_id, "CreationDate": int(time.time()), "_tokens": [token]})+ _grants[grant_id] = grant+ logger.info("Created grant %s on %s for %s", grant_id, rec["KeyId"], grantee)+ return json_response({"GrantId": grant_id, "GrantToken": token})++def _list_grants(data):- # KeyId takes a key ID or key ARN only, not an alias. Grants are not- # modelled, so a key that exists has none.key_id = data.get("KeyId", "")- rec = None if "alias/" in key_id else _resolve_key(key_id)+ rec = _grant_key(key_id)+ if not rec:+ return error_response_json("NotFoundException", f"Key {key_id} not found", 400)+ limit = data.get("Limit", _GRANTS_DEFAULT_LIMIT)+ if not isinstance(limit, int) or not 1 <= limit <= _GRANTS_MAX_LIMIT:+ return error_response_json(+ "ValidationException",+ f"Limit must be between 1 and {_GRANTS_MAX_LIMIT}.",+ 400,+ )++ grants = sorted(+ (g for g in _grants.values() if g["KeyId"] == rec["Arn"]),+ key=lambda g: (g["CreationDate"], g["GrantId"]),+ )+ if data.get("GrantId"):+ grants = [g for g in grants if g["GrantId"] == data["GrantId"]]+ if data.get("GranteePrincipal"):+ grants = [g for g in grants if g["GranteePrincipal"] == data["GranteePrincipal"]]++ start = 0+ marker = data.get("Marker")+ if marker:+ ids = [g["GrantId"] for g in grants]+ if marker not in ids:+ return error_response_json("InvalidMarkerException", "Invalid marker.", 400)+ start = ids.index(marker)++ page = grants[start:start + limit]+ resp = {"Grants": [_grant_entry(g) for g in page], "Truncated": start + limit < len(grants)}+ if resp["Truncated"]:+ resp["NextMarker"] = grants[start + limit]["GrantId"]+ return json_response(resp)+++def _revoke_grant(data):+ key_id = data.get("KeyId", "")+ rec = _grant_key(key_id)if not rec:return error_response_json("NotFoundException", f"Key {key_id} not found", 400)- return json_response({"Grants": [], "Truncated": False})+ grant_id = data.get("GrantId", "")+ grant = _find_grant(rec, grant_id)+ if not grant:+ return error_response_json("NotFoundException", f"Grant {grant_id} not found", 400)+ if data.get("DryRun"):+ return _dry_run_error("RevokeGrant")+ del _grants[grant_id]+ logger.info("Revoked grant %s on %s", grant_id, rec["KeyId"])+ return json_response({})+++def _retire_grant(data):+ """Identify the grant by its token, or by KeyId and GrantId together."""+ token = data.get("GrantToken")+ if token:+ grant = next((g for g in _grants.values() if token in g["_tokens"]), None)+ if not grant:+ return error_response_json("InvalidGrantTokenException", "Invalid grant token.", 400)+ else:+ key_id, grant_id = data.get("KeyId"), data.get("GrantId")+ if not key_id or not grant_id:+ return error_response_json(+ "ValidationException",+ "Specify a GrantToken, or both a KeyId and a GrantId.",+ 400,+ )+ rec = _grant_key(key_id)+ if not rec:+ return error_response_json("NotFoundException", f"Key {key_id} not found", 400)+ grant = _find_grant(rec, grant_id)+ if not grant:+ return error_response_json("NotFoundException", f"Grant {grant_id} not found", 400)+ if data.get("DryRun"):+ return _dry_run_error("RetireGrant")+ del _grants[grant["GrantId"]]+ logger.info("Retired grant %s", grant["GrantId"])+ return json_response({})# ---- Key Rotation ----@@ -2040,7 +2244,10 @@ async def handle_request(method, path, headers, body, query_params):"CreateAlias": _create_alias,"DeleteAlias": _delete_alias,"ListAliases": _list_aliases,+ "CreateGrant": _create_grant,"ListGrants": _list_grants,+ "RevokeGrant": _revoke_grant,+ "RetireGrant": _retire_grant,"UpdateAlias": _update_alias,"EnableKeyRotation": _enable_key_rotation,"DisableKeyRotation": _disable_key_rotation,@@ -2074,3 +2281,4 @@ def reset():_keys.clear()_aliases.clear()_alias_dates.clear()+ _grants.clear()diff --git a/tests/test_kms.py b/tests/test_kms.pyindex 87967f14..c90fc5c3 100644--- a/tests/test_kms.py+++ b/tests/test_kms.py@@ -2450,3 +2450,255 @@ def test_kms_list_grants(kms_client):with pytest.raises(ClientError) as exc:kms_client.list_grants(KeyId=missing)assert exc.value.response["Error"]["Code"] == "NotFoundException"+++def _new_grant_key(kms_client, **kwargs):+ return kms_client.create_key(**kwargs)["KeyMetadata"]+++def test_kms_create_grant_is_listed(kms_client):+ meta = _new_grant_key(kms_client)+ grantee = "arn:aws:iam::000000000000:role/grant-reader"+ resp = kms_client.create_grant(+ KeyId=meta["KeyId"],+ GranteePrincipal=grantee,+ RetiringPrincipal="arn:aws:iam::000000000000:role/grant-retirer",+ Operations=["Encrypt", "Decrypt"],+ Constraints={"EncryptionContextSubset": {"app": "billing"}},+ )+ assert resp["GrantId"] and resp["GrantToken"]++ for key_ref in (meta["KeyId"], meta["Arn"]):+ grants = kms_client.list_grants(KeyId=key_ref)["Grants"]+ assert len(grants) == 1+ grant = grants[0]+ assert grant["GrantId"] == resp["GrantId"]+ assert grant["KeyId"] == meta["Arn"]+ assert grant["GranteePrincipal"] == grantee+ assert grant["RetiringPrincipal"] == "arn:aws:iam::000000000000:role/grant-retirer"+ assert grant["Operations"] == ["Encrypt", "Decrypt"]+ assert grant["Constraints"] == {"EncryptionContextSubset": {"app": "billing"}}+ assert grant["IssuingAccount"].startswith("arn:aws:iam::")+ assert isinstance(grant["CreationDate"], _dt.datetime)+ assert "GrantToken" not in grant+++def test_kms_list_grants_filters(kms_client):+ meta = _new_grant_key(kms_client)+ first = kms_client.create_grant(KeyId=meta["KeyId"], GranteePrincipal="arn:aws:iam::000000000000:role/a", Operations=["Encrypt"])+ kms_client.create_grant(KeyId=meta["KeyId"], GranteePrincipal="arn:aws:iam::000000000000:role/b", Operations=["Decrypt"])+ other = _new_grant_key(kms_client)+ kms_client.create_grant(KeyId=other["KeyId"], GranteePrincipal="arn:aws:iam::000000000000:role/a", Operations=["Encrypt"])++ assert len(kms_client.list_grants(KeyId=meta["KeyId"])["Grants"]) == 2+ by_id = kms_client.list_grants(KeyId=meta["KeyId"], GrantId=first["GrantId"])["Grants"]+ assert [g["GrantId"] for g in by_id] == [first["GrantId"]]+ by_grantee = kms_client.list_grants(KeyId=meta["KeyId"], GranteePrincipal="arn:aws:iam::000000000000:role/b")["Grants"]+ assert [g["GranteePrincipal"] for g in by_grantee] == ["arn:aws:iam::000000000000:role/b"]+++def test_kms_list_grants_paginates(kms_client):+ meta = _new_grant_key(kms_client)+ created = {+ kms_client.create_grant(KeyId=meta["KeyId"], GranteePrincipal=f"arn:aws:iam::000000000000:role/p{i}", Operations=["Encrypt"])["GrantId"]+ for i in range(5)+ }+ seen, marker = [], None+ while True:+ kwargs = {"KeyId": meta["KeyId"], "Limit": 2}+ if marker:+ kwargs["Marker"] = marker+ page = kms_client.list_grants(**kwargs)+ assert len(page["Grants"]) <= 2+ seen += [g["GrantId"] for g in page["Grants"]]+ if not page["Truncated"]:+ assert "NextMarker" not in page+ break+ marker = page["NextMarker"]+ assert len(seen) == len(set(seen)) == 5+ assert set(seen) == created++ with pytest.raises(ClientError) as exc:+ kms_client.list_grants(KeyId=meta["KeyId"], Marker="not-a-marker")+ assert exc.value.response["Error"]["Code"] == "InvalidMarkerException"+++def test_kms_create_grant_with_name_is_idempotent(kms_client):+ meta = _new_grant_key(kms_client)+ params = {"KeyId": meta["KeyId"], "GranteePrincipal": "arn:aws:iam::000000000000:role/n", "Operations": ["Encrypt"], "Name": "retry-safe"}+ first = kms_client.create_grant(**params)+ again = kms_client.create_grant(**params)+ assert again["GrantId"] == first["GrantId"]+ assert again["GrantToken"] != first["GrantToken"]+ assert len(kms_client.list_grants(KeyId=meta["KeyId"])["Grants"]) == 1++ changed = kms_client.create_grant(**{**params, "Operations": ["Decrypt"]})+ assert changed["GrantId"] != first["GrantId"]++ unnamed = {k: v for k, v in params.items() if k != "Name"}+ assert kms_client.create_grant(**unnamed)["GrantId"] != kms_client.create_grant(**unnamed)["GrantId"]+++def test_kms_revoke_grant(kms_client):+ meta = _new_grant_key(kms_client)+ grant_id = kms_client.create_grant(KeyId=meta["KeyId"], GranteePrincipal="arn:aws:iam::000000000000:role/r", Operations=["Encrypt"])["GrantId"]+ kms_client.revoke_grant(KeyId=meta["Arn"], GrantId=grant_id)+ assert kms_client.list_grants(KeyId=meta["KeyId"])["Grants"] == []++ with pytest.raises(ClientError) as exc:+ kms_client.revoke_grant(KeyId=meta["KeyId"], GrantId=grant_id)+ assert exc.value.response["Error"]["Code"] == "NotFoundException"+++def test_kms_revoke_grant_checks_the_key(kms_client):+ meta = _new_grant_key(kms_client)+ other = _new_grant_key(kms_client)+ grant_id = kms_client.create_grant(KeyId=meta["KeyId"], GranteePrincipal="arn:aws:iam::000000000000:role/r", Operations=["Encrypt"])["GrantId"]+ with pytest.raises(ClientError) as exc:+ kms_client.revoke_grant(KeyId=other["KeyId"], GrantId=grant_id)+ assert exc.value.response["Error"]["Code"] == "NotFoundException"+ assert len(kms_client.list_grants(KeyId=meta["KeyId"])["Grants"]) == 1+++def test_kms_retire_grant_by_token_and_by_id(kms_client):+ meta = _new_grant_key(kms_client)+ by_token = kms_client.create_grant(KeyId=meta["KeyId"], GranteePrincipal="arn:aws:iam::000000000000:role/t", Operations=["Encrypt"])+ by_id = kms_client.create_grant(KeyId=meta["KeyId"], GranteePrincipal="arn:aws:iam::000000000000:role/i", Operations=["Encrypt"])++ kms_client.retire_grant(GrantToken=by_token["GrantToken"])+ kms_client.retire_grant(KeyId=meta["Arn"], GrantId=by_id["GrantId"])+ assert kms_client.list_grants(KeyId=meta["KeyId"])["Grants"] == []++ with pytest.raises(ClientError) as exc:+ kms_client.retire_grant(GrantToken=by_token["GrantToken"])+ assert exc.value.response["Error"]["Code"] == "InvalidGrantTokenException"+ with pytest.raises(ClientError) as exc:+ kms_client.retire_grant(GrantId=by_id["GrantId"])+ assert exc.value.response["Error"]["Code"] == "ValidationException"+++def test_kms_create_grant_rejects_operations_the_key_cannot_do(kms_client):+ symmetric = _new_grant_key(kms_client)+ signing = _new_grant_key(kms_client, KeySpec="RSA_2048", KeyUsage="SIGN_VERIFY")+ for key, operation in ((symmetric, "Sign"), (symmetric, "GenerateMac"), (signing, "GenerateDataKey")):+ with pytest.raises(ClientError) as exc:+ kms_client.create_grant(KeyId=key["KeyId"], GranteePrincipal="arn:aws:iam::000000000000:role/v", Operations=[operation])+ assert exc.value.response["Error"]["Code"] == "ValidationException"+ assert kms_client.create_grant(KeyId=signing["KeyId"], GranteePrincipal="arn:aws:iam::000000000000:role/v", Operations=["Sign", "Verify"])["GrantId"]+++def test_kms_create_grant_key_states(kms_client):+ disabled = _new_grant_key(kms_client)+ kms_client.disable_key(KeyId=disabled["KeyId"])+ pending = _new_grant_key(kms_client)+ kms_client.schedule_key_deletion(KeyId=pending["KeyId"], PendingWindowInDays=7)+ for meta, code in ((disabled, "DisabledException"), (pending, "KMSInvalidStateException")):+ with pytest.raises(ClientError) as exc:+ kms_client.create_grant(KeyId=meta["KeyId"], GranteePrincipal="arn:aws:iam::000000000000:role/s", Operations=["Encrypt"])+ assert exc.value.response["Error"]["Code"] == code+ assert kms_client.list_grants(KeyId=meta["KeyId"])["Grants"] == []+++def test_kms_grant_operations_reject_unknown_key_and_alias(kms_client):+ meta = _new_grant_key(kms_client)+ alias = f"alias/grant-{_uuid_mod.uuid4().hex[:8]}"+ kms_client.create_alias(AliasName=alias, TargetKeyId=meta["KeyId"])+ try:+ for key_ref in ("00000000-0000-0000-0000-000000000000", alias):+ with pytest.raises(ClientError) as exc:+ kms_client.create_grant(KeyId=key_ref, GranteePrincipal="arn:aws:iam::000000000000:role/x", Operations=["Encrypt"])+ assert exc.value.response["Error"]["Code"] == "NotFoundException"+ with pytest.raises(ClientError) as exc:+ kms_client.revoke_grant(KeyId=key_ref, GrantId="0" * 64)+ assert exc.value.response["Error"]["Code"] == "NotFoundException"+ finally:+ kms_client.delete_alias(AliasName=alias)+++def test_kms_grant_dry_run_changes_nothing(kms_client):+ meta = _new_grant_key(kms_client)+ with pytest.raises(ClientError) as exc:+ kms_client.create_grant(KeyId=meta["KeyId"], GranteePrincipal="arn:aws:iam::000000000000:role/d", Operations=["Encrypt"], DryRun=True)+ assert exc.value.response["Error"]["Code"] == "DryRunOperationException"+ assert kms_client.list_grants(KeyId=meta["KeyId"])["Grants"] == []++ grant = kms_client.create_grant(KeyId=meta["KeyId"], GranteePrincipal="arn:aws:iam::000000000000:role/d", Operations=["Encrypt"])+ for call in (+ lambda: kms_client.revoke_grant(KeyId=meta["KeyId"], GrantId=grant["GrantId"], DryRun=True),+ lambda: kms_client.retire_grant(GrantToken=grant["GrantToken"], DryRun=True),+ ):+ with pytest.raises(ClientError) as exc:+ call()+ assert exc.value.response["Error"]["Code"] == "DryRunOperationException"+ assert len(kms_client.list_grants(KeyId=meta["KeyId"])["Grants"]) == 1+++def test_kms_grants_survive_persistence(monkeypatch, tmp_path):+ from ministack.core import persistence+ from ministack.core.responses import (+ get_account_id,+ get_region,+ set_request_account_id,+ set_request_region,+ )+ from ministack.services import kms as _kms++ monkeypatch.setattr(persistence, "PERSIST_STATE", True)+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))+ original_account = get_account_id()+ original_region = get_region()+ _kms.reset()+ try:+ set_request_account_id("000000000000")+ set_request_region("us-east-1")+ _status, _headers, body = _kms._create_key({})+ key_id = json.loads(body)["KeyMetadata"]["KeyId"]+ _status, _headers, body = _kms._create_grant({+ "KeyId": key_id,+ "GranteePrincipal": "arn:aws:iam::000000000000:role/persisted",+ "Operations": ["Encrypt"],+ "Name": "persisted",+ })+ created = json.loads(body)++ persistence.save_state("kms", _kms.get_state())+ _kms.reset()+ _kms.load_persisted_state(persistence.load_state("kms"))++ _status, _headers, body = _kms._list_grants({"KeyId": key_id})+ assert [g["GrantId"] for g in json.loads(body)["Grants"]] == [created["GrantId"]]+ status, _headers, _body = _kms._retire_grant({"GrantToken": created["GrantToken"]})+ assert status == 200+ _status, _headers, body = _kms._list_grants({"KeyId": key_id})+ assert json.loads(body)["Grants"] == []+ finally:+ _kms.reset()+ set_request_account_id(original_account)+ set_request_region(original_region)+++def test_kms_create_grant_on_hmac_key_allows_only_mac_operations(kms_client):+ hmac_key = _new_grant_key(kms_client, KeySpec="HMAC_256", KeyUsage="GENERATE_VERIFY_MAC")+ for operations in (["Encrypt"], ["Sign"], ["GenerateDataKey"], ["GetPublicKey"], ["GenerateMac", "Decrypt"]):+ with pytest.raises(ClientError) as exc:+ kms_client.create_grant(KeyId=hmac_key["KeyId"], GranteePrincipal="arn:aws:iam::000000000000:role/h", Operations=operations)+ assert exc.value.response["Error"]["Code"] == "ValidationException"+ assert kms_client.list_grants(KeyId=hmac_key["KeyId"])["Grants"] == []++ allowed = ["GenerateMac", "VerifyMac", "DescribeKey", "CreateGrant", "RetireGrant"]+ kms_client.create_grant(KeyId=hmac_key["KeyId"], GranteePrincipal="arn:aws:iam::000000000000:role/h", Operations=allowed)+ assert kms_client.list_grants(KeyId=hmac_key["KeyId"])["Grants"][0]["Operations"] == allowed+++def test_kms_create_grant_rejects_primary_pending_replica_deletion():+ east, west = _regional_kms("us-east-1"), _regional_kms("us-west-2")+ key_id = east.create_key(MultiRegion=True)["KeyMetadata"]["KeyId"]+ east.replicate_key(KeyId=key_id, ReplicaRegion="us-west-2")+ try:+ assert east.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)["KeyState"] == "PendingReplicaDeletion"+ with pytest.raises(ClientError) as exc:+ east.create_grant(KeyId=key_id, GranteePrincipal="arn:aws:iam::000000000000:role/m", Operations=["Encrypt"])+ assert exc.value.response["Error"]["Code"] == "KMSInvalidStateException"+ assert east.list_grants(KeyId=key_id)["Grants"] == []+ finally:+ west.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)