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/ec2 lambda provided - KMS cryptography - TF v1.1.36 (#114)
Nahuel Nucerab169fb235875
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1a0ab0d7..e89561cc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,29 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [1.1.36] — 2026-04-04++### Added+- **EC2 `ReplaceRouteTableAssociation`** — moves a subnet association from one route table to another; completes full Terraform route table association lifecycle+- **EC2 `ModifyVpcEndpoint`** — add/remove route tables, subnets, and policy on existing VPC endpoints+- **EC2 `DescribePrefixLists`** — returns AWS service prefix lists (S3, DynamoDB) and user-managed prefix lists; required by Terraform for every VPC endpoint+- **EC2 Managed Prefix Lists** — `CreateManagedPrefixList`, `DescribeManagedPrefixLists`, `GetManagedPrefixListEntries`, `ModifyManagedPrefixList`, `DeleteManagedPrefixList`; supports versioned CIDR entry management+- **EC2 VPN Gateways** — `CreateVpnGateway`, `DescribeVpnGateways`, `AttachVpnGateway`, `DetachVpnGateway`, `DeleteVpnGateway`; includes attachment state tracking and `attachment.vpc-id` filter+- **EC2 VPN Route Propagation** — `EnableVgwRoutePropagation`, `DisableVgwRoutePropagation`; tracks propagating VGWs on route tables+- **EC2 Customer Gateways** — `CreateCustomerGateway`, `DescribeCustomerGateways`, `DeleteCustomerGateway`+- **Lambda `provided` runtime support** — `provided.al2023`, `provided.al2` runtimes now execute via Docker using the AWS Lambda RIE; code is mounted to `/var/task` matching real AWS behavior; Go, Rust, and C++ Lambda functions work correctly with companion files accessible at `LAMBDA_TASK_ROOT`+- **KMS Terraform support** — `EnableKeyRotation`, `DisableKeyRotation`, `GetKeyRotationStatus`, `GetKeyPolicy`, `PutKeyPolicy`, `ListKeyPolicies`, `EnableKey`, `DisableKey`, `ScheduleKeyDeletion`, `CancelKeyDeletion`, `TagResource`, `UntagResource`, `ListResourceTags`; KMS now has 27 actions (was 14). Fixes Terraform `aws_kms_key` with `enable_key_rotation = true`. Reported by @betorvs+- **Docker image: `cryptography` package included** — KMS RSA Sign/Verify/GetPublicKey now work out of the box in the Docker image (+20MB image size, 211MB → 231MB)++### Stats+- EC2 now supports **127 actions** (was 109)+- Full Terraform VPC module coverage: 98/98 actions for 20 resource types++### Tests+- 988 tests total, all passing++---+## [1.1.35] — 2026-04-04### Fixeddiff --git a/Dockerfile b/Dockerfileindex b642b324..5ddbf1dd 100644--- a/Dockerfile+++ b/Dockerfile@@ -15,7 +15,8 @@ RUN pip install --no-cache-dir --upgrade pip && \"cbor2>=5.4.0" \"defusedxml>=0.7" \"docker>=7.0.0" \- "pyyaml>=6.0"+ "pyyaml>=6.0" \+ "cryptography>=41.0"COPY ministack/ ministack/diff --git a/README.md b/README.mdindex 0f15c5ae..feaf10c9 100644--- a/README.md+++ b/README.md@@ -54,6 +54,34 @@ That's it. No account, no API key, no sign-up.---+## Internal API++MiniStack exposes internal endpoints for test automation:++```bash+# Health check — returns service status+curl http://localhost:4566/_ministack/health++# Reset all state — wipe every service back to empty (useful between test runs)+curl -X POST http://localhost:4566/_ministack/reset++# Runtime config — change settings without restart+curl -X POST http://localhost:4566/_ministack/config \+ -H "Content-Type: application/json" \+ -d '{"MINISTACK_ACCOUNT_ID": "123456789012"}'+```++The reset endpoint is especially useful in CI pipelines and test suites — call it in `setUp`/`beforeEach` to get a clean environment for every test without restarting the container.++Also compatible with LocalStack's health endpoint:++```bash+curl http://localhost:4566/_localstack/health+curl http://localhost:4566/health+```++---+## Using with AWS CLI```bash@@ -162,6 +190,33 @@ sfn.create_state_machine(roleArn="arn:aws:iam::000000000000:role/role",)+# Step Functions — TestState API (test a single state in isolation)+# Note: inject_host_prefix=False prevents boto3 from prepending "sync-" to the hostname+from botocore.config import Config as BotoConfig+sfn_test = client("stepfunctions", config=BotoConfig(inject_host_prefix=False))++result = sfn_test.test_state(+ definition='{"Type":"Pass","Result":{"greeting":"hello"},"End":true}',+ input='{"name":"world"}',+)+print(result["status"]) # SUCCEEDED+print(result["output"]) # {"greeting": "hello"}++# TestState with mock — test error handling without calling real services+result = sfn_test.test_state(+ definition=json.dumps({+ "Type": "Task",+ "Resource": "arn:aws:lambda:us-east-1:000000000000:function:my-fn",+ "Catch": [{"ErrorEquals": ["States.ALL"], "Next": "Fallback"}],+ "End": True+ }),+ input='{}',+ inspectionLevel="DEBUG",+ mock={"errorOutput": {"error": "ServiceError", "cause": "Timeout"}},+)+print(result["status"]) # CAUGHT_ERROR+print(result["nextState"]) # Fallback+# EC2ec2 = client("ec2")reservation = ec2.run_instances(@@ -202,7 +257,7 @@ subnet = ec2.create_subnet(| **SQS** | CreateQueue, DeleteQueue, ListQueues, GetQueueUrl, GetQueueAttributes, SetQueueAttributes, PurgeQueue, SendMessage, ReceiveMessage, DeleteMessage, ChangeMessageVisibility, ChangeMessageVisibilityBatch, SendMessageBatch, DeleteMessageBatch, TagQueue, UntagQueue, ListQueueTags | Both Query API and JSON protocol; FIFO queues with deduplication; DLQ support || **SNS** | CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes, Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, GetSubscriptionAttributes, SetSubscriptionAttributes, ConfirmSubscription, Publish, PublishBatch, TagResource, UntagResource, ListTagsForResource, CreatePlatformApplication, CreatePlatformEndpoint | SNS→SQS fanout delivery; SNS→Lambda fanout (synchronous invocation) || **DynamoDB** | CreateTable, UpdateTable, DeleteTable, DescribeTable, ListTables, PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem, TransactWriteItems, TransactGetItems, DescribeTimeToLive, UpdateTimeToLive, DescribeContinuousBackups, UpdateContinuousBackups, DescribeEndpoints, TagResource, UntagResource, ListTagsOfResource | TTL enforced via thread-safe background reaper (60s cadence); DynamoDB Streams — `StreamSpecification` emits INSERT/MODIFY/REMOVE records on all write operations, respects `StreamViewType` |-| **Lambda** | CreateFunction, DeleteFunction, GetFunction, GetFunctionConfiguration, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration, AddPermission, RemovePermission, GetPolicy, ListVersionsByFunction, PublishVersion, CreateAlias, GetAlias, UpdateAlias, DeleteAlias, ListAliases, TagResource, UntagResource, ListTags, CreateEventSourceMapping, DeleteEventSourceMapping, GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping, CreateFunctionUrlConfig, GetFunctionUrlConfig, UpdateFunctionUrlConfig, DeleteFunctionUrlConfig, ListFunctionUrlConfigs, PutFunctionConcurrency, GetFunctionConcurrency, DeleteFunctionConcurrency, PutFunctionEventInvokeConfig, GetFunctionEventInvokeConfig, DeleteFunctionEventInvokeConfig, PublishLayerVersion, GetLayerVersion, GetLayerVersionByArn, ListLayerVersions, DeleteLayerVersion, ListLayers, AddLayerVersionPermission, RemoveLayerVersionPermission, GetLayerVersionPolicy | Python and Node.js runtimes execute with warm worker pool; `Publish=True` creates immutable numbered versions; Code via `ZipFile` or `S3Bucket`/`S3Key`; SQS, Kinesis, and DynamoDB Streams event source mappings; Function URL CRUD; Lambda Layers CRUD; Aliases; Concurrency; EventInvokeConfig |+| **Lambda** | CreateFunction, DeleteFunction, GetFunction, GetFunctionConfiguration, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration, AddPermission, RemovePermission, GetPolicy, ListVersionsByFunction, PublishVersion, CreateAlias, GetAlias, UpdateAlias, DeleteAlias, ListAliases, TagResource, UntagResource, ListTags, CreateEventSourceMapping, DeleteEventSourceMapping, GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping, CreateFunctionUrlConfig, GetFunctionUrlConfig, UpdateFunctionUrlConfig, DeleteFunctionUrlConfig, ListFunctionUrlConfigs, PutFunctionConcurrency, GetFunctionConcurrency, DeleteFunctionConcurrency, PutFunctionEventInvokeConfig, GetFunctionEventInvokeConfig, DeleteFunctionEventInvokeConfig, PublishLayerVersion, GetLayerVersion, GetLayerVersionByArn, ListLayerVersions, DeleteLayerVersion, ListLayers, AddLayerVersionPermission, RemoveLayerVersionPermission, GetLayerVersionPolicy | Python and Node.js runtimes execute with warm worker pool; `provided.al2023`/`provided.al2` runtimes execute via Docker RIE (Go, Rust, C++ support); `Publish=True` creates immutable numbered versions; Code via `ZipFile` or `S3Bucket`/`S3Key`; SQS, Kinesis, and DynamoDB Streams event source mappings; Function URL CRUD; Lambda Layers CRUD; Aliases; Concurrency; EventInvokeConfig || **IAM** | CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles, DeleteRole, CreatePolicy, GetPolicy, DeletePolicy, AttachRolePolicy, DetachRolePolicy, PutRolePolicy, GetRolePolicy, DeleteRolePolicy, ListRolePolicies, ListAttachedRolePolicies, CreateAccessKey, ListAccessKeys, DeleteAccessKey, CreateInstanceProfile, GetInstanceProfile, DeleteInstanceProfile, AddRoleToInstanceProfile, RemoveRoleFromInstanceProfile, ListInstanceProfiles, CreateGroup, GetGroup, AddUserToGroup, RemoveUserFromGroup, CreateServiceLinkedRole, DeleteServiceLinkedRole, GetServiceLinkedRoleDeletionStatus, CreateOpenIDConnectProvider, TagRole, UntagRole, TagUser, UntagUser, TagPolicy, UntagPolicy | || **STS** | GetCallerIdentity, AssumeRole, GetSessionToken, AssumeRoleWithWebIdentity | || **SecretsManager** | CreateSecret, GetSecretValue, ListSecrets, DeleteSecret, UpdateSecret, DescribeSecret, PutSecretValue, RestoreSecret, RotateSecret, GetRandomPassword, ListSecretVersionIds, ReplicateSecretToRegions, TagResource, UntagResource, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy, ValidateResourcePolicy | |@@ -272,7 +327,7 @@ Unsupported resource types fail with `CREATE_FAILED` (or `ROLLBACK_COMPLETE` if| **Athena** | StartQueryExecution, GetQueryExecution, GetQueryResults, StopQueryExecution, ListQueryExecutions, BatchGetQueryExecution, CreateWorkGroup, DeleteWorkGroup, GetWorkGroup, ListWorkGroups, UpdateWorkGroup, CreateNamedQuery, DeleteNamedQuery, GetNamedQuery, ListNamedQueries, BatchGetNamedQuery, CreateDataCatalog, GetDataCatalog, ListDataCatalogs, DeleteDataCatalog, UpdateDataCatalog, CreatePreparedStatement, GetPreparedStatement, DeletePreparedStatement, ListPreparedStatements, GetTableMetadata, ListTableMetadata, TagResource, UntagResource, ListTagsForResource | Real SQL via **DuckDB** when installed (`pip install duckdb`), otherwise returns mock results; result pagination; column type metadata || **Firehose** | CreateDeliveryStream, DeleteDeliveryStream, DescribeDeliveryStream, ListDeliveryStreams, PutRecord, PutRecordBatch, UpdateDestination, TagDeliveryStream, UntagDeliveryStream, ListTagsForDeliveryStream, StartDeliveryStreamEncryption, StopDeliveryStreamEncryption | S3 destinations write records to the local S3 emulator; all other destination types buffer in-memory; concurrency-safe `UpdateDestination` via `VersionId` || **Route53** | CreateHostedZone, GetHostedZone, DeleteHostedZone, ListHostedZones, ListHostedZonesByName, UpdateHostedZoneComment, ChangeResourceRecordSets (CREATE/UPSERT/DELETE), ListResourceRecordSets, GetChange, CreateHealthCheck, GetHealthCheck, DeleteHealthCheck, ListHealthChecks, UpdateHealthCheck, ChangeTagsForResource, ListTagsForResource | REST/XML protocol; SOA + NS records auto-created; CallerReference idempotency; alias records, weighted/failover/latency routing; marker-based pagination |-| **EC2** | RunInstances, DescribeInstances, DescribeInstanceAttribute, DescribeInstanceTypes, DescribeVpcAttribute, TerminateInstances, StopInstances, StartInstances, RebootInstances, DescribeImages, CreateSecurityGroup, DeleteSecurityGroup, DescribeSecurityGroups, AuthorizeSecurityGroupIngress, RevokeSecurityGroupIngress, AuthorizeSecurityGroupEgress, RevokeSecurityGroupEgress, CreateKeyPair, DeleteKeyPair, DescribeKeyPairs, ImportKeyPair, CreateVpc, DeleteVpc, DescribeVpcs, ModifyVpcAttribute, CreateSubnet, DeleteSubnet, DescribeSubnets, ModifySubnetAttribute, CreateInternetGateway, DeleteInternetGateway, DescribeInternetGateways, AttachInternetGateway, DetachInternetGateway, CreateRouteTable, DeleteRouteTable, DescribeRouteTables, AssociateRouteTable, DisassociateRouteTable, CreateRoute, ReplaceRoute, DeleteRoute, CreateNetworkInterface, DeleteNetworkInterface, DescribeNetworkInterfaces, AttachNetworkInterface, DetachNetworkInterface, CreateVpcEndpoint, DeleteVpcEndpoints, DescribeVpcEndpoints, DescribeAvailabilityZones, AllocateAddress, ReleaseAddress, AssociateAddress, DisassociateAddress, DescribeAddresses, CreateTags, DeleteTags, DescribeTags, CreateNatGateway, DescribeNatGateways, DeleteNatGateway, CreateNetworkAcl, DescribeNetworkAcls, DeleteNetworkAcl, CreateNetworkAclEntry, DeleteNetworkAclEntry, ReplaceNetworkAclEntry, ReplaceNetworkAclAssociation, CreateFlowLogs, DescribeFlowLogs, DeleteFlowLogs, CreateVpcPeeringConnection, AcceptVpcPeeringConnection, DescribeVpcPeeringConnections, DeleteVpcPeeringConnection, CreateDhcpOptions, AssociateDhcpOptions, DescribeDhcpOptions, DeleteDhcpOptions, CreateEgressOnlyInternetGateway, DescribeEgressOnlyInternetGateways, DeleteEgressOnlyInternetGateway, DescribeInstanceCreditSpecifications, DescribeInstanceMaintenanceOptions, DescribeInstanceAutoRecoveryAttribute, ModifyInstanceMaintenanceOptions, DescribeInstanceTopology, DescribeSpotInstanceRequests, DescribeCapacityReservations | In-memory state only — no real VMs; default VPC, subnet, security group, internet gateway, and route table always present; rules stored but not enforced (matches LocalStack); Terraform v6 compatible |+| **EC2** | RunInstances, DescribeInstances, DescribeInstanceAttribute, DescribeInstanceTypes, DescribeVpcAttribute, TerminateInstances, StopInstances, StartInstances, RebootInstances, DescribeImages, CreateSecurityGroup, DeleteSecurityGroup, DescribeSecurityGroups, AuthorizeSecurityGroupIngress, RevokeSecurityGroupIngress, AuthorizeSecurityGroupEgress, RevokeSecurityGroupEgress, DescribeSecurityGroupRules, CreateKeyPair, DeleteKeyPair, DescribeKeyPairs, ImportKeyPair, CreateVpc, DeleteVpc, DescribeVpcs, ModifyVpcAttribute, CreateSubnet, DeleteSubnet, DescribeSubnets, ModifySubnetAttribute, CreateInternetGateway, DeleteInternetGateway, DescribeInternetGateways, AttachInternetGateway, DetachInternetGateway, CreateRouteTable, DeleteRouteTable, DescribeRouteTables, AssociateRouteTable, DisassociateRouteTable, ReplaceRouteTableAssociation, CreateRoute, ReplaceRoute, DeleteRoute, CreateNetworkInterface, DeleteNetworkInterface, DescribeNetworkInterfaces, AttachNetworkInterface, DetachNetworkInterface, CreateVpcEndpoint, DeleteVpcEndpoints, DescribeVpcEndpoints, ModifyVpcEndpoint, DescribePrefixLists, DescribeAvailabilityZones, AllocateAddress, ReleaseAddress, AssociateAddress, DisassociateAddress, DescribeAddresses, DescribeAddressesAttribute, CreateTags, DeleteTags, DescribeTags, CreateNatGateway, DescribeNatGateways, DeleteNatGateway, CreateNetworkAcl, DescribeNetworkAcls, DeleteNetworkAcl, CreateNetworkAclEntry, DeleteNetworkAclEntry, ReplaceNetworkAclEntry, ReplaceNetworkAclAssociation, CreateFlowLogs, DescribeFlowLogs, DeleteFlowLogs, CreateVpcPeeringConnection, AcceptVpcPeeringConnection, DescribeVpcPeeringConnections, DeleteVpcPeeringConnection, CreateDhcpOptions, AssociateDhcpOptions, DescribeDhcpOptions, DeleteDhcpOptions, CreateEgressOnlyInternetGateway, DescribeEgressOnlyInternetGateways, DeleteEgressOnlyInternetGateway, CreateManagedPrefixList, DescribeManagedPrefixLists, GetManagedPrefixListEntries, ModifyManagedPrefixList, DeleteManagedPrefixList, CreateVpnGateway, DescribeVpnGateways, AttachVpnGateway, DetachVpnGateway, DeleteVpnGateway, EnableVgwRoutePropagation, DisableVgwRoutePropagation, CreateCustomerGateway, DescribeCustomerGateways, DeleteCustomerGateway, DescribeInstanceCreditSpecifications, DescribeInstanceMaintenanceOptions, DescribeInstanceAutoRecoveryAttribute, ModifyInstanceMaintenanceOptions, DescribeInstanceTopology, DescribeSpotInstanceRequests, DescribeCapacityReservations | 127 actions; in-memory state only — no real VMs; CreateVpc provisions per-VPC default route table, network ACL, and security group; full Terraform VPC module v6.6.0 compatible; VPN/Customer gateways, managed prefix lists, VPC endpoints with modify support || **EBS** | CreateVolume, DeleteVolume, DescribeVolumes, DescribeVolumeStatus, AttachVolume, DetachVolume, ModifyVolume, DescribeVolumesModifications, EnableVolumeIO, ModifyVolumeAttribute, DescribeVolumeAttribute, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, CopySnapshot, ModifySnapshotAttribute, DescribeSnapshotAttribute | Part of EC2 Query/XML service; attach/detach updates volume state; snapshots stored as completed immediately; Pro-only on LocalStack — free here || **EFS** | CreateFileSystem, DescribeFileSystems, DeleteFileSystem, UpdateFileSystem, CreateMountTarget, DescribeMountTargets, DeleteMountTarget, DescribeMountTargetSecurityGroups, ModifyMountTargetSecurityGroups, CreateAccessPoint, DescribeAccessPoints, DeleteAccessPoint, TagResource, UntagResource, ListTagsForResource, PutLifecycleConfiguration, DescribeLifecycleConfiguration, PutBackupPolicy, DescribeBackupPolicy, DescribeAccountPreferences, PutAccountPreferences | REST/JSON `/2015-02-01/*`; CreationToken idempotency; FileSystem deletion blocked when mount targets exist; Pro-only on LocalStack — free here || **EMR** | RunJobFlow, DescribeCluster, ListClusters, TerminateJobFlows, ModifyCluster, SetTerminationProtection, SetVisibleToAllUsers, AddJobFlowSteps, DescribeStep, ListSteps, CancelSteps, AddInstanceFleet, ListInstanceFleets, ModifyInstanceFleet, AddInstanceGroups, ListInstanceGroups, ModifyInstanceGroups, ListBootstrapActions, AddTags, RemoveTags, GetBlockPublicAccessConfiguration, PutBlockPublicAccessConfiguration | Control plane only — no real Spark/Hadoop; clusters start in WAITING (KeepAlive=true) or TERMINATED (KeepAlive=false); steps stored as COMPLETED immediately; all three instance modes (simple, InstanceGroups, InstanceFleets); TerminationProtected enforced; Pro-only on LocalStack — free here |@@ -619,6 +674,27 @@ provider "aws" {}```+**Terraform VPC module** — fully supported (v6.6.0):++```hcl+module "vpc" {+ source = "terraform-aws-modules/vpc/aws"+ version = "6.6.0"++ name = "my-vpc"+ cidr = "10.0.0.0/16"++ azs = ["us-east-1a", "us-east-1b", "us-east-1c"]+ private_subnets = ["10.0.0.0/20", "10.0.16.0/20", "10.0.32.0/20"]+ public_subnets = ["10.0.64.0/20", "10.0.80.0/20", "10.0.96.0/20"]++ enable_nat_gateway = true+ single_nat_gateway = true+}+```++Creates VPC with per-VPC default network ACL, security group, and main route table. All 23 resources (subnets, IGW, NAT, route tables, associations, routes, default resources) supported.+### AWS CDK```typescriptdiff --git a/ministack/services/ec2.py b/ministack/services/ec2.pyindex 74accf2f..95384acb 100644--- a/ministack/services/ec2.py+++ b/ministack/services/ec2.py@@ -19,11 +19,12 @@ Supports:Tags: CreateTags, DeleteTags, DescribeTagsVPC attributes: ModifyVpcAttribute, ModifySubnetAttributeRoute Tables: CreateRouteTable, DeleteRouteTable, DescribeRouteTables,- AssociateRouteTable, DisassociateRouteTable,+ AssociateRouteTable, DisassociateRouteTable, ReplaceRouteTableAssociation,CreateRoute, ReplaceRoute, DeleteRouteENI: CreateNetworkInterface, DeleteNetworkInterface, DescribeNetworkInterfaces,AttachNetworkInterface, DetachNetworkInterface- VPC Endpoints: CreateVpcEndpoint, DeleteVpcEndpoints, DescribeVpcEndpoints+ VPC Endpoints: CreateVpcEndpoint, DeleteVpcEndpoints, DescribeVpcEndpoints,+ ModifyVpcEndpoint, DescribePrefixListsEBS Volumes: CreateVolume, DeleteVolume, DescribeVolumes, DescribeVolumeStatus,AttachVolume, DetachVolume, ModifyVolume, DescribeVolumesModifications,EnableVolumeIO, ModifyVolumeAttribute, DescribeVolumeAttribute@@ -40,6 +41,14 @@ Supports:DeleteDhcpOptionsEgress IGW: CreateEgressOnlyInternetGateway, DescribeEgressOnlyInternetGateways,DeleteEgressOnlyInternetGateway+ Prefix Lists: CreateManagedPrefixList, DescribeManagedPrefixLists,+ GetManagedPrefixListEntries, ModifyManagedPrefixList,+ DeleteManagedPrefixList+ VPN Gateways: CreateVpnGateway, DescribeVpnGateways, AttachVpnGateway,+ DetachVpnGateway, DeleteVpnGateway,+ EnableVgwRoutePropagation, DisableVgwRoutePropagation+ Customer GW: CreateCustomerGateway, DescribeCustomerGateways,+ DeleteCustomerGateway"""import copy@@ -82,6 +91,9 @@ _flow_logs: dict = {} # flow_log_id -> flow log record_vpc_peering: dict = {} # pcx_id -> peering connection record_dhcp_options: dict = {} # dopt_id -> DHCP options record_egress_igws: dict = {} # eigw_id -> egress-only internet gateway record+_prefix_lists: dict = {} # pl_id -> managed prefix list record+_vpn_gateways: dict = {} # vgw_id -> VPN gateway record+_customer_gateways: dict = {} # cgw_id -> customer gateway record# ── Persistence ────────────────────────────────────────────@@ -107,6 +119,9 @@ def get_state():"vpc_peering": copy.deepcopy(_vpc_peering),"dhcp_options": copy.deepcopy(_dhcp_options),"egress_igws": copy.deepcopy(_egress_igws),+ "prefix_lists": copy.deepcopy(_prefix_lists),+ "vpn_gateways": copy.deepcopy(_vpn_gateways),+ "customer_gateways": copy.deepcopy(_customer_gateways),}@@ -131,6 +146,9 @@ def restore_state(data):_vpc_peering.update(data.get("vpc_peering", {}))_dhcp_options.update(data.get("dhcp_options", {}))_egress_igws.update(data.get("egress_igws", {}))+ _prefix_lists.update(data.get("prefix_lists", {}))+ _vpn_gateways.update(data.get("vpn_gateways", {}))+ _customer_gateways.update(data.get("customer_gateways", {}))_restored = load_state("ec2")@@ -2412,6 +2430,359 @@ def _delete_egress_only_igw(params):return _xml(200, "DeleteEgressOnlyInternetGatewayResponse", "<returnCode>true</returnCode>")+# ---------------------------------------------------------------------------+# ReplaceRouteTableAssociation+# ---------------------------------------------------------------------------++def _replace_route_table_association(p):+ assoc_id = _p(p, "AssociationId")+ new_rtb_id = _p(p, "RouteTableId")+ if new_rtb_id not in _route_tables:+ return _error("InvalidRouteTableID.NotFound", f"The route table '{new_rtb_id}' does not exist", 400)+ new_assoc_id = "rtbassoc-" + "".join(random.choices(string.hexdigits[:16], k=17))+ for rtb in _route_tables.values():+ for i, a in enumerate(rtb["Associations"]):+ if a["RouteTableAssociationId"] == assoc_id:+ subnet_id = a.get("SubnetId")+ is_main = a.get("Main", False)+ rtb["Associations"].pop(i)+ _route_tables[new_rtb_id]["Associations"].append({+ "RouteTableAssociationId": new_assoc_id,+ "RouteTableId": new_rtb_id,+ "SubnetId": subnet_id,+ "Main": is_main,+ "AssociationState": {"State": "associated"},+ })+ return _xml(200, "ReplaceRouteTableAssociationResponse",+ f"<newAssociationId>{new_assoc_id}</newAssociationId>")+ return _error("InvalidAssociationID.NotFound", f"Association '{assoc_id}' not found", 400)+++# ---------------------------------------------------------------------------+# ModifyVpcEndpoint+# ---------------------------------------------------------------------------++def _modify_vpc_endpoint(p):+ vpce_id = _p(p, "VpcEndpointId")+ ep = _vpc_endpoints.get(vpce_id)+ if not ep:+ return _error("InvalidVpcEndpointId.NotFound", f"The VPC endpoint '{vpce_id}' does not exist", 400)+ add_rtbs = _parse_member_list(p, "AddRouteTableId")+ rm_rtbs = _parse_member_list(p, "RemoveRouteTableId")+ add_subnets = _parse_member_list(p, "AddSubnetId")+ rm_subnets = _parse_member_list(p, "RemoveSubnetId")+ if add_rtbs:+ ep["RouteTableIds"] = list(set(ep.get("RouteTableIds", []) + add_rtbs))+ if rm_rtbs:+ ep["RouteTableIds"] = [r for r in ep.get("RouteTableIds", []) if r not in rm_rtbs]+ if add_subnets:+ ep["SubnetIds"] = list(set(ep.get("SubnetIds", []) + add_subnets))+ if rm_subnets:+ ep["SubnetIds"] = [s for s in ep.get("SubnetIds", []) if s not in rm_subnets]+ policy = _p(p, "PolicyDocument")+ if policy:+ ep["PolicyDocument"] = policy+ return _xml(200, "ModifyVpcEndpointResponse", "<return>true</return>")+++# ---------------------------------------------------------------------------+# DescribePrefixLists+# ---------------------------------------------------------------------------++_AWS_PREFIX_LISTS = {+ "com.amazonaws.{region}.s3": ("pl-63a5400a", "com.amazonaws.{region}.s3"),+ "com.amazonaws.{region}.dynamodb": ("pl-02cd2c6b", "com.amazonaws.{region}.dynamodb"),+}++def _describe_prefix_lists(p):+ filter_ids = _parse_member_list(p, "PrefixListId")+ filters = _parse_filters(p)+ items = ""+ # Built-in AWS service prefix lists+ for tpl_svc, (pl_id, tpl_name) in _AWS_PREFIX_LISTS.items():+ svc = tpl_svc.replace("{region}", REGION)+ name = tpl_name.replace("{region}", REGION)+ if filter_ids and pl_id not in filter_ids:+ continue+ if filters.get("prefix-list-name") and name not in filters["prefix-list-name"]:+ continue+ items += f"""<item>+ <prefixListId>{pl_id}</prefixListId>+ <prefixListName>{name}</prefixListName>+ <cidrSet><item><cidr>0.0.0.0/0</cidr></item></cidrSet>+ </item>"""+ # User-created managed prefix lists+ for pl in _prefix_lists.values():+ if filter_ids and pl["PrefixListId"] not in filter_ids:+ continue+ if filters.get("prefix-list-name") and pl.get("PrefixListName", "") not in filters["prefix-list-name"]:+ continue+ entries = "".join(f"<item><cidr>{e['Cidr']}</cidr></item>" for e in pl.get("Entries", []))+ items += f"""<item>+ <prefixListId>{pl['PrefixListId']}</prefixListId>+ <prefixListName>{pl.get('PrefixListName','')}</prefixListName>+ <cidrSet>{entries}</cidrSet>+ </item>"""+ return _xml(200, "DescribePrefixListsResponse", f"<prefixListSet>{items}</prefixListSet>")+++# ---------------------------------------------------------------------------+# Managed Prefix Lists+# ---------------------------------------------------------------------------++def _create_managed_prefix_list(p):+ name = _p(p, "PrefixListName") or ""+ max_entries = int(_p(p, "MaxEntries") or "10")+ af = _p(p, "AddressFamily") or "IPv4"+ pl_id = "pl-" + "".join(random.choices(string.hexdigits[:16], k=17))+ entries = []+ i = 1+ while _p(p, f"Entry.{i}.Cidr"):+ entries.append({"Cidr": _p(p, f"Entry.{i}.Cidr"), "Description": _p(p, f"Entry.{i}.Description")})+ i += 1+ tags = _parse_tags(p)+ _prefix_lists[pl_id] = {+ "PrefixListId": pl_id, "PrefixListName": name, "State": "create-complete",+ "AddressFamily": af, "MaxEntries": max_entries, "Version": 1,+ "Entries": entries, "Tags": tags, "OwnerId": ACCOUNT_ID,+ "PrefixListArn": f"arn:aws:ec2:{REGION}:{ACCOUNT_ID}:prefix-list/{pl_id}",+ }+ if tags:+ _tags[pl_id] = tags+ return _xml(200, "CreateManagedPrefixListResponse", _prefix_list_xml(_prefix_lists[pl_id], tag="prefixList"))+++def _describe_managed_prefix_lists(p):+ filter_ids = _parse_member_list(p, "PrefixListId")+ filters = _parse_filters(p)+ items = ""+ for pl in _prefix_lists.values():+ if filter_ids and pl["PrefixListId"] not in filter_ids:+ continue+ if filters.get("prefix-list-name") and pl.get("PrefixListName", "") not in filters["prefix-list-name"]:+ continue+ items += _prefix_list_xml(pl)+ return _xml(200, "DescribeManagedPrefixListsResponse", f"<prefixListSet>{items}</prefixListSet>")+++def _get_managed_prefix_list_entries(p):+ pl_id = _p(p, "PrefixListId")+ pl = _prefix_lists.get(pl_id)+ if not pl:+ return _error("InvalidPrefixListID.NotFound", f"Prefix list '{pl_id}' not found", 400)+ entries = "".join(f"""<item>+ <cidr>{e['Cidr']}</cidr>+ <description>{e.get('Description','')}</description>+ </item>""" for e in pl.get("Entries", []))+ return _xml(200, "GetManagedPrefixListEntriesResponse", f"<entrySet>{entries}</entrySet>")+++def _modify_managed_prefix_list(p):+ pl_id = _p(p, "PrefixListId")+ pl = _prefix_lists.get(pl_id)+ if not pl:+ return _error("InvalidPrefixListID.NotFound", f"Prefix list '{pl_id}' not found", 400)+ name = _p(p, "PrefixListName")+ if name:+ pl["PrefixListName"] = name+ max_e = _p(p, "MaxEntries")+ if max_e:+ pl["MaxEntries"] = int(max_e)+ # Add entries+ i = 1+ while _p(p, f"AddEntry.{i}.Cidr"):+ pl["Entries"].append({"Cidr": _p(p, f"AddEntry.{i}.Cidr"), "Description": _p(p, f"AddEntry.{i}.Description")})+ i += 1+ # Remove entries+ i = 1+ rm_cidrs = set()+ while _p(p, f"RemoveEntry.{i}.Cidr"):+ rm_cidrs.add(_p(p, f"RemoveEntry.{i}.Cidr"))+ i += 1+ if rm_cidrs:+ pl["Entries"] = [e for e in pl["Entries"] if e["Cidr"] not in rm_cidrs]+ pl["Version"] = pl.get("Version", 1) + 1+ return _xml(200, "ModifyManagedPrefixListResponse", _prefix_list_xml(pl, tag="prefixList"))+++def _delete_managed_prefix_list(p):+ pl_id = _p(p, "PrefixListId")+ if pl_id not in _prefix_lists:+ return _error("InvalidPrefixListID.NotFound", f"Prefix list '{pl_id}' not found", 400)+ del _prefix_lists[pl_id]+ return _xml(200, "DeleteManagedPrefixListResponse", "<return>true</return>")+++def _prefix_list_xml(pl, tag="item"):+ return f"""<{tag}>+ <prefixListId>{pl['PrefixListId']}</prefixListId>+ <prefixListName>{pl.get('PrefixListName','')}</prefixListName>+ <state>{pl.get('State','create-complete')}</state>+ <addressFamily>{pl.get('AddressFamily','IPv4')}</addressFamily>+ <maxEntries>{pl.get('MaxEntries',10)}</maxEntries>+ <version>{pl.get('Version',1)}</version>+ <prefixListArn>{pl.get('PrefixListArn','')}</prefixListArn>+ <ownerId>{pl.get('OwnerId', ACCOUNT_ID)}</ownerId>+ <tagSet/>+ </{tag}>"""+++# ---------------------------------------------------------------------------+# VPN Gateways+# ---------------------------------------------------------------------------++def _create_vpn_gateway(p):+ gw_type = _p(p, "Type") or "ipsec.1"+ az = _p(p, "AvailabilityZone") or ""+ asn = _p(p, "AmazonSideAsn") or "64512"+ vgw_id = "vgw-" + "".join(random.choices(string.hexdigits[:16], k=17))+ tags = _parse_tags(p)+ _vpn_gateways[vgw_id] = {+ "VpnGatewayId": vgw_id, "Type": gw_type, "State": "available",+ "AvailabilityZone": az, "AmazonSideAsn": asn,+ "Attachments": [], "Tags": tags, "OwnerId": ACCOUNT_ID,+ }+ if tags:+ _tags[vgw_id] = tags+ return _xml(200, "CreateVpnGatewayResponse", _vgw_xml(_vpn_gateways[vgw_id], tag="vpnGateway"))+++def _describe_vpn_gateways(p):+ filter_ids = _parse_member_list(p, "VpnGatewayId")+ filters = _parse_filters(p)+ items = ""+ for vgw in _vpn_gateways.values():+ if filter_ids and vgw["VpnGatewayId"] not in filter_ids:+ continue+ if filters.get("attachment.vpc-id"):+ vpc_ids = [a["VpcId"] for a in vgw.get("Attachments", [])]+ if not any(v in vpc_ids for v in filters["attachment.vpc-id"]):+ continue+ items += _vgw_xml(vgw)+ return _xml(200, "DescribeVpnGatewaysResponse", f"<vpnGatewaySet>{items}</vpnGatewaySet>")+++def _attach_vpn_gateway(p):+ vgw_id = _p(p, "VpnGatewayId")+ vpc_id = _p(p, "VpcId")+ vgw = _vpn_gateways.get(vgw_id)+ if not vgw:+ return _error("InvalidVpnGatewayID.NotFound", f"VPN gateway '{vgw_id}' not found", 400)+ vgw["Attachments"] = [{"VpcId": vpc_id, "State": "attached"}]+ return _xml(200, "AttachVpnGatewayResponse",+ f"<attachment><vpcId>{vpc_id}</vpcId><state>attached</state></attachment>")+++def _detach_vpn_gateway(p):+ vgw_id = _p(p, "VpnGatewayId")+ vgw = _vpn_gateways.get(vgw_id)+ if not vgw:+ return _error("InvalidVpnGatewayID.NotFound", f"VPN gateway '{vgw_id}' not found", 400)+ vgw["Attachments"] = []+ vgw["State"] = "detached"+ return _xml(200, "DetachVpnGatewayResponse", "<return>true</return>")+++def _delete_vpn_gateway(p):+ vgw_id = _p(p, "VpnGatewayId")+ if vgw_id not in _vpn_gateways:+ return _error("InvalidVpnGatewayID.NotFound", f"VPN gateway '{vgw_id}' not found", 400)+ del _vpn_gateways[vgw_id]+ return _xml(200, "DeleteVpnGatewayResponse", "<return>true</return>")+++def _vgw_xml(vgw, tag="item"):+ attachments = "".join(+ f"<item><vpcId>{a['VpcId']}</vpcId><state>{a['State']}</state></item>"+ for a in vgw.get("Attachments", [])+ )+ return f"""<{tag}>+ <vpnGatewayId>{vgw['VpnGatewayId']}</vpnGatewayId>+ <state>{vgw['State']}</state>+ <type>{vgw['Type']}</type>+ <availabilityZone>{vgw.get('AvailabilityZone','')}</availabilityZone>+ <amazonSideAsn>{vgw.get('AmazonSideAsn','64512')}</amazonSideAsn>+ <attachments>{attachments}</attachments>+ <tagSet/>+ </{tag}>"""+++# ---------------------------------------------------------------------------+# VPN Gateway Route Propagation+# ---------------------------------------------------------------------------++def _enable_vgw_route_propagation(p):+ rtb_id = _p(p, "RouteTableId")+ vgw_id = _p(p, "GatewayId")+ rtb = _route_tables.get(rtb_id)+ if not rtb:+ return _error("InvalidRouteTableID.NotFound", f"Route table '{rtb_id}' not found", 400)+ propagating = rtb.setdefault("PropagatingVgws", [])+ if vgw_id not in propagating:+ propagating.append(vgw_id)+ return _xml(200, "EnableVgwRoutePropagationResponse", "<return>true</return>")+++def _disable_vgw_route_propagation(p):+ rtb_id = _p(p, "RouteTableId")+ vgw_id = _p(p, "GatewayId")+ rtb = _route_tables.get(rtb_id)+ if not rtb:+ return _error("InvalidRouteTableID.NotFound", f"Route table '{rtb_id}' not found", 400)+ propagating = rtb.get("PropagatingVgws", [])+ if vgw_id in propagating:+ propagating.remove(vgw_id)+ return _xml(200, "DisableVgwRoutePropagationResponse", "<return>true</return>")+++# ---------------------------------------------------------------------------+# Customer Gateways+# ---------------------------------------------------------------------------++def _create_customer_gateway(p):+ bgp_asn = _p(p, "BgpAsn") or "65000"+ ip_address = _p(p, "IpAddress") or _p(p, "PublicIp") or ""+ gw_type = _p(p, "Type") or "ipsec.1"+ cgw_id = "cgw-" + "".join(random.choices(string.hexdigits[:16], k=17))+ tags = _parse_tags(p)+ _customer_gateways[cgw_id] = {+ "CustomerGatewayId": cgw_id, "BgpAsn": bgp_asn, "IpAddress": ip_address,+ "Type": gw_type, "State": "available", "Tags": tags, "OwnerId": ACCOUNT_ID,+ }+ if tags:+ _tags[cgw_id] = tags+ return _xml(200, "CreateCustomerGatewayResponse", _cgw_xml(_customer_gateways[cgw_id], tag="customerGateway"))+++def _describe_customer_gateways(p):+ filter_ids = _parse_member_list(p, "CustomerGatewayId")+ items = ""+ for cgw in _customer_gateways.values():+ if filter_ids and cgw["CustomerGatewayId"] not in filter_ids:+ continue+ items += _cgw_xml(cgw)+ return _xml(200, "DescribeCustomerGatewaysResponse", f"<customerGatewaySet>{items}</customerGatewaySet>")+++def _delete_customer_gateway(p):+ cgw_id = _p(p, "CustomerGatewayId")+ if cgw_id not in _customer_gateways:+ return _error("InvalidCustomerGatewayID.NotFound", f"Customer gateway '{cgw_id}' not found", 400)+ del _customer_gateways[cgw_id]+ return _xml(200, "DeleteCustomerGatewayResponse", "<return>true</return>")+++def _cgw_xml(cgw, tag="item"):+ return f"""<{tag}>+ <customerGatewayId>{cgw['CustomerGatewayId']}</customerGatewayId>+ <bgpAsn>{cgw['BgpAsn']}</bgpAsn>+ <ipAddress>{cgw['IpAddress']}</ipAddress>+ <type>{cgw['Type']}</type>+ <state>{cgw['State']}</state>+ <tagSet/>+ </{tag}>"""++# ---------------------------------------------------------------------------# Reset# ---------------------------------------------------------------------------@@ -2436,6 +2807,9 @@ def reset():_vpc_peering.clear()_dhcp_options.clear()_egress_igws.clear()+ _prefix_lists.clear()+ _vpn_gateways.clear()+ _customer_gateways.clear()_init_defaults()@@ -2731,6 +3105,24 @@ _ACTION_MAP = {"CreateVpcEndpoint": _create_vpc_endpoint,"DeleteVpcEndpoints": _delete_vpc_endpoints,"DescribeVpcEndpoints": _describe_vpc_endpoints,+ "ReplaceRouteTableAssociation": _replace_route_table_association,+ "ModifyVpcEndpoint": _modify_vpc_endpoint,+ "DescribePrefixLists": _describe_prefix_lists,+ "CreateManagedPrefixList": _create_managed_prefix_list,+ "DescribeManagedPrefixLists": _describe_managed_prefix_lists,+ "GetManagedPrefixListEntries": _get_managed_prefix_list_entries,+ "ModifyManagedPrefixList": _modify_managed_prefix_list,+ "DeleteManagedPrefixList": _delete_managed_prefix_list,+ "CreateVpnGateway": _create_vpn_gateway,+ "DescribeVpnGateways": _describe_vpn_gateways,+ "AttachVpnGateway": _attach_vpn_gateway,+ "DetachVpnGateway": _detach_vpn_gateway,+ "DeleteVpnGateway": _delete_vpn_gateway,+ "EnableVgwRoutePropagation": _enable_vgw_route_propagation,+ "DisableVgwRoutePropagation": _disable_vgw_route_propagation,+ "CreateCustomerGateway": _create_customer_gateway,+ "DescribeCustomerGateways": _describe_customer_gateways,+ "DeleteCustomerGateway": _delete_customer_gateway,# EBS Volumes"CreateVolume": _create_volume,"DeleteVolume": _delete_volume,diff --git a/ministack/services/kms.py b/ministack/services/kms.pyindex bd274994..e29d98fb 100644--- a/ministack/services/kms.py+++ b/ministack/services/kms.py@@ -656,6 +656,150 @@ def _update_alias(data):return json_response({})+# ---- Key Rotation ----+++def _enable_key_rotation(data):+ rec = _resolve_key(data.get("KeyId", ""))+ if not rec:+ return error_response_json("NotFoundException", f"Key {data.get('KeyId', '')} not found", 400)+ rec["KeyRotationEnabled"] = True+ rec["RotationPeriodInDays"] = data.get("RotationPeriodInDays", 365)+ return json_response({})+++def _disable_key_rotation(data):+ rec = _resolve_key(data.get("KeyId", ""))+ if not rec:+ return error_response_json("NotFoundException", f"Key {data.get('KeyId', '')} not found", 400)+ rec["KeyRotationEnabled"] = False+ return json_response({})+++def _get_key_rotation_status(data):+ rec = _resolve_key(data.get("KeyId", ""))+ if not rec:+ return error_response_json("NotFoundException", f"Key {data.get('KeyId', '')} not found", 400)+ return json_response({+ "KeyRotationEnabled": rec.get("KeyRotationEnabled", False),+ "RotationPeriodInDays": rec.get("RotationPeriodInDays", 365),+ })+++# ---- Key Policy ----+++def _get_key_policy(data):+ rec = _resolve_key(data.get("KeyId", ""))+ if not rec:+ return error_response_json("NotFoundException", f"Key {data.get('KeyId', '')} not found", 400)+ policy = rec.get("Policy", json.dumps({+ "Version": "2012-10-17",+ "Id": "key-default-1",+ "Statement": [{+ "Sid": "Enable IAM User Permissions",+ "Effect": "Allow",+ "Principal": {"AWS": f"arn:aws:iam::{ACCOUNT_ID}:root"},+ "Action": "kms:*",+ "Resource": "*",+ }],+ }))+ return json_response({"Policy": policy, "PolicyName": "default"})+++def _put_key_policy(data):+ rec = _resolve_key(data.get("KeyId", ""))+ if not rec:+ return error_response_json("NotFoundException", f"Key {data.get('KeyId', '')} not found", 400)+ rec["Policy"] = data.get("Policy", "")+ return json_response({})+++def _list_key_policies(data):+ rec = _resolve_key(data.get("KeyId", ""))+ if not rec:+ return error_response_json("NotFoundException", f"Key {data.get('KeyId', '')} not found", 400)+ return json_response({"PolicyNames": ["default"], "Truncated": False})+++# ---- Enable / Disable / Schedule Deletion ----+++def _enable_key(data):+ rec = _resolve_key(data.get("KeyId", ""))+ if not rec:+ return error_response_json("NotFoundException", f"Key {data.get('KeyId', '')} not found", 400)+ rec["Enabled"] = True+ rec["KeyState"] = "Enabled"+ return json_response({})+++def _disable_key(data):+ rec = _resolve_key(data.get("KeyId", ""))+ if not rec:+ return error_response_json("NotFoundException", f"Key {data.get('KeyId', '')} not found", 400)+ rec["Enabled"] = False+ rec["KeyState"] = "Disabled"+ return json_response({})+++def _schedule_key_deletion(data):+ rec = _resolve_key(data.get("KeyId", ""))+ if not rec:+ return error_response_json("NotFoundException", f"Key {data.get('KeyId', '')} not found", 400)+ days = data.get("PendingWindowInDays", 30)+ rec["KeyState"] = "PendingDeletion"+ rec["Enabled"] = False+ rec["DeletionDate"] = time.time() + (days * 86400)+ return json_response({+ "KeyId": rec["KeyId"],+ "KeyState": "PendingDeletion",+ "DeletionDate": rec["DeletionDate"],+ })+++def _cancel_key_deletion(data):+ rec = _resolve_key(data.get("KeyId", ""))+ if not rec:+ return error_response_json("NotFoundException", f"Key {data.get('KeyId', '')} not found", 400)+ rec["KeyState"] = "Disabled"+ rec.pop("DeletionDate", None)+ return json_response({"KeyId": rec["KeyId"]})+++# ---- Tags ----+++def _tag_resource(data):+ rec = _resolve_key(data.get("KeyId", ""))+ if not rec:+ return error_response_json("NotFoundException", f"Key {data.get('KeyId', '')} not found", 400)+ tags = rec.setdefault("Tags", [])+ for tag in data.get("Tags", []):+ existing = next((t for t in tags if t["TagKey"] == tag["TagKey"]), None)+ if existing:+ existing["TagValue"] = tag["TagValue"]+ else:+ tags.append(tag)+ return json_response({})+++def _untag_resource(data):+ rec = _resolve_key(data.get("KeyId", ""))+ if not rec:+ return error_response_json("NotFoundException", f"Key {data.get('KeyId', '')} not found", 400)+ remove_keys = set(data.get("TagKeys", []))+ rec["Tags"] = [t for t in rec.get("Tags", []) if t["TagKey"] not in remove_keys]+ return json_response({})+++def _list_resource_tags(data):+ rec = _resolve_key(data.get("KeyId", ""))+ if not rec:+ return error_response_json("NotFoundException", f"Key {data.get('KeyId', '')} not found", 400)+ return json_response({"Tags": rec.get("Tags", []), "Truncated": False})++# ---- Request handler ----async def handle_request(method, path, headers, body, query_params):@@ -682,6 +826,19 @@ async def handle_request(method, path, headers, body, query_params):"DeleteAlias": _delete_alias,"ListAliases": _list_aliases,"UpdateAlias": _update_alias,+ "EnableKeyRotation": _enable_key_rotation,+ "DisableKeyRotation": _disable_key_rotation,+ "GetKeyRotationStatus": _get_key_rotation_status,+ "GetKeyPolicy": _get_key_policy,+ "PutKeyPolicy": _put_key_policy,+ "ListKeyPolicies": _list_key_policies,+ "EnableKey": _enable_key,+ "DisableKey": _disable_key,+ "ScheduleKeyDeletion": _schedule_key_deletion,+ "CancelKeyDeletion": _cancel_key_deletion,+ "TagResource": _tag_resource,+ "UntagResource": _untag_resource,+ "ListResourceTags": _list_resource_tags,}handler = handlers.get(action)diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 9869e7d3..20df8b70 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -937,6 +937,9 @@ _RUNTIME_IMAGE_MAP: dict[str, str] = {"nodejs16.x": "node:16-slim","nodejs18.x": "node:18-slim","nodejs20.x": "node:20-slim",+ "provided.al2023": "public.ecr.aws/lambda/provided:al2023",+ "provided.al2": "public.ecr.aws/lambda/provided:al2",+ "provided": "public.ecr.aws/lambda/provided:al2023",}@@ -949,6 +952,8 @@ def _docker_image_for_runtime(runtime: str) -> str | None:if runtime.startswith("nodejs"):ver = runtime.replace("nodejs", "").rstrip(".x")return f"node:{ver}-slim"+ if runtime.startswith("provided"):+ return "public.ecr.aws/lambda/provided:al2023"return None@@ -986,12 +991,13 @@ def _execute_function_docker(func: dict, event: dict) -> dict:},}+ is_provided = runtime.startswith("provided")is_node = runtime.startswith("nodejs")- if not runtime.startswith("python") and not is_node:+ if not runtime.startswith("python") and not is_node and not is_provided:return {"body": {"statusCode": 200,- "body": f"Mock response - {runtime} docker wrapper only supports Python and Node.js runtimes",+ "body": f"Mock response - {runtime} docker wrapper only supports Python, Node.js, and provided runtimes",},}@@ -1028,9 +1034,10 @@ def _execute_function_docker(func: dict, event: dict) -> dict:lzf.extractall(layer_dir)layers_dirs.append(layer_dir)- if "." not in handler:- return {"body": {"errorMessage": f"Invalid handler format: {handler}", "errorType": "Runtime.InvalidEntrypoint"}, "error": True}- module_name, func_name = handler.rsplit(".", 1)+ if not is_provided:+ if "." not in handler:+ return {"body": {"errorMessage": f"Invalid handler format: {handler}", "errorType": "Runtime.InvalidEntrypoint"}, "error": True}+ module_name, func_name = handler.rsplit(".", 1)# Build volume mountsvolumes: dict = {}@@ -1056,12 +1063,16 @@ def _execute_function_docker(func: dict, event: dict) -> dict:"AWS_LAMBDA_FUNCTION_MEMORY_SIZE": str(config["MemorySize"]),"AWS_LAMBDA_FUNCTION_VERSION": config.get("Version", "$LATEST"),"AWS_LAMBDA_LOG_STREAM_NAME": new_uuid(),- "_LAMBDA_HANDLER_MODULE": module_name,- "_LAMBDA_HANDLER_FUNC": func_name,"_LAMBDA_FUNCTION_ARN": config["FunctionArn"],"_LAMBDA_TIMEOUT": str(timeout),"_LAMBDA_LAYERS_DIRS": ":".join(container_layer_dirs),}+ if not is_provided:+ container_env["_LAMBDA_HANDLER_MODULE"] = module_name+ container_env["_LAMBDA_HANDLER_FUNC"] = func_name+ else:+ container_env["LAMBDA_TASK_ROOT"] = "/var/task"+ container_env["_HANDLER"] = handlerendpoint = _normalize_endpoint_url(os.environ.get("AWS_ENDPOINT_URL", ""))if not endpoint:endpoint = _normalize_endpoint_url(env_vars.get("AWS_ENDPOINT_URL", ""))@@ -1075,7 +1086,63 @@ def _execute_function_docker(func: dict, event: dict) -> dict:with open(event_file, "w") as ef:ef.write(json.dumps(event))- if is_node:+ if is_provided:+ # provided runtimes: use AWS Lambda RIE built into the provided image.+ # Make bootstrap executable, start container with RIE, POST event via HTTP.+ bootstrap_path = os.path.join(code_dir, "bootstrap")+ if os.path.exists(bootstrap_path):+ os.chmod(bootstrap_path, 0o755)+ # provided runtimes use the AWS Lambda RIE built into the base image.+ # RIE listens on port 8080; we POST the event and read the response.+ import urllib.request+ bootstrap_path = os.path.join(code_dir, "bootstrap")+ if os.path.exists(bootstrap_path):+ os.chmod(bootstrap_path, 0o755)+ run_kwargs: dict = {+ "image": image, "command": ["/var/task/bootstrap"],+ "environment": container_env, "volumes": volumes,+ "ports": {"8080/tcp": None}, "detach": True, "stdin_open": False,+ }+ if LAMBDA_DOCKER_NETWORK:+ run_kwargs["network"] = LAMBDA_DOCKER_NETWORK+ container = client.containers.run(**run_kwargs)+ try:+ import time as _time+ for _attempt in range(30):+ _time.sleep(0.5)+ container.reload()+ if container.status != "running":+ break+ try:+ ports = container.ports.get("8080/tcp") or []+ if not ports:+ continue+ host_port = ports[0]["HostPort"]+ rie_url = f"http://127.0.0.1:{host_port}/2015-03-31/functions/function/invocations"+ req = urllib.request.Request(rie_url, data=json.dumps(event).encode(),+ headers={"Content-Type": "application/json"})+ resp = urllib.request.urlopen(req, timeout=timeout)+ body = resp.read().decode("utf-8", errors="replace")+ try:+ parsed = json.loads(body)+ except json.JSONDecodeError:+ parsed = body+ logs = container.logs(stdout=True, stderr=True).decode("utf-8", errors="replace").strip()+ return {"body": parsed, "log": logs}+ except (urllib.error.URLError, ConnectionRefusedError, OSError):+ continue+ stdout = container.logs(stdout=True, stderr=True).decode("utf-8", errors="replace").strip()+ return {"body": {"errorMessage": f"provided runtime failed: {stdout[:500]}", "errorType": "Runtime.ExitError"}, "error": True, "log": stdout}+ finally:+ try:+ container.stop(timeout=2)+ except Exception:+ pass+ try:+ container.remove(force=True)+ except Exception:+ pass+ elif is_node:wrapper_path = os.path.join(code_dir, "_wrapper.js")with open(wrapper_path, "w") as wf:wf.write(_NODE_WRAPPER_SCRIPT)diff --git a/pyproject.toml b/pyproject.tomlindex d755d288..ac66db74 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "ministack"-version = "1.1.35"+version = "1.1.36"description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"readme = "README.md"license = { file = "LICENSE" }diff --git a/tests/test_services.py b/tests/test_services.pyindex 0077743c..1bb8a026 100644--- a/tests/test_services.py+++ b/tests/test_services.py@@ -18639,3 +18639,474 @@ def test_appsync_graphql_empty_query():assert False, "Should have failed"except urllib.error.HTTPError as e:assert e.code == 400+++# ---------------------------------------------------------------------------+# EC2 v1.1.36 — new VPC/Terraform actions+# ---------------------------------------------------------------------------++def test_ec2_create_vpc_default_resources(ec2):+ """CreateVpc must create per-VPC default ACL, SG, and main route table."""+ vpc = ec2.create_vpc(CidrBlock="10.99.0.0/16")+ vpc_id = vpc["Vpc"]["VpcId"]+ try:+ # DescribeNetworkAcls with vpc-id + default=true+ acls = ec2.describe_network_acls(Filters=[+ {"Name": "vpc-id", "Values": [vpc_id]},+ {"Name": "default", "Values": ["true"]},+ ])+ assert len(acls["NetworkAcls"]) == 1+ acl = acls["NetworkAcls"][0]+ assert acl["IsDefault"] is True+ assert acl["VpcId"] == vpc_id++ # DescribeSecurityGroups with vpc-id + group-name=default+ sgs = ec2.describe_security_groups(Filters=[+ {"Name": "vpc-id", "Values": [vpc_id]},+ {"Name": "group-name", "Values": ["default"]},+ ])+ assert len(sgs["SecurityGroups"]) == 1+ assert sgs["SecurityGroups"][0]["VpcId"] == vpc_id++ # DescribeRouteTables with vpc-id + association.main=true+ rtbs = ec2.describe_route_tables(Filters=[+ {"Name": "vpc-id", "Values": [vpc_id]},+ {"Name": "association.main", "Values": ["true"]},+ ])+ assert len(rtbs["RouteTables"]) == 1+ assert rtbs["RouteTables"][0]["VpcId"] == vpc_id+ finally:+ ec2.delete_vpc(VpcId=vpc_id)+++def test_ec2_route_table_association_filter(ec2):+ """AssociateRouteTable + DescribeRouteTables filter by association ID."""+ vpc = ec2.create_vpc(CidrBlock="10.98.0.0/16")+ vpc_id = vpc["Vpc"]["VpcId"]+ try:+ subnet = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.98.1.0/24")+ subnet_id = subnet["Subnet"]["SubnetId"]+ rtb = ec2.create_route_table(VpcId=vpc_id)+ rtb_id = rtb["RouteTable"]["RouteTableId"]+ assoc = ec2.associate_route_table(RouteTableId=rtb_id, SubnetId=subnet_id)+ assoc_id = assoc["AssociationId"]++ # Filter by association ID+ result = ec2.describe_route_tables(Filters=[+ {"Name": "association.route-table-association-id", "Values": [assoc_id]},+ ])+ assert len(result["RouteTables"]) == 1+ assert result["RouteTables"][0]["RouteTableId"] == rtb_id++ # Filter by subnet ID+ result2 = ec2.describe_route_tables(Filters=[+ {"Name": "association.subnet-id", "Values": [subnet_id]},+ ])+ assert len(result2["RouteTables"]) == 1++ ec2.disassociate_route_table(AssociationId=assoc_id)+ ec2.delete_route_table(RouteTableId=rtb_id)+ ec2.delete_subnet(SubnetId=subnet_id)+ finally:+ ec2.delete_vpc(VpcId=vpc_id)+++def test_ec2_replace_route_table_association(ec2):+ """ReplaceRouteTableAssociation moves subnet to a different route table."""+ vpc = ec2.create_vpc(CidrBlock="10.97.0.0/16")+ vpc_id = vpc["Vpc"]["VpcId"]+ try:+ subnet = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.97.1.0/24")+ subnet_id = subnet["Subnet"]["SubnetId"]+ rtb1 = ec2.create_route_table(VpcId=vpc_id)+ rtb1_id = rtb1["RouteTable"]["RouteTableId"]+ rtb2 = ec2.create_route_table(VpcId=vpc_id)+ rtb2_id = rtb2["RouteTable"]["RouteTableId"]++ assoc = ec2.associate_route_table(RouteTableId=rtb1_id, SubnetId=subnet_id)+ old_assoc_id = assoc["AssociationId"]++ # Replace association to rtb2+ new = ec2.replace_route_table_association(AssociationId=old_assoc_id, RouteTableId=rtb2_id)+ new_assoc_id = new["NewAssociationId"]+ assert new_assoc_id != old_assoc_id++ # Verify subnet is now on rtb2+ result = ec2.describe_route_tables(Filters=[+ {"Name": "association.subnet-id", "Values": [subnet_id]},+ ])+ assert result["RouteTables"][0]["RouteTableId"] == rtb2_id++ ec2.disassociate_route_table(AssociationId=new_assoc_id)+ ec2.delete_route_table(RouteTableId=rtb1_id)+ ec2.delete_route_table(RouteTableId=rtb2_id)+ ec2.delete_subnet(SubnetId=subnet_id)+ finally:+ ec2.delete_vpc(VpcId=vpc_id)+++def test_ec2_modify_vpc_endpoint(ec2):+ """ModifyVpcEndpoint adds/removes route tables."""+ vpc = ec2.create_vpc(CidrBlock="10.96.0.0/16")+ vpc_id = vpc["Vpc"]["VpcId"]+ try:+ rtb = ec2.create_route_table(VpcId=vpc_id)+ rtb_id = rtb["RouteTable"]["RouteTableId"]+ ep = ec2.create_vpc_endpoint(+ VpcId=vpc_id, ServiceName="com.amazonaws.us-east-1.s3",+ VpcEndpointType="Gateway",+ )+ vpce_id = ep["VpcEndpoint"]["VpcEndpointId"]++ # Add route table+ ec2.modify_vpc_endpoint(VpcEndpointId=vpce_id, AddRouteTableIds=[rtb_id])+ desc = ec2.describe_vpc_endpoints(VpcEndpointIds=[vpce_id])+ assert rtb_id in desc["VpcEndpoints"][0]["RouteTableIds"]++ # Remove route table+ ec2.modify_vpc_endpoint(VpcEndpointId=vpce_id, RemoveRouteTableIds=[rtb_id])+ desc = ec2.describe_vpc_endpoints(VpcEndpointIds=[vpce_id])+ assert rtb_id not in desc["VpcEndpoints"][0]["RouteTableIds"]++ ec2.delete_vpc_endpoints(VpcEndpointIds=[vpce_id])+ ec2.delete_route_table(RouteTableId=rtb_id)+ finally:+ ec2.delete_vpc(VpcId=vpc_id)+++def test_ec2_describe_prefix_lists(ec2):+ """DescribePrefixLists returns built-in AWS service prefix lists."""+ result = ec2.describe_prefix_lists()+ pl_names = [pl["PrefixListName"] for pl in result["PrefixLists"]]+ assert any("s3" in n for n in pl_names)+ assert any("dynamodb" in n for n in pl_names)+++def test_ec2_managed_prefix_list_crud(ec2):+ """Full lifecycle: create, describe, get entries, modify, delete."""+ pl = ec2.create_managed_prefix_list(+ PrefixListName="test-pl", MaxEntries=5, AddressFamily="IPv4",+ Entries=[{"Cidr": "10.0.0.0/8", "Description": "RFC1918-10"}],+ )+ pl_id = pl["PrefixList"]["PrefixListId"]+ assert pl["PrefixList"]["PrefixListName"] == "test-pl"++ # Describe+ desc = ec2.describe_managed_prefix_lists(PrefixListIds=[pl_id])+ assert len(desc["PrefixLists"]) == 1+ assert desc["PrefixLists"][0]["PrefixListName"] == "test-pl"++ # Get entries+ entries = ec2.get_managed_prefix_list_entries(PrefixListId=pl_id)+ assert len(entries["Entries"]) == 1+ assert entries["Entries"][0]["Cidr"] == "10.0.0.0/8"++ # Modify — add entry+ ec2.modify_managed_prefix_list(+ PrefixListId=pl_id, CurrentVersion=1,+ AddEntries=[{"Cidr": "172.16.0.0/12", "Description": "RFC1918-172"}],+ )+ entries = ec2.get_managed_prefix_list_entries(PrefixListId=pl_id)+ cidrs = [e["Cidr"] for e in entries["Entries"]]+ assert "10.0.0.0/8" in cidrs+ assert "172.16.0.0/12" in cidrs++ # Modify — remove entry+ ec2.modify_managed_prefix_list(+ PrefixListId=pl_id, CurrentVersion=2,+ RemoveEntries=[{"Cidr": "10.0.0.0/8"}],+ )+ entries = ec2.get_managed_prefix_list_entries(PrefixListId=pl_id)+ cidrs = [e["Cidr"] for e in entries["Entries"]]+ assert "10.0.0.0/8" not in cidrs+ assert "172.16.0.0/12" in cidrs++ # Delete+ ec2.delete_managed_prefix_list(PrefixListId=pl_id)+ desc = ec2.describe_managed_prefix_lists(PrefixListIds=[pl_id])+ assert len(desc["PrefixLists"]) == 0+++def test_ec2_vpn_gateway_crud(ec2):+ """Full lifecycle: create, attach, describe, detach, delete."""+ vpc = ec2.create_vpc(CidrBlock="10.95.0.0/16")+ vpc_id = vpc["Vpc"]["VpcId"]+ try:+ vgw = ec2.create_vpn_gateway(Type="ipsec.1")+ vgw_id = vgw["VpnGateway"]["VpnGatewayId"]+ assert vgw["VpnGateway"]["State"] == "available"++ # Attach+ ec2.attach_vpn_gateway(VpnGatewayId=vgw_id, VpcId=vpc_id)+ desc = ec2.describe_vpn_gateways(VpnGatewayIds=[vgw_id])+ attachments = desc["VpnGateways"][0]["VpcAttachments"]+ assert len(attachments) == 1+ assert attachments[0]["VpcId"] == vpc_id+ assert attachments[0]["State"] == "attached"++ # Filter by attachment.vpc-id+ filtered = ec2.describe_vpn_gateways(Filters=[+ {"Name": "attachment.vpc-id", "Values": [vpc_id]},+ ])+ assert len(filtered["VpnGateways"]) == 1++ # Detach+ ec2.detach_vpn_gateway(VpnGatewayId=vgw_id, VpcId=vpc_id)+ desc = ec2.describe_vpn_gateways(VpnGatewayIds=[vgw_id])+ assert desc["VpnGateways"][0]["VpcAttachments"] == []++ # Delete+ ec2.delete_vpn_gateway(VpnGatewayId=vgw_id)+ desc = ec2.describe_vpn_gateways(VpnGatewayIds=[vgw_id])+ assert len(desc["VpnGateways"]) == 0+ finally:+ ec2.delete_vpc(VpcId=vpc_id)+++def test_ec2_vgw_route_propagation(ec2):+ """EnableVgwRoutePropagation / DisableVgwRoutePropagation."""+ vpc = ec2.create_vpc(CidrBlock="10.94.0.0/16")+ vpc_id = vpc["Vpc"]["VpcId"]+ try:+ rtb = ec2.create_route_table(VpcId=vpc_id)+ rtb_id = rtb["RouteTable"]["RouteTableId"]+ vgw = ec2.create_vpn_gateway(Type="ipsec.1")+ vgw_id = vgw["VpnGateway"]["VpnGatewayId"]++ ec2.enable_vgw_route_propagation(RouteTableId=rtb_id, GatewayId=vgw_id)+ # No error = success (propagation stored server-side)++ ec2.disable_vgw_route_propagation(RouteTableId=rtb_id, GatewayId=vgw_id)+ # No error = success++ ec2.delete_vpn_gateway(VpnGatewayId=vgw_id)+ ec2.delete_route_table(RouteTableId=rtb_id)+ finally:+ ec2.delete_vpc(VpcId=vpc_id)+++def test_ec2_customer_gateway_crud(ec2):+ """Full lifecycle: create, describe, delete."""+ cgw = ec2.create_customer_gateway(BgpAsn=65000, IpAddress="203.0.113.1", Type="ipsec.1")+ cgw_id = cgw["CustomerGateway"]["CustomerGatewayId"]+ assert cgw["CustomerGateway"]["State"] == "available"+ assert cgw["CustomerGateway"]["IpAddress"] == "203.0.113.1"++ # Describe+ desc = ec2.describe_customer_gateways(CustomerGatewayIds=[cgw_id])+ assert len(desc["CustomerGateways"]) == 1+ assert desc["CustomerGateways"][0]["BgpAsn"] == "65000"++ # Delete+ ec2.delete_customer_gateway(CustomerGatewayId=cgw_id)+ desc = ec2.describe_customer_gateways(CustomerGatewayIds=[cgw_id])+ assert len(desc["CustomerGateways"]) == 0+++def test_ec2_create_route_nat_gateway(ec2):+ """CreateRoute with NatGatewayId stores it separately from GatewayId."""+ vpc = ec2.create_vpc(CidrBlock="10.93.0.0/16")+ vpc_id = vpc["Vpc"]["VpcId"]+ try:+ subnet = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.93.1.0/24")+ subnet_id = subnet["Subnet"]["SubnetId"]+ eip = ec2.allocate_address(Domain="vpc")+ nat = ec2.create_nat_gateway(SubnetId=subnet_id, AllocationId=eip["AllocationId"])+ nat_id = nat["NatGateway"]["NatGatewayId"]+ rtb = ec2.create_route_table(VpcId=vpc_id)+ rtb_id = rtb["RouteTable"]["RouteTableId"]++ ec2.create_route(RouteTableId=rtb_id, DestinationCidrBlock="0.0.0.0/0", NatGatewayId=nat_id)++ desc = ec2.describe_route_tables(RouteTableIds=[rtb_id])+ routes = desc["RouteTables"][0]["Routes"]+ nat_route = [r for r in routes if r.get("DestinationCidrBlock") == "0.0.0.0/0"][0]+ assert nat_route.get("NatGatewayId") == nat_id+ assert nat_route.get("GatewayId", "") == ""++ ec2.delete_route(RouteTableId=rtb_id, DestinationCidrBlock="0.0.0.0/0")+ ec2.delete_route_table(RouteTableId=rtb_id)+ ec2.delete_nat_gateway(NatGatewayId=nat_id)+ ec2.release_address(AllocationId=eip["AllocationId"])+ ec2.delete_subnet(SubnetId=subnet_id)+ finally:+ ec2.delete_vpc(VpcId=vpc_id)+++def test_ec2_full_terraform_vpc_flow(ec2):+ """End-to-end Terraform VPC module flow: VPC → subnets → IGW → NAT → routes → associations."""+ # 1. Create VPC+ vpc = ec2.create_vpc(CidrBlock="10.50.0.0/16")+ vpc_id = vpc["Vpc"]["VpcId"]+ try:+ # 2. Verify default resources+ acls = ec2.describe_network_acls(Filters=[+ {"Name": "vpc-id", "Values": [vpc_id]},+ {"Name": "default", "Values": ["true"]},+ ])+ assert len(acls["NetworkAcls"]) == 1++ sgs = ec2.describe_security_groups(Filters=[+ {"Name": "vpc-id", "Values": [vpc_id]},+ {"Name": "group-name", "Values": ["default"]},+ ])+ assert len(sgs["SecurityGroups"]) == 1++ main_rtbs = ec2.describe_route_tables(Filters=[+ {"Name": "vpc-id", "Values": [vpc_id]},+ {"Name": "association.main", "Values": ["true"]},+ ])+ assert len(main_rtbs["RouteTables"]) == 1++ # 3. Create 6 subnets+ subnets = []+ for cidr, az in [+ ("10.50.0.0/20", "us-east-1a"), ("10.50.16.0/20", "us-east-1b"), ("10.50.32.0/20", "us-east-1c"),+ ("10.50.64.0/20", "us-east-1a"), ("10.50.80.0/20", "us-east-1b"), ("10.50.96.0/20", "us-east-1c"),+ ]:+ s = ec2.create_subnet(VpcId=vpc_id, CidrBlock=cidr, AvailabilityZone=az)+ subnets.append(s["Subnet"]["SubnetId"])++ # 4. IGW+ igw = ec2.create_internet_gateway()+ igw_id = igw["InternetGateway"]["InternetGatewayId"]+ ec2.attach_internet_gateway(InternetGatewayId=igw_id, VpcId=vpc_id)++ # 5. EIP + NAT+ eip = ec2.allocate_address(Domain="vpc")+ nat = ec2.create_nat_gateway(SubnetId=subnets[3], AllocationId=eip["AllocationId"])+ nat_id = nat["NatGateway"]["NatGatewayId"]++ # 6. Public + private route tables+ pub_rtb = ec2.create_route_table(VpcId=vpc_id)["RouteTable"]["RouteTableId"]+ priv_rtb = ec2.create_route_table(VpcId=vpc_id)["RouteTable"]["RouteTableId"]++ # 7. Associate subnets (3 public, 3 private)+ assoc_ids = []+ for i in range(3):+ a = ec2.associate_route_table(RouteTableId=pub_rtb, SubnetId=subnets[i + 3])+ assoc_ids.append(a["AssociationId"])+ # Verify filter works+ found = ec2.describe_route_tables(Filters=[+ {"Name": "association.route-table-association-id", "Values": [a["AssociationId"]]},+ ])+ assert len(found["RouteTables"]) == 1+ for i in range(3):+ a = ec2.associate_route_table(RouteTableId=priv_rtb, SubnetId=subnets[i])+ assoc_ids.append(a["AssociationId"])++ # 8. Routes+ ec2.create_route(RouteTableId=pub_rtb, DestinationCidrBlock="0.0.0.0/0", GatewayId=igw_id)+ ec2.create_route(RouteTableId=priv_rtb, DestinationCidrBlock="0.0.0.0/0", NatGatewayId=nat_id)++ # Verify NAT route+ desc = ec2.describe_route_tables(RouteTableIds=[priv_rtb])+ nat_route = [r for r in desc["RouteTables"][0]["Routes"] if r.get("DestinationCidrBlock") == "0.0.0.0/0"][0]+ assert nat_route.get("NatGatewayId") == nat_id++ # 9. Cleanup+ ec2.delete_route(RouteTableId=pub_rtb, DestinationCidrBlock="0.0.0.0/0")+ ec2.delete_route(RouteTableId=priv_rtb, DestinationCidrBlock="0.0.0.0/0")+ for aid in assoc_ids:+ ec2.disassociate_route_table(AssociationId=aid)+ ec2.delete_route_table(RouteTableId=pub_rtb)+ ec2.delete_route_table(RouteTableId=priv_rtb)+ ec2.delete_nat_gateway(NatGatewayId=nat_id)+ ec2.release_address(AllocationId=eip["AllocationId"])+ ec2.detach_internet_gateway(InternetGatewayId=igw_id, VpcId=vpc_id)+ ec2.delete_internet_gateway(InternetGatewayId=igw_id)+ for sid in subnets:+ ec2.delete_subnet(SubnetId=sid)+ finally:+ ec2.delete_vpc(VpcId=vpc_id)+++# ---------------------------------------------------------------------------+# KMS v1.1.36 — Terraform key rotation, policy, tags, lifecycle+# ---------------------------------------------------------------------------++def test_kms_enable_disable_key_rotation(kms_client):+ """EnableKeyRotation / DisableKeyRotation / GetKeyRotationStatus."""+ key = kms_client.create_key(KeyUsage="ENCRYPT_DECRYPT")+ key_id = key["KeyMetadata"]["KeyId"]+ status = kms_client.get_key_rotation_status(KeyId=key_id)+ assert status["KeyRotationEnabled"] is False+ kms_client.enable_key_rotation(KeyId=key_id)+ status = kms_client.get_key_rotation_status(KeyId=key_id)+ assert status["KeyRotationEnabled"] is True+ kms_client.disable_key_rotation(KeyId=key_id)+ status = kms_client.get_key_rotation_status(KeyId=key_id)+ assert status["KeyRotationEnabled"] is False+ kms_client.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)+++def test_kms_get_put_key_policy(kms_client):+ """GetKeyPolicy / PutKeyPolicy."""+ key = kms_client.create_key()+ key_id = key["KeyMetadata"]["KeyId"]+ policy = kms_client.get_key_policy(KeyId=key_id, PolicyName="default")+ assert "Statement" in policy["Policy"]+ custom = '{"Version":"2012-10-17","Statement":[]}'+ kms_client.put_key_policy(KeyId=key_id, PolicyName="default", Policy=custom)+ got = kms_client.get_key_policy(KeyId=key_id, PolicyName="default")+ assert got["Policy"] == custom+ kms_client.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)+++def test_kms_tag_untag_list_v2(kms_client):+ """TagResource / UntagResource / ListResourceTags."""+ key = kms_client.create_key()+ key_id = key["KeyMetadata"]["KeyId"]+ kms_client.tag_resource(KeyId=key_id, Tags=[+ {"TagKey": "env", "TagValue": "test"},+ {"TagKey": "team", "TagValue": "platform"},+ ])+ tags = kms_client.list_resource_tags(KeyId=key_id)+ tag_map = {t["TagKey"]: t["TagValue"] for t in tags["Tags"]}+ assert tag_map["env"] == "test"+ assert tag_map["team"] == "platform"+ kms_client.untag_resource(KeyId=key_id, TagKeys=["team"])+ tags = kms_client.list_resource_tags(KeyId=key_id)+ assert len(tags["Tags"]) == 1+ assert tags["Tags"][0]["TagKey"] == "env"+ kms_client.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)+++def test_kms_enable_disable_key(kms_client):+ """EnableKey / DisableKey."""+ key = kms_client.create_key()+ key_id = key["KeyMetadata"]["KeyId"]+ assert key["KeyMetadata"]["KeyState"] == "Enabled"+ kms_client.disable_key(KeyId=key_id)+ desc = kms_client.describe_key(KeyId=key_id)+ assert desc["KeyMetadata"]["KeyState"] == "Disabled"+ kms_client.enable_key(KeyId=key_id)+ desc = kms_client.describe_key(KeyId=key_id)+ assert desc["KeyMetadata"]["KeyState"] == "Enabled"+ kms_client.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)+++def test_kms_schedule_cancel_deletion(kms_client):+ """ScheduleKeyDeletion / CancelKeyDeletion."""+ key = kms_client.create_key()+ key_id = key["KeyMetadata"]["KeyId"]+ resp = kms_client.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)+ assert resp["KeyState"] == "PendingDeletion"+ kms_client.cancel_key_deletion(KeyId=key_id)+ desc = kms_client.describe_key(KeyId=key_id)+ assert desc["KeyMetadata"]["KeyState"] == "Disabled"+++def test_kms_terraform_full_flow(kms_client):+ """Full Terraform aws_kms_key lifecycle."""+ key = kms_client.create_key(KeySpec="SYMMETRIC_DEFAULT", KeyUsage="ENCRYPT_DECRYPT", Description="RDS key")+ key_id = key["KeyMetadata"]["KeyId"]+ kms_client.enable_key_rotation(KeyId=key_id)+ assert kms_client.get_key_rotation_status(KeyId=key_id)["KeyRotationEnabled"] is True+ pol = kms_client.get_key_policy(KeyId=key_id, PolicyName="default")+ assert len(pol["Policy"]) > 0+ kms_client.tag_resource(KeyId=key_id, Tags=[{"TagKey": "Name", "TagValue": "rds-key"}])+ assert kms_client.list_resource_tags(KeyId=key_id)["Tags"][0]["TagValue"] == "rds-key"+ desc = kms_client.describe_key(KeyId=key_id)+ assert desc["KeyMetadata"]["Description"] == "RDS key"+ kms_client.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)