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/fixes stable v1.2.0 (#244)
Nahuel Nucerab9e86a864fe9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 38f8370c..d05733d2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,44 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [1.2.0] — 2026-04-11++### Added+- **AutoScaling service** — new full service with 22 API operations: CreateAutoScalingGroup, DescribeAutoScalingGroups, UpdateAutoScalingGroup, DeleteAutoScalingGroup, CreateLaunchConfiguration, DescribeLaunchConfigurations, DeleteLaunchConfiguration, PutScalingPolicy, DescribePolicies, DeletePolicy, PutLifecycleHook, DescribeLifecycleHooks, DeleteLifecycleHook, CompleteLifecycleAction, RecordLifecycleActionHeartbeat, PutScheduledUpdateGroupAction, DescribeScheduledActions, DeleteScheduledAction, CreateOrUpdateTags, DescribeTags, DeleteTags, DescribeAutoScalingInstances.+- **9 new CloudFormation provisioners** — `AWS::Lambda::LayerVersion`, `AWS::StepFunctions::StateMachine`, `AWS::Route53::HostedZone`, `AWS::ApiGatewayV2::Api`, `AWS::ApiGatewayV2::Stage`, `AWS::SES::EmailIdentity`, `AWS::WAFv2::WebACL`, `AWS::CloudFront::Distribution`, `AWS::RDS::DBCluster`. All 9 support create, delete, and Fn::GetAtt. Total provisioners: 66 (was 57).+- **5 AutoScaling CFN provisioners upgraded** — `AWS::AutoScaling::AutoScalingGroup`, `LaunchConfiguration`, `ScalingPolicy`, `LifecycleHook`, `ScheduledAction` now store real data (were stubs).+- **EC2 `DescribeInstanceStatus`** — new operation with `IncludeAllInstances` support. Returns instance state, system status, and instance status.+- **EC2 `DescribeVpcClassicLink` / `DescribeVpcClassicLinkDnsSupport`** — stubs returning empty sets. Unblocks all VPC-dependent Terraform resources (subnet, security group, instance, ALB, NLB, EFS).+- **Test parallelization** — CI now runs tests in parallel with pytest-xdist. Adjusted worker count for CFN stack reliability, added retries for flaky tests, increased CFN stack wait timeout. Contributed by @jgrumboe (#199).+- **SFN REST-JSON `aws-sdk` dispatcher + RDS Data API integration** — Step Functions `aws-sdk:rdsdata:executeStatement` and other RDS Data actions now dispatch via a new REST-JSON protocol handler. Static action→path map avoids botocore dependency. RDS Data API returns stub success when no database endpoint is available, allowing SFN workflows to proceed in mock environments. Contributed by @jayjanssen (#237).+- **Lambda warm worker layer extraction** — warm worker pool now extracts Lambda layers and makes their code available to handlers. Python layers are added to `sys.path` via `_LAMBDA_LAYERS_DIRS` env var. Node.js layers are resolved via `NODE_PATH` pointing to each layer's `nodejs/node_modules` directory. Includes zip-slip protection on extraction. Contributed by @bognari (#236).+- **Lambda Node.js ESM (.mjs) handler support** — Node.js handlers using ES modules (`.mjs` files or `package.json` with `"type": "module"`) now load correctly via dynamic `import()` fallback when `require()` fails with `ERR_REQUIRE_ESM`. Supports `export const handler`, `export default`, and cross-module ESM imports. Works in both warm worker pool and cold invocation paths. Contributed by @bognari (#238).++### Fixed+- **Terraform AWS provider v5.x compatibility (Lambda, DynamoDB, SFN, ESM)** — Lambda no longer injects default runtime/handler for Image-based functions and preserves `ImageConfigResponse` in create/update responses. ESM omits `StartingPosition` for SQS event sources (only valid for Kinesis/DynamoDB Streams). DynamoDB returns `ProvisionedThroughput` with zero values for PAY_PER_REQUEST tables and GSIs. Step Functions implements `ValidateStateMachineDefinition` stub required by provider v5.42.0+. Contributed by @DaviReisVieira (#242).+- **Kinesis `IncreaseStreamRetentionPeriod` rejects same value** — setting retention to 24h (the default) failed with "must be greater than current value". Now accepts same-value as no-op. Blocked `aws_kinesis_stream` in Terraform and Pulumi.+- **ACM `DescribeCertificate` timestamps as ISO strings** — Terraform Go SDK expects epoch floats. `CreatedAt`, `IssuedAt`, `NotBefore`, `NotAfter` now return epoch numbers. Blocked `aws_acm_certificate` in Terraform.+- **Lambda ESM `Enabled` field ignored** — creating an ESM with `Enabled: false` always returned `State: Enabled`. Now respects the request parameter.+- **Lambda ESM `Enabled` field in response** — real AWS does not include `Enabled` in ESM responses, only `State`. Extra field caused Terraform drift.+- **ECS TaskDefinition extra container fields** — `container_definitions` included `environment=[], mountPoints=[], volumesFrom=[], memoryReservation=0` when not specified. Caused Terraform replacement on every apply.+- **DynamoDB `CreateTable` ignores `Tags`** — tags passed in `CreateTable` were not stored. `ListTagsOfResource` returned empty. Terraform re-applied tags every plan.+- **SNS `CreateTopic` ignores `Tags`** — same as DynamoDB. Tags now stored on create.+- **SNS `DisplayName` defaults to topic name** — real AWS defaults to empty string. Caused Terraform drift.+- **SSM `PutParameter` ignores `Tags`** — tags now stored on create.+- **Lambda empty `Environment` block returned** — when no env vars set, response included `Environment: {Variables: {}}`. Terraform tried to remove it every plan. Now omitted when not set.+- **Lambda `DeadLetterConfig` empty object returned** — when not configured, response included `DeadLetterConfig: {}`. Now omitted when not set.+- **Lambda Function URL missing `InvokeMode`** — response lacked `InvokeMode` field. Terraform wanted to set "BUFFERED" every plan. Now defaults to "BUFFERED".+- **Lambda Function URL empty `Cors` block** — `cors: {}` returned when not configured. Now omitted.+- **API Gateway v2 empty `corsConfiguration`** — returned `{}` when not set. Caused Terraform/Pulumi drift.+- **API Gateway v2 missing `apiKeySelectionExpression`** — now defaults to `$request.header.x-api-key`.+- **Cognito UserPool extra empty blocks** — `DeviceConfiguration`, `UserPoolAddOns`, `UsernameConfiguration`, `VerificationMessageTemplate` returned when not set. Now only included when explicitly provided. Added missing `DeletionProtection` field.+- **SNS `GetTopicAttributes` 404 with empty account ARN** — SDKs that skip `GetCallerIdentity` (Pulumi with `skipRequestingAccountId`) construct ARNs with empty account ID (`arn:aws:sns:us-east-1::name`). All SNS operations now normalize these to the default account.+- **SES `DeleteIdentity` malformed XML response** — response lacked `<DeleteIdentityResult/>` element. Go SDK deserialization failed. Also fixed `SetIdentityNotificationTopic` and `SetIdentityFeedbackForwardingEnabled`.+- **Go SDK v2 "failed to close HTTP response body" warning** — all responses lacked `Content-Length` header, causing Uvicorn to use `Transfer-Encoding: chunked`. The Go AWS SDK v2 warns on every chunked response close. Now sets `Content-Length` on all responses. Affects all services. Reported by @mspiller.+- **S3 `ListObjectVersions` returns only one version** — when versioning is enabled, multiple PUTs to the same key only stored the latest object. `ListObjectVersions` returned a single version with hardcoded `VersionId: "1"`. Now maintains full version history with unique VersionIds per PUT. Reported by @aldex32.++---+## [1.1.62] — 2026-04-10### Addeddiff --git a/README.md b/README.mdindex b2d29318..e26a7f9a 100644--- a/README.md+++ b/README.md@@ -4,7 +4,7 @@<h1 align="center">MiniStack</h1><p align="center"><strong>Free, open-source local AWS emulator. Free forever.</strong></p>-<p align="center">35+ AWS services on a single port · Terraform compatible · Real databases · MIT licensed</p>+<p align="center">40 AWS services on a single port · Terraform compatible · Real databases · MIT licensed</p><p align="center"><a href="https://github.com/Nahuel990/ministack/releases"><img src="https://img.shields.io/github/v/release/Nahuel990/ministack" alt="GitHub release"></a>@@ -26,7 +26,7 @@LocalStack recently moved its core services behind a paid plan. If you relied on LocalStack Community for local development and CI/CD pipelines, MiniStack is your free alternative.-- **38 AWS services** emulated on a single port (4566)+- **40 AWS services** emulated on a single port (4566)- **Drop-in compatible** — works with `boto3`, AWS CLI, Terraform, CDK, Pulumi, any SDK- **Real infrastructure** — RDS spins up actual Postgres/MySQL containers, ElastiCache spins up real Redis, Athena runs real SQL via DuckDB, ECS runs real Docker containers- **Tiny footprint** — ~200MB image, ~30MB RAM at idle vs LocalStack's ~1GB image and ~500MB RAM@@ -409,6 +409,20 @@ subnet = ec2.create_subnet(| `AWS::ECS::Service` | Service ARN | ServiceArn, Name || `AWS::ElasticLoadBalancingV2::LoadBalancer` | LB ARN | Arn, DNSName, LoadBalancerFullName, CanonicalHostedZoneID, SecurityGroups || `AWS::ElasticLoadBalancingV2::Listener` | Listener ARN | ListenerArn, Arn |+| `AWS::Lambda::LayerVersion` | Layer version ARN | LayerVersionArn, Arn |+| `AWS::StepFunctions::StateMachine` | State machine ARN | Arn, Name |+| `AWS::Route53::HostedZone` | Zone ID | Id, NameServers |+| `AWS::ApiGatewayV2::Api` | API ID | ApiId, ApiEndpoint |+| `AWS::ApiGatewayV2::Stage` | Stage ID | StageName |+| `AWS::SES::EmailIdentity` | Identity | EmailIdentity |+| `AWS::WAFv2::WebACL` | WebACL ID | Arn, Id |+| `AWS::CloudFront::Distribution` | Distribution ID | Arn, DomainName, Id |+| `AWS::RDS::DBCluster` | Cluster ID | Arn, Endpoint.Address, Endpoint.Port, ReadEndpoint.Address |+| `AWS::AutoScaling::AutoScalingGroup` | ASG name | Arn |+| `AWS::AutoScaling::LaunchConfiguration` | LC name | Arn |+| `AWS::AutoScaling::ScalingPolicy` | Policy ARN | Arn, PolicyName |+| `AWS::AutoScaling::LifecycleHook` | Hook name | LifecycleHookName |+| `AWS::AutoScaling::ScheduledAction` | Action ARN | Arn, ScheduledActionName || `AWS::CloudFormation::WaitCondition` | Condition ID | — || `AWS::CloudFormation::WaitConditionHandle` | Handle URL | — |@@ -425,7 +439,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, 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, CreateLaunchTemplate, CreateLaunchTemplateVersion, DescribeLaunchTemplates, DescribeLaunchTemplateVersions, ModifyLaunchTemplate, DeleteLaunchTemplate | 133 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; launch templates with versioning ($Latest/$Default) |+| **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, DescribeInstanceStatus, DescribeVpcClassicLink, DescribeVpcClassicLinkDnsSupport, CreateLaunchTemplate, CreateLaunchTemplateVersion, DescribeLaunchTemplates, DescribeLaunchTemplateVersions, ModifyLaunchTemplate, DeleteLaunchTemplate | 136 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; launch templates with versioning ($Latest/$Default) || **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 |@@ -435,6 +449,7 @@ Unsupported resource types fail with `CREATE_FAILED` (or `ROLLBACK_COMPLETE` if| **Cloud Map** | CreateHttpNamespace, CreatePrivateDnsNamespace, CreatePublicDnsNamespace, GetNamespace, ListNamespaces, DeleteNamespace, UpdateHttpNamespace, UpdatePrivateDnsNamespace, UpdatePublicDnsNamespace, CreateService, GetService, ListServices, DeleteService, UpdateService, RegisterInstance, DeregisterInstance, DiscoverInstances, DiscoverInstancesRevision, ListInstances, GetInstancesHealthStatus, UpdateInstanceCustomHealthStatus, GetServiceAttributes, UpdateServiceAttributes, DeleteServiceAttributes, GetOperation, ListOperations, TagResource, UntagResource, ListTagsForResource | DNS namespaces create Route53 hosted zones; operation tracking; Terraform `aws_service_discovery_*` compatible || **RDS Data API** | ExecuteStatement, BatchExecuteStatement, BeginTransaction, CommitTransaction, RollbackTransaction | Routes SQL to real Docker-backed RDS database containers; supports MySQL (pymysql) and PostgreSQL (psycopg2); REST paths (`/Execute`, `/BeginTransaction`, etc.) || **S3 Files** | CreateFileSystem, GetFileSystem, ListFileSystems, DeleteFileSystem, CreateMountTarget, GetMountTarget, ListMountTargets, UpdateMountTarget, DeleteMountTarget, CreateAccessPoint, GetAccessPoint, ListAccessPoints, DeleteAccessPoint, GetFileSystemPolicy, PutFileSystemPolicy, DeleteFileSystemPolicy, GetSynchronizationConfiguration, PutSynchronizationConfiguration, TagResource, UntagResource, ListTagsForResource | 21 operations; control plane for the new S3 Files service (launched April 2026); file systems, mount targets, access points, policies |+| **AutoScaling** | CreateAutoScalingGroup, DescribeAutoScalingGroups, UpdateAutoScalingGroup, DeleteAutoScalingGroup, DescribeAutoScalingInstances, CreateLaunchConfiguration, DescribeLaunchConfigurations, DeleteLaunchConfiguration, PutScalingPolicy, DescribePolicies, DeletePolicy, PutLifecycleHook, DescribeLifecycleHooks, DeleteLifecycleHook, CompleteLifecycleAction, RecordLifecycleActionHeartbeat, PutScheduledUpdateGroupAction, DescribeScheduledActions, DeleteScheduledAction, CreateOrUpdateTags, DescribeTags, DeleteTags | 22 actions; in-memory state — no real instance scaling; full ASG lifecycle (launch configs, scaling policies, lifecycle hooks, scheduled actions, tags); CDK/Terraform compatible |---@@ -619,7 +634,7 @@ Install DuckDB for full Athena SQL compatibility: `pip install ministack[full]`.When `PERSIST_STATE=1`, MiniStack saves service state to `STATE_DIR` on shutdown and reloads it on startup. Writes are atomic (write-to-tmp then rename) to prevent corruption on crash.-Services currently supporting persistence: **All 36+ services** — API Gateway v1/v2, ALB, ACM, AppSync, Athena, Cloud Map, CloudFront, CloudWatch, CloudWatch Logs, Cognito, DynamoDB, EC2, ECR, ECS, EFS, ElastiCache, EMR, EventBridge, Firehose, Glue, IAM/STS, Kinesis, KMS, Lambda, RDS, Route 53, S3, Secrets Manager, SES, SES v2, SNS, SQS, SSM, Step Functions, WAF v2+Services currently supporting persistence: **All 40 services** — API Gateway v1/v2, ALB, ACM, AppSync, Athena, Cloud Map, CloudFront, CloudWatch, CloudWatch Logs, Cognito, DynamoDB, EC2, ECR, ECS, EFS, ElastiCache, EMR, EventBridge, Firehose, Glue, IAM/STS, Kinesis, KMS, Lambda, RDS, Route 53, S3, Secrets Manager, SES, SES v2, SNS, SQS, SSM, Step Functions, WAF v2```bashdocker run -p 4566:4566 \@@ -717,7 +732,7 @@ pip install boto3 pytest duckdb docker cbor2# Start MiniStackdocker compose up -d-# Run the full test suite (955 tests across all 38 services)+# Run the full test suite (1,146 tests across all 40 services)pytest tests/ -v```diff --git a/ministack/app.py b/ministack/app.pyindex d3b2846f..24d09f17 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -44,6 +44,7 @@ from ministack.services import (acm,alb,apigateway,+ autoscaling,apigateway_v1,appsync,athena,@@ -131,6 +132,7 @@ SERVICE_HANDLERS = {"servicediscovery": servicediscovery.handle_request,"s3files": s3files.handle_request,"rds-data": rds_data.handle_request,+ "autoscaling": autoscaling.handle_request,}SERVICE_NAME_ALIASES = {@@ -490,7 +492,7 @@ async def app(scope, receive, send):_non_s3_hosts = {"s3", "s3-control", "sqs", "sns", "dynamodb", "lambda", "iam", "sts","secretsmanager", "logs", "ssm", "events", "kinesis","monitoring", "ses", "states", "ecs", "rds", "rds-data", "elasticache",- "glue", "athena", "apigateway", "cloudformation"}+ "glue", "athena", "apigateway", "cloudformation", "autoscaling"}if bucket not in _non_s3_hosts:vhost_path = "/" + bucket + path if path != "/" else "/" + bucket + "/"try:@@ -560,6 +562,9 @@ async def _send_response(send, status, headers, body):except UnicodeEncodeError:return v.encode("utf-8")+ body_bytes = body if isinstance(body, bytes) else body.encode("utf-8")+ if "content-length" not in {k.lower() for k in headers}:+ headers["Content-Length"] = str(len(body_bytes))header_list = [(k.encode("latin-1"), _encode_header_value(str(v))) for k, v in headers.items()]await send({"type": "http.response.start",@@ -568,7 +573,7 @@ async def _send_response(send, status, headers, body):})await send({"type": "http.response.body",- "body": body if isinstance(body, bytes) else body.encode("utf-8"),+ "body": body_bytes,})diff --git a/ministack/core/router.py b/ministack/core/router.pyindex cdc91a0f..71e8c5f6 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -181,6 +181,10 @@ SERVICE_PATTERNS = {"host_patterns": [r"rds-data\."],"credential_scope": "rds-data",},+ "autoscaling": {+ "host_patterns": [r"autoscaling\."],+ "credential_scope": "autoscaling",+ },}@@ -236,6 +240,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"servicediscovery": "servicediscovery","s3files": "s3files","rds-data": "rds-data",+ "autoscaling": "autoscaling",}if svc_name in scope_map:return scope_map[svc_name]@@ -429,6 +434,18 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) -># name. These are routed via credential scope or host header instead."CopySnapshot": "ec2", "ModifySnapshotAttribute": "ec2","DescribeSnapshotAttribute": "ec2",+ # AutoScaling actions+ "CreateAutoScalingGroup": "autoscaling", "DescribeAutoScalingGroups": "autoscaling",+ "UpdateAutoScalingGroup": "autoscaling", "DeleteAutoScalingGroup": "autoscaling",+ "CreateLaunchConfiguration": "autoscaling", "DescribeLaunchConfigurations": "autoscaling",+ "DeleteLaunchConfiguration": "autoscaling",+ "PutScalingPolicy": "autoscaling", "DescribePolicies": "autoscaling",+ "DeletePolicy": "autoscaling",+ "PutLifecycleHook": "autoscaling", "DescribeLifecycleHooks": "autoscaling",+ "DeleteLifecycleHook": "autoscaling",+ "PutScheduledUpdateGroupAction": "autoscaling", "DescribeScheduledActions": "autoscaling",+ "DeleteScheduledAction": "autoscaling",+ "DescribeAutoScalingInstances": "autoscaling",}if action in action_service_map:return action_service_map[action]diff --git a/ministack/services/acm.py b/ministack/services/acm.pyindex 085e073f..a7448075 100644--- a/ministack/services/acm.py+++ b/ministack/services/acm.py@@ -41,6 +41,16 @@ def _future_iso(seconds):return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + seconds))+def _epoch(iso_or_epoch):+ """Convert ISO timestamp to epoch float if needed. ACM API returns epoch floats."""+ if isinstance(iso_or_epoch, (int, float)):+ return float(iso_or_epoch)+ try:+ return time.mktime(time.strptime(iso_or_epoch, "%Y-%m-%dT%H:%M:%SZ")) - time.timezone+ except (ValueError, TypeError):+ return time.time()++def _cert_arn():return f"arn:aws:acm:{REGION}:{get_account_id()}:certificate/{new_uuid()}"@@ -68,10 +78,10 @@ def _cert_shape(cert):"KeyAlgorithm": "RSA_2048","SignatureAlgorithm": "SHA256WITHRSA","InUseBy": cert.get("InUseBy", []),- "CreatedAt": cert["CreatedAt"],- "IssuedAt": cert.get("IssuedAt", cert["CreatedAt"]),- "NotBefore": cert.get("NotBefore", cert["CreatedAt"]),- "NotAfter": cert.get("NotAfter", _future_iso(365 * 24 * 3600)),+ "CreatedAt": _epoch(cert["CreatedAt"]),+ "IssuedAt": _epoch(cert.get("IssuedAt", cert["CreatedAt"])),+ "NotBefore": _epoch(cert.get("NotBefore", cert["CreatedAt"])),+ "NotAfter": _epoch(cert.get("NotAfter", _future_iso(365 * 24 * 3600))),"DomainValidationOptions": cert.get("DomainValidationOptions", []),"Options": cert.get("Options", {}),"Tags": cert.get("Tags", []),diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.pyindex 5ecb4083..cdf8091a 100644--- a/ministack/services/apigateway.py+++ b/ministack/services/apigateway.py@@ -435,12 +435,14 @@ def _create_api(data):"apiEndpoint": f"http://{api_id}.execute-api.{_HOST}:{_PORT}","createdDate": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),"routeSelectionExpression": data.get("routeSelectionExpression", "$request.method $request.path"),+ "apiKeySelectionExpression": data.get("apiKeySelectionExpression", "$request.header.x-api-key"),"tags": data.get("tags", {}),- "corsConfiguration": data.get("corsConfiguration", {}),"disableSchemaValidation": data.get("disableSchemaValidation", False),"disableExecuteApiEndpoint": data.get("disableExecuteApiEndpoint", False),"version": data.get("version", ""),}+ if data.get("corsConfiguration"):+ api["corsConfiguration"] = data["corsConfiguration"]_apis[api_id] = api_routes[api_id] = {}_integrations[api_id] = {}diff --git a/ministack/services/autoscaling.py b/ministack/services/autoscaling.pynew file mode 100644index 00000000..4bc6fab4--- /dev/null+++ b/ministack/services/autoscaling.py@@ -0,0 +1,503 @@+"""+AutoScaling Service Emulator.+Query API (Action=...) — groups, launch configs, policies, hooks, scheduled actions.+All in-memory, no actual instance scaling.++Supports:+ ASG: CreateAutoScalingGroup, DescribeAutoScalingGroups, UpdateAutoScalingGroup,+ DeleteAutoScalingGroup, DescribeAutoScalingInstances+ LC: CreateLaunchConfiguration, DescribeLaunchConfigurations, DeleteLaunchConfiguration+ Policies: PutScalingPolicy, DescribePolicies, DeletePolicy+ Hooks: PutLifecycleHook, DescribeLifecycleHooks, DeleteLifecycleHook,+ CompleteLifecycleAction, RecordLifecycleActionHeartbeat+ Schedule: PutScheduledUpdateGroupAction, DescribeScheduledActions, DeleteScheduledAction+ Tags: CreateOrUpdateTags, DescribeTags, DeleteTags+"""++import logging+import os+import time+from collections import defaultdict++from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid, now_iso++logger = logging.getLogger("autoscaling")+REGION = os.environ.get("MINISTACK_REGION", "us-east-1")++_asgs = AccountScopedDict()+_launch_configs = AccountScopedDict()+_policies = AccountScopedDict()+_hooks = AccountScopedDict()+_scheduled_actions = AccountScopedDict()+_tags = AccountScopedDict() # asg_name -> [{"Key":..., "Value":...}, ...]+++def _p(params, key):+ v = params.get(key, "")+ return v[0] if isinstance(v, list) else v+++def _parse_member_list(params, prefix):+ items = []+ i = 1+ while True:+ key = f"{prefix}.member.{i}"+ val = _p(params, key)+ if not val:+ break+ items.append(val)+ i += 1+ return items+++def _xml(status, root_tag, inner):+ body = (f'<?xml version="1.0" encoding="UTF-8"?>'+ f'<{root_tag} xmlns="http://autoscaling.amazonaws.com/doc/2011-01-01/">'+ f'{inner}'+ f'<ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>'+ f'</{root_tag}>').encode("utf-8")+ return status, {"Content-Type": "application/xml"}, body+++def _error(code, message, status=400):+ return _xml(status, "ErrorResponse",+ f'<Error><Type>Sender</Type><Code>{code}</Code><Message>{message}</Message></Error>')+++def _asg_arn(name):+ return f"arn:aws:autoscaling:{REGION}:{get_account_id()}:autoScalingGroup:{new_uuid()}:autoScalingGroupName/{name}"+++# ---------------------------------------------------------------------------+# AutoScalingGroup+# ---------------------------------------------------------------------------++def _create_asg(p):+ name = _p(p, "AutoScalingGroupName")+ if not name:+ return _error("ValidationError", "AutoScalingGroupName is required")+ if name in _asgs:+ return _error("AlreadyExistsFault", f"AutoScalingGroup {name} already exists")++ arn = _asg_arn(name)+ _asgs[name] = {+ "AutoScalingGroupName": name,+ "AutoScalingGroupARN": arn,+ "LaunchConfigurationName": _p(p, "LaunchConfigurationName"),+ "LaunchTemplate": {},+ "MinSize": int(_p(p, "MinSize") or 0),+ "MaxSize": int(_p(p, "MaxSize") or 0),+ "DesiredCapacity": int(_p(p, "DesiredCapacity") or _p(p, "MinSize") or 0),+ "DefaultCooldown": int(_p(p, "DefaultCooldown") or 300),+ "AvailabilityZones": _parse_member_list(p, "AvailabilityZones") or [f"{REGION}a"],+ "HealthCheckType": _p(p, "HealthCheckType") or "EC2",+ "HealthCheckGracePeriod": int(_p(p, "HealthCheckGracePeriod") or 300),+ "Instances": [],+ "CreatedTime": now_iso(),+ "VPCZoneIdentifier": _p(p, "VPCZoneIdentifier") or "",+ "TerminationPolicies": _parse_member_list(p, "TerminationPolicies") or ["Default"],+ "NewInstancesProtectedFromScaleIn": _p(p, "NewInstancesProtectedFromScaleIn") == "true",+ "ServiceLinkedRoleARN": _p(p, "ServiceLinkedRoleARN") or "",+ "Tags": [],+ "Status": "",+ }++ # Parse launch template+ lt_id = _p(p, "LaunchTemplate.LaunchTemplateId") or _p(p, "LaunchTemplate.LaunchTemplateName")+ lt_ver = _p(p, "LaunchTemplate.Version") or "$Default"+ if lt_id:+ _asgs[name]["LaunchTemplate"] = {+ "LaunchTemplateId": lt_id,+ "LaunchTemplateName": lt_id,+ "Version": lt_ver,+ }++ # Parse tags+ i = 1+ tags = []+ while _p(p, f"Tags.member.{i}.Key"):+ tags.append({+ "Key": _p(p, f"Tags.member.{i}.Key"),+ "Value": _p(p, f"Tags.member.{i}.Value"),+ "ResourceId": name,+ "ResourceType": "auto-scaling-group",+ "PropagateAtLaunch": _p(p, f"Tags.member.{i}.PropagateAtLaunch") == "true",+ })+ i += 1+ _asgs[name]["Tags"] = tags+ _tags[name] = tags++ logger.info("CreateAutoScalingGroup: %s", name)+ return _xml(200, "CreateAutoScalingGroupResponse", "<CreateAutoScalingGroupResult/>")+++def _describe_asgs(p):+ names = _parse_member_list(p, "AutoScalingGroupNames")+ members = ""+ for name, asg in _asgs.items():+ if names and name not in names:+ continue+ azs = "".join(f"<member>{az}</member>" for az in asg["AvailabilityZones"])+ tp = "".join(f"<member>{t}</member>" for t in asg["TerminationPolicies"])+ tags_xml = "".join(+ f"<member><Key>{t['Key']}</Key><Value>{t['Value']}</Value>"+ f"<ResourceId>{t['ResourceId']}</ResourceId><ResourceType>{t['ResourceType']}</ResourceType>"+ f"<PropagateAtLaunch>{'true' if t.get('PropagateAtLaunch') else 'false'}</PropagateAtLaunch></member>"+ for t in asg.get("Tags", [])+ )+ lt = asg.get("LaunchTemplate", {})+ lt_xml = ""+ if lt:+ lt_xml = (f"<LaunchTemplate>"+ f"<LaunchTemplateId>{lt.get('LaunchTemplateId', '')}</LaunchTemplateId>"+ f"<LaunchTemplateName>{lt.get('LaunchTemplateName', '')}</LaunchTemplateName>"+ f"<Version>{lt.get('Version', '')}</Version></LaunchTemplate>")+ members += (f"<member>"+ f"<AutoScalingGroupName>{name}</AutoScalingGroupName>"+ f"<AutoScalingGroupARN>{asg['AutoScalingGroupARN']}</AutoScalingGroupARN>"+ f"<MinSize>{asg['MinSize']}</MinSize>"+ f"<MaxSize>{asg['MaxSize']}</MaxSize>"+ f"<DesiredCapacity>{asg['DesiredCapacity']}</DesiredCapacity>"+ f"<DefaultCooldown>{asg['DefaultCooldown']}</DefaultCooldown>"+ f"<AvailabilityZones>{azs}</AvailabilityZones>"+ f"<HealthCheckType>{asg['HealthCheckType']}</HealthCheckType>"+ f"<HealthCheckGracePeriod>{asg['HealthCheckGracePeriod']}</HealthCheckGracePeriod>"+ f"<CreatedTime>{asg['CreatedTime']}</CreatedTime>"+ f"<VPCZoneIdentifier>{asg['VPCZoneIdentifier']}</VPCZoneIdentifier>"+ f"<TerminationPolicies>{tp}</TerminationPolicies>"+ f"<NewInstancesProtectedFromScaleIn>{'true' if asg['NewInstancesProtectedFromScaleIn'] else 'false'}</NewInstancesProtectedFromScaleIn>"+ f"<Tags>{tags_xml}</Tags>"+ f"<Instances/>"+ f"{lt_xml}"+ f"<LaunchConfigurationName>{asg.get('LaunchConfigurationName', '')}</LaunchConfigurationName>"+ f"</member>")+ return _xml(200, "DescribeAutoScalingGroupsResponse",+ f"<DescribeAutoScalingGroupsResult><AutoScalingGroups>{members}</AutoScalingGroups></DescribeAutoScalingGroupsResult>")+++def _update_asg(p):+ name = _p(p, "AutoScalingGroupName")+ asg = _asgs.get(name)+ if not asg:+ return _error("ValidationError", f"AutoScalingGroup {name} not found")+ for k, pk in [("MinSize", "MinSize"), ("MaxSize", "MaxSize"), ("DesiredCapacity", "DesiredCapacity"),+ ("DefaultCooldown", "DefaultCooldown"), ("HealthCheckGracePeriod", "HealthCheckGracePeriod")]:+ v = _p(p, pk)+ if v:+ asg[k] = int(v)+ if _p(p, "HealthCheckType"):+ asg["HealthCheckType"] = _p(p, "HealthCheckType")+ if _p(p, "VPCZoneIdentifier"):+ asg["VPCZoneIdentifier"] = _p(p, "VPCZoneIdentifier")+ return _xml(200, "UpdateAutoScalingGroupResponse", "<UpdateAutoScalingGroupResult/>")+++def _delete_asg(p):+ name = _p(p, "AutoScalingGroupName")+ _asgs.pop(name, None)+ _tags.pop(name, None)+ # Remove associated hooks+ keys_to_del = [k for k in _hooks if k.startswith(f"{name}/")]+ for k in keys_to_del:+ del _hooks[k]+ return _xml(200, "DeleteAutoScalingGroupResponse", "<DeleteAutoScalingGroupResult/>")+++def _describe_asg_instances(p):+ return _xml(200, "DescribeAutoScalingInstancesResponse",+ "<DescribeAutoScalingInstancesResult><AutoScalingInstances/></DescribeAutoScalingInstancesResult>")+++# ---------------------------------------------------------------------------+# LaunchConfiguration+# ---------------------------------------------------------------------------++def _create_lc(p):+ name = _p(p, "LaunchConfigurationName")+ if not name:+ return _error("ValidationError", "LaunchConfigurationName is required")+ if name in _launch_configs:+ return _error("AlreadyExistsFault", f"LaunchConfiguration {name} already exists")+ arn = f"arn:aws:autoscaling:{REGION}:{get_account_id()}:launchConfiguration:{new_uuid()}:launchConfigurationName/{name}"+ _launch_configs[name] = {+ "LaunchConfigurationName": name,+ "LaunchConfigurationARN": arn,+ "ImageId": _p(p, "ImageId") or "ami-00000000",+ "InstanceType": _p(p, "InstanceType") or "t2.micro",+ "KeyName": _p(p, "KeyName") or "",+ "SecurityGroups": _parse_member_list(p, "SecurityGroups"),+ "UserData": _p(p, "UserData") or "",+ "CreatedTime": now_iso(),+ }+ return _xml(200, "CreateLaunchConfigurationResponse", "<CreateLaunchConfigurationResult/>")+++def _describe_lcs(p):+ names = _parse_member_list(p, "LaunchConfigurationNames")+ members = ""+ for name, lc in _launch_configs.items():+ if names and name not in names:+ continue+ sgs = "".join(f"<member>{sg}</member>" for sg in lc.get("SecurityGroups", []))+ members += (f"<member>"+ f"<LaunchConfigurationName>{name}</LaunchConfigurationName>"+ f"<LaunchConfigurationARN>{lc['LaunchConfigurationARN']}</LaunchConfigurationARN>"+ f"<ImageId>{lc['ImageId']}</ImageId>"+ f"<InstanceType>{lc['InstanceType']}</InstanceType>"+ f"<CreatedTime>{lc['CreatedTime']}</CreatedTime>"+ f"<SecurityGroups>{sgs}</SecurityGroups>"+ f"</member>")+ return _xml(200, "DescribeLaunchConfigurationsResponse",+ f"<DescribeLaunchConfigurationsResult><LaunchConfigurations>{members}</LaunchConfigurations></DescribeLaunchConfigurationsResult>")+++def _delete_lc(p):+ name = _p(p, "LaunchConfigurationName")+ _launch_configs.pop(name, None)+ return _xml(200, "DeleteLaunchConfigurationResponse", "<DeleteLaunchConfigurationResult/>")+++# ---------------------------------------------------------------------------+# Scaling Policy+# ---------------------------------------------------------------------------++def _put_scaling_policy(p):+ asg_name = _p(p, "AutoScalingGroupName")+ policy_name = _p(p, "PolicyName")+ if not policy_name:+ return _error("ValidationError", "PolicyName is required")+ arn = f"arn:aws:autoscaling:{REGION}:{get_account_id()}:scalingPolicy:{new_uuid()}:autoScalingGroupName/{asg_name}:policyName/{policy_name}"+ key = f"{asg_name}/{policy_name}"+ _policies[key] = {+ "PolicyARN": arn,+ "PolicyName": policy_name,+ "AutoScalingGroupName": asg_name,+ "PolicyType": _p(p, "PolicyType") or "SimpleScaling",+ "AdjustmentType": _p(p, "AdjustmentType") or "ChangeInCapacity",+ "ScalingAdjustment": int(_p(p, "ScalingAdjustment") or 0),+ "Cooldown": int(_p(p, "Cooldown") or 300),+ }+ return _xml(200, "PutScalingPolicyResponse",+ f"<PutScalingPolicyResult><PolicyARN>{arn}</PolicyARN></PutScalingPolicyResult>")+++def _describe_policies(p):+ asg_name = _p(p, "AutoScalingGroupName")+ members = ""+ for key, pol in _policies.items():+ if asg_name and pol["AutoScalingGroupName"] != asg_name:+ continue+ members += (f"<member>"+ f"<PolicyARN>{pol['PolicyARN']}</PolicyARN>"+ f"<PolicyName>{pol['PolicyName']}</PolicyName>"+ f"<AutoScalingGroupName>{pol['AutoScalingGroupName']}</AutoScalingGroupName>"+ f"<PolicyType>{pol['PolicyType']}</PolicyType>"+ f"</member>")+ return _xml(200, "DescribePoliciesResponse",+ f"<DescribePoliciesResult><ScalingPolicies>{members}</ScalingPolicies></DescribePoliciesResult>")+++def _delete_policy(p):+ policy_name = _p(p, "PolicyName")+ asg_name = _p(p, "AutoScalingGroupName")+ key = f"{asg_name}/{policy_name}"+ _policies.pop(key, None)+ return _xml(200, "DeletePolicyResponse", "<DeletePolicyResult/>")+++# ---------------------------------------------------------------------------+# Lifecycle Hook+# ---------------------------------------------------------------------------++def _put_lifecycle_hook(p):+ asg_name = _p(p, "AutoScalingGroupName")+ hook_name = _p(p, "LifecycleHookName")+ key = f"{asg_name}/{hook_name}"+ _hooks[key] = {+ "LifecycleHookName": hook_name,+ "AutoScalingGroupName": asg_name,+ "LifecycleTransition": _p(p, "LifecycleTransition") or "autoscaling:EC2_INSTANCE_LAUNCHING",+ "HeartbeatTimeout": int(_p(p, "HeartbeatTimeout") or 3600),+ "DefaultResult": _p(p, "DefaultResult") or "ABANDON",+ "NotificationTargetARN": _p(p, "NotificationTargetARN") or "",+ "RoleARN": _p(p, "RoleARN") or "",+ }+ return _xml(200, "PutLifecycleHookResponse", "<PutLifecycleHookResult/>")+++def _describe_lifecycle_hooks(p):+ asg_name = _p(p, "AutoScalingGroupName")+ members = ""+ for key, hook in _hooks.items():+ if hook["AutoScalingGroupName"] != asg_name:+ continue+ members += (f"<member>"+ f"<LifecycleHookName>{hook['LifecycleHookName']}</LifecycleHookName>"+ f"<AutoScalingGroupName>{hook['AutoScalingGroupName']}</AutoScalingGroupName>"+ f"<LifecycleTransition>{hook['LifecycleTransition']}</LifecycleTransition>"+ f"<HeartbeatTimeout>{hook['HeartbeatTimeout']}</HeartbeatTimeout>"+ f"<DefaultResult>{hook['DefaultResult']}</DefaultResult>"+ f"</member>")+ return _xml(200, "DescribeLifecycleHooksResponse",+ f"<DescribeLifecycleHooksResult><LifecycleHooks>{members}</LifecycleHooks></DescribeLifecycleHooksResult>")+++def _delete_lifecycle_hook(p):+ asg_name = _p(p, "AutoScalingGroupName")+ hook_name = _p(p, "LifecycleHookName")+ _hooks.pop(f"{asg_name}/{hook_name}", None)+ return _xml(200, "DeleteLifecycleHookResponse", "<DeleteLifecycleHookResult/>")+++def _complete_lifecycle_action(p):+ return _xml(200, "CompleteLifecycleActionResponse", "<CompleteLifecycleActionResult/>")+++def _record_lifecycle_heartbeat(p):+ return _xml(200, "RecordLifecycleActionHeartbeatResponse", "<RecordLifecycleActionHeartbeatResult/>")+++# ---------------------------------------------------------------------------+# Scheduled Action+# ---------------------------------------------------------------------------++def _put_scheduled_action(p):+ asg_name = _p(p, "AutoScalingGroupName")+ action_name = _p(p, "ScheduledActionName")+ key = f"{asg_name}/{action_name}"+ arn = f"arn:aws:autoscaling:{REGION}:{get_account_id()}:scheduledUpdateGroupAction:{new_uuid()}:autoScalingGroupName/{asg_name}:scheduledActionName/{action_name}"+ _scheduled_actions[key] = {+ "ScheduledActionARN": arn,+ "ScheduledActionName": action_name,+ "AutoScalingGroupName": asg_name,+ "Recurrence": _p(p, "Recurrence") or "",+ "MinSize": int(_p(p, "MinSize") or -1),+ "MaxSize": int(_p(p, "MaxSize") or -1),+ "DesiredCapacity": int(_p(p, "DesiredCapacity") or -1),+ }+ return _xml(200, "PutScheduledUpdateGroupActionResponse", "<PutScheduledUpdateGroupActionResult/>")+++def _describe_scheduled_actions(p):+ asg_name = _p(p, "AutoScalingGroupName")+ members = ""+ for key, sa in _scheduled_actions.items():+ if asg_name and sa["AutoScalingGroupName"] != asg_name:+ continue+ members += (f"<member>"+ f"<ScheduledActionARN>{sa['ScheduledActionARN']}</ScheduledActionARN>"+ f"<ScheduledActionName>{sa['ScheduledActionName']}</ScheduledActionName>"+ f"<AutoScalingGroupName>{sa['AutoScalingGroupName']}</AutoScalingGroupName>"+ f"</member>")+ return _xml(200, "DescribeScheduledActionsResponse",+ f"<DescribeScheduledActionsResult><ScheduledUpdateGroupActions>{members}</ScheduledUpdateGroupActions></DescribeScheduledActionsResult>")+++def _delete_scheduled_action(p):+ asg_name = _p(p, "AutoScalingGroupName")+ action_name = _p(p, "ScheduledActionName")+ _scheduled_actions.pop(f"{asg_name}/{action_name}", None)+ return _xml(200, "DeleteScheduledActionResponse", "<DeleteScheduledActionResult/>")+++# ---------------------------------------------------------------------------+# Tags+# ---------------------------------------------------------------------------++def _create_or_update_tags(p):+ i = 1+ while _p(p, f"Tags.member.{i}.Key"):+ asg_name = _p(p, f"Tags.member.{i}.ResourceId")+ tag = {+ "Key": _p(p, f"Tags.member.{i}.Key"),+ "Value": _p(p, f"Tags.member.{i}.Value"),+ "ResourceId": asg_name,+ "ResourceType": "auto-scaling-group",+ "PropagateAtLaunch": _p(p, f"Tags.member.{i}.PropagateAtLaunch") == "true",+ }+ existing = _tags.setdefault(asg_name, [])+ existing = [t for t in existing if t["Key"] != tag["Key"]]+ existing.append(tag)+ _tags[asg_name] = existing+ if asg_name in _asgs:+ _asgs[asg_name]["Tags"] = existing+ i += 1+ return _xml(200, "CreateOrUpdateTagsResponse", "<CreateOrUpdateTagsResult/>")+++def _describe_tags(p):+ members = ""+ for asg_name, tag_list in _tags.items():+ for t in tag_list:+ members += (f"<member>"+ f"<Key>{t['Key']}</Key><Value>{t['Value']}</Value>"+ f"<ResourceId>{t['ResourceId']}</ResourceId>"+ f"<ResourceType>{t['ResourceType']}</ResourceType>"+ f"<PropagateAtLaunch>{'true' if t.get('PropagateAtLaunch') else 'false'}</PropagateAtLaunch>"+ f"</member>")+ return _xml(200, "DescribeTagsResponse",+ f"<DescribeTagsResult><Tags>{members}</Tags></DescribeTagsResult>")+++def _delete_tags(p):+ i = 1+ while _p(p, f"Tags.member.{i}.Key"):+ asg_name = _p(p, f"Tags.member.{i}.ResourceId")+ key = _p(p, f"Tags.member.{i}.Key")+ existing = _tags.get(asg_name, [])+ _tags[asg_name] = [t for t in existing if t["Key"] != key]+ if asg_name in _asgs:+ _asgs[asg_name]["Tags"] = _tags[asg_name]+ i += 1+ return _xml(200, "DeleteTagsResponse", "<DeleteTagsResult/>")+++# ---------------------------------------------------------------------------+# Request handler+# ---------------------------------------------------------------------------++_ACTION_MAP = {+ "CreateAutoScalingGroup": _create_asg,+ "DescribeAutoScalingGroups": _describe_asgs,+ "UpdateAutoScalingGroup": _update_asg,+ "DeleteAutoScalingGroup": _delete_asg,+ "DescribeAutoScalingInstances": _describe_asg_instances,+ "CreateLaunchConfiguration": _create_lc,+ "DescribeLaunchConfigurations": _describe_lcs,+ "DeleteLaunchConfiguration": _delete_lc,+ "PutScalingPolicy": _put_scaling_policy,+ "DescribePolicies": _describe_policies,+ "DeletePolicy": _delete_policy,+ "PutLifecycleHook": _put_lifecycle_hook,+ "DescribeLifecycleHooks": _describe_lifecycle_hooks,+ "DeleteLifecycleHook": _delete_lifecycle_hook,+ "CompleteLifecycleAction": _complete_lifecycle_action,+ "RecordLifecycleActionHeartbeat": _record_lifecycle_heartbeat,+ "PutScheduledUpdateGroupAction": _put_scheduled_action,+ "DescribeScheduledActions": _describe_scheduled_actions,+ "DeleteScheduledAction": _delete_scheduled_action,+ "CreateOrUpdateTags": _create_or_update_tags,+ "DescribeTags": _describe_tags,+ "DeleteTags": _delete_tags,+}+++async def handle_request(method, path, headers, body, query_params):+ from urllib.parse import parse_qs+ if body:+ params = parse_qs(body.decode("utf-8", errors="replace"), keep_blank_values=True)+ params = {k: v[0] if len(v) == 1 else v for k, v in params.items()}+ else:+ params = dict(query_params) if query_params else {}++ action = params.get("Action", "")+ if isinstance(action, list):+ action = action[0]++ handler = _ACTION_MAP.get(action)+ if not handler:+ s, h, b = _error("InvalidAction", f"Unknown AutoScaling action: {action}")+ return s, h, b++ s, h, b = handler(params)+ return s, h, bdiff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex ecb8a03b..a9288054 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -33,6 +33,14 @@ import ministack.services.ec2 as _ec2import ministack.services.ecs as _ecsimport ministack.services.alb as _albimport ministack.services.kinesis as _kinesis+import ministack.services.stepfunctions as _sfn+import ministack.services.route53 as _r53+import ministack.services.apigateway as _apigw_v2+import ministack.services.ses as _ses+import ministack.services.waf as _waf+import ministack.services.cloudfront as _cf+import ministack.services.rds as _rds+import ministack.services.autoscaling as _asglogger = logging.getLogger("cloudformation")@@ -1908,6 +1916,456 @@ def _elbv2_listener_delete(physical_id, props):_alb._tags.pop(rule_arn, None)+# ---------------------------------------------------------------------------+# Lambda LayerVersion+# ---------------------------------------------------------------------------++def _lambda_layer_create(logical_id, props, stack_name):+ layer_name = props.get("LayerName") or _physical_name(stack_name, logical_id, max_len=64)+ runtimes = props.get("CompatibleRuntimes", [])+ architectures = props.get("CompatibleArchitectures", [])++ content = props.get("Content", {})+ s3_bucket = content.get("S3Bucket", "")+ s3_key = content.get("S3Key", "")++ if layer_name not in _lambda_svc._layers:+ _lambda_svc._layers[layer_name] = {"versions": [], "next_version": 1}+ layer = _lambda_svc._layers[layer_name]+ ver = layer["next_version"]+ layer["next_version"] = ver + 1++ import base64, hashlib+ zip_data = None+ if s3_bucket and s3_key:+ zip_data = _s3._get_object_data(s3_bucket, s3_key)++ layer_arn = f"arn:aws:lambda:{REGION}:{get_account_id()}:layer:{layer_name}"+ version_arn = f"{layer_arn}:{ver}"++ ver_config = {+ "LayerArn": layer_arn,+ "LayerVersionArn": version_arn,+ "Version": ver,+ "Description": props.get("Description", ""),+ "CompatibleRuntimes": runtimes,+ "CompatibleArchitectures": architectures,+ "LicenseInfo": props.get("LicenseInfo", ""),+ "CreatedDate": now_iso(),+ "Content": {+ "CodeSha256": (base64.b64encode(hashlib.sha256(zip_data).digest()).decode() if zip_data else ""),+ "CodeSize": len(zip_data) if zip_data else 0,+ },+ }+ layer["versions"].append(ver_config)+ return version_arn, {"LayerVersionArn": version_arn, "Arn": version_arn}+++def _lambda_layer_delete(physical_id, props):+ # physical_id is the version ARN like arn:aws:lambda:...:layer:name:1+ parts = physical_id.split(":")+ if len(parts) >= 2:+ layer_name = parts[-2].split("layer:")[-1] if "layer:" in physical_id else ""+ layer = _lambda_svc._layers.get(layer_name)+ if layer:+ layer["versions"] = [v for v in layer["versions"] if v["LayerVersionArn"] != physical_id]+++# ---------------------------------------------------------------------------+# StepFunctions StateMachine+# ---------------------------------------------------------------------------++def _sfn_state_machine_create(logical_id, props, stack_name):+ name = props.get("StateMachineName") or _physical_name(stack_name, logical_id, max_len=80)+ role_arn = props.get("RoleArn", f"arn:aws:iam::{get_account_id()}:role/StepFunctionsRole")+ definition = props.get("DefinitionString", "{}")+ if isinstance(definition, dict):+ import json as _json+ definition = _json.dumps(definition)+ sm_type = props.get("StateMachineType", "STANDARD")++ arn = f"arn:aws:states:{REGION}:{get_account_id()}:stateMachine:{name}"+ ts = now_iso()+ _sfn._state_machines[arn] = {+ "stateMachineArn": arn,+ "name": name,+ "definition": definition,+ "roleArn": role_arn,+ "type": sm_type,+ "creationDate": ts,+ "status": "ACTIVE",+ "loggingConfiguration": props.get("LoggingConfiguration", {"level": "OFF", "includeExecutionData": False}),+ }+ return arn, {"Arn": arn, "Name": name}+++def _sfn_state_machine_delete(physical_id, props):+ _sfn._state_machines.pop(physical_id, None)+++# ---------------------------------------------------------------------------+# Route53 HostedZone+# ---------------------------------------------------------------------------++def _r53_hosted_zone_create(logical_id, props, stack_name):+ zone_name = props.get("Name", "")+ if not zone_name.endswith("."):+ zone_name += "."++ zone_id = _r53._zone_id()+ caller_ref = new_uuid()++ _r53._zones[zone_id] = {+ "id": zone_id,+ "name": zone_name,+ "caller_reference": caller_ref,+ "comment": (props.get("HostedZoneConfig", {}) or {}).get("Comment", ""),+ "private": False,+ }+ _r53._records[zone_id] = _r53._default_records(zone_name)+ _r53._caller_refs[caller_ref] = zone_id+ return zone_id, {"Id": zone_id, "NameServers": ["ns-1.awsdns-01.org", "ns-2.awsdns-02.co.uk"]}+++def _r53_hosted_zone_delete(physical_id, props):+ _r53._zones.pop(physical_id, None)+ _r53._records.pop(physical_id, None)+++# ---------------------------------------------------------------------------+# ApiGatewayV2 Api+# ---------------------------------------------------------------------------++def _apigw_v2_api_create(logical_id, props, stack_name):+ api_id = new_uuid()[:8]+ name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=128)+ protocol = props.get("ProtocolType", "HTTP")+ api = {+ "apiId": api_id,+ "name": name,+ "protocolType": protocol,+ "apiEndpoint": f"http://{api_id}.execute-api.localhost:4566",+ "createdDate": now_iso(),+ "routeSelectionExpression": props.get("RouteSelectionExpression", "$request.method $request.path"),+ "apiKeySelectionExpression": props.get("ApiKeySelectionExpression", "$request.header.x-api-key"),+ "tags": props.get("Tags", {}),+ "disableSchemaValidation": props.get("DisableSchemaValidation", False),+ "disableExecuteApiEndpoint": props.get("DisableExecuteApiEndpoint", False),+ "version": props.get("Version", ""),+ }+ if props.get("CorsConfiguration"):+ api["corsConfiguration"] = props["CorsConfiguration"]+ _apigw_v2._apis[api_id] = api+ _apigw_v2._routes[api_id] = {}+ _apigw_v2._integrations[api_id] = {}+ _apigw_v2._stages[api_id] = {}+ _apigw_v2._deployments[api_id] = {}+ return api_id, {"ApiId": api_id, "ApiEndpoint": api["apiEndpoint"]}+++def _apigw_v2_api_delete(physical_id, props):+ _apigw_v2._apis.pop(physical_id, None)+ _apigw_v2._routes.pop(physical_id, None)+ _apigw_v2._integrations.pop(physical_id, None)+ _apigw_v2._stages.pop(physical_id, None)+ _apigw_v2._deployments.pop(physical_id, None)+++# ---------------------------------------------------------------------------+# ApiGatewayV2 Stage+# ---------------------------------------------------------------------------++def _apigw_v2_stage_create(logical_id, props, stack_name):+ api_id = props.get("ApiId", "")+ stage_name = props.get("StageName", "$default")+ stage = {+ "stageName": stage_name,+ "autoDeploy": props.get("AutoDeploy", False),+ "createdDate": now_iso(),+ "lastUpdatedDate": now_iso(),+ "stageVariables": props.get("StageVariables", {}),+ "description": props.get("Description", ""),+ "defaultRouteSettings": props.get("DefaultRouteSettings", {}),+ "routeSettings": props.get("RouteSettings", {}),+ "tags": props.get("Tags", {}),+ }+ _apigw_v2._stages.setdefault(api_id, {})[stage_name] = stage+ physical_id = f"{api_id}/{stage_name}"+ return physical_id, {"StageName": stage_name}+++def _apigw_v2_stage_delete(physical_id, props):+ parts = physical_id.split("/", 1)+ if len(parts) == 2:+ api_id, stage_name = parts+ stages = _apigw_v2._stages.get(api_id, {})+ stages.pop(stage_name, None)+++# ---------------------------------------------------------------------------+# SES EmailIdentity+# ---------------------------------------------------------------------------++def _ses_email_identity_create(logical_id, props, stack_name):+ identity = props.get("EmailIdentity", "")+ _ses._identities[identity] = _ses._make_identity(identity,+ "Domain" if "@" not in identity else "EmailAddress")+ return identity, {"EmailIdentity": identity}+++def _ses_email_identity_delete(physical_id, props):+ _ses._identities.pop(physical_id, None)+++# ---------------------------------------------------------------------------+# WAFv2 WebACL+# ---------------------------------------------------------------------------++def _waf_web_acl_create(logical_id, props, stack_name):+ name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=128)+ uid = new_uuid()+ lock_token = new_uuid()+ scope = props.get("Scope", "REGIONAL")+ arn = f"arn:aws:wafv2:{REGION}:{get_account_id()}:{scope.lower()}/webacl/{name}/{uid}"+ _waf._web_acls[uid] = {+ "ARN": arn, "Id": uid, "Name": name,+ "Description": props.get("Description", ""),+ "DefaultAction": props.get("DefaultAction", {"Allow": {}}),+ "Rules": props.get("Rules", []),+ "VisibilityConfig": props.get("VisibilityConfig", {}),+ "Capacity": 0,+ "LockToken": lock_token,+ "Scope": scope,+ }+ return uid, {"Arn": arn, "Id": uid}+++def _waf_web_acl_delete(physical_id, props):+ _waf._web_acls.pop(physical_id, None)+++# ---------------------------------------------------------------------------+# CloudFront Distribution+# ---------------------------------------------------------------------------++def _cf_distribution_create(logical_id, props, stack_name):+ dist_config = props.get("DistributionConfig", props)+ dist_id = _cf._dist_id()+ arn = f"arn:aws:cloudfront::{get_account_id()}:distribution/{dist_id}"++ origins = dist_config.get("Origins", [])+ default_cache = dist_config.get("DefaultCacheBehavior", {})++ _cf._distributions[dist_id] = {+ "Id": dist_id,+ "ARN": arn,+ "Status": "Deployed",+ "DomainName": f"{dist_id}.cloudfront.net",+ "LastModifiedTime": now_iso(),+ "ETag": new_uuid(),+ "config_xml": "",+ "enabled": dist_config.get("Enabled", True),+ }+ return dist_id, {"Arn": arn, "DomainName": f"{dist_id}.cloudfront.net", "Id": dist_id}+++def _cf_distribution_delete(physical_id, props):+ _cf._distributions.pop(physical_id, None)+++# ---------------------------------------------------------------------------+# RDS DBCluster+# ---------------------------------------------------------------------------++def _rds_db_cluster_create(logical_id, props, stack_name):+ cluster_id = props.get("DBClusterIdentifier") or _physical_name(stack_name, logical_id, lowercase=True, max_len=63)+ engine = props.get("Engine", "aurora-postgresql")+ engine_version = props.get("EngineVersion", "15.4")+ master_user = props.get("MasterUsername", "admin")+ arn = f"arn:aws:rds:{REGION}:{get_account_id()}:cluster:{cluster_id}"+ suffix = new_uuid()[:8]++ _rds._clusters[cluster_id] = {+ "DBClusterIdentifier": cluster_id,+ "DBClusterArn": arn,+ "Engine": engine,+ "EngineVersion": engine_version,+ "EngineMode": props.get("EngineMode", "provisioned"),+ "Status": "available",+ "MasterUsername": master_user,+ "DatabaseName": props.get("DatabaseName", ""),+ "Endpoint": f"{cluster_id}.cluster-{suffix}.{REGION}.rds.amazonaws.com",+ "ReaderEndpoint": f"{cluster_id}.cluster-ro-{suffix}.{REGION}.rds.amazonaws.com",+ "Port": int(props.get("Port", 5432)),+ "MultiAZ": props.get("MultiAZ", False),+ "AvailabilityZones": [f"{REGION}a", f"{REGION}b", f"{REGION}c"],+ "DBClusterMembers": [],+ "VpcSecurityGroups": [],+ "DBSubnetGroup": props.get("DBSubnetGroupName", "default"),+ "StorageEncrypted": props.get("StorageEncrypted", False),+ "DeletionProtection": props.get("DeletionProtection", False),+ "CopyTagsToSnapshot": props.get("CopyTagsToSnapshot", False),+ "AllocatedStorage": 1,+ "ClusterCreateTime": now_iso(),+ "BackupRetentionPeriod": int(props.get("BackupRetentionPeriod", 1)),+ }+ return cluster_id, {+ "Arn": arn,+ "ClusterResourceId": f"cluster-{new_uuid()[:20]}",+ "Endpoint.Address": f"{cluster_id}.cluster-{suffix}.{REGION}.rds.amazonaws.com",+ "Endpoint.Port": str(int(props.get("Port", 5432))),+ "ReadEndpoint.Address": f"{cluster_id}.cluster-ro-{suffix}.{REGION}.rds.amazonaws.com",+ }+++def _rds_db_cluster_delete(physical_id, props):+ _rds._clusters.pop(physical_id, None)+++# ---------------------------------------------------------------------------+# AutoScaling Group+# ---------------------------------------------------------------------------++def _asg_create(logical_id, props, stack_name):+ name = props.get("AutoScalingGroupName") or _physical_name(stack_name, logical_id, max_len=255)+ arn = f"arn:aws:autoscaling:{REGION}:{get_account_id()}:autoScalingGroup:{new_uuid()}:autoScalingGroupName/{name}"+ asg = {+ "AutoScalingGroupName": name,+ "AutoScalingGroupARN": arn,+ "LaunchConfigurationName": props.get("LaunchConfigurationName", ""),+ "LaunchTemplate": {},+ "MinSize": int(props.get("MinSize", 0)),+ "MaxSize": int(props.get("MaxSize", 0)),+ "DesiredCapacity": int(props.get("DesiredCapacity", props.get("MinSize", 0))),+ "DefaultCooldown": int(props.get("Cooldown", 300)),+ "AvailabilityZones": props.get("AvailabilityZones", [f"{REGION}a"]),+ "HealthCheckType": props.get("HealthCheckType", "EC2"),+ "HealthCheckGracePeriod": int(props.get("HealthCheckGracePeriod", 300)),+ "Instances": [],+ "CreatedTime": now_iso(),+ "VPCZoneIdentifier": ",".join(props.get("VPCZoneIdentifier", [])) if isinstance(props.get("VPCZoneIdentifier"), list) else props.get("VPCZoneIdentifier", ""),+ "TerminationPolicies": props.get("TerminationPolicies", ["Default"]),+ "NewInstancesProtectedFromScaleIn": props.get("NewInstancesProtectedFromScaleIn", False),+ "Tags": [],+ "Status": "",+ }+ lt = props.get("LaunchTemplate", {})+ if lt:+ asg["LaunchTemplate"] = {+ "LaunchTemplateId": lt.get("LaunchTemplateId", lt.get("LaunchTemplateName", "")),+ "LaunchTemplateName": lt.get("LaunchTemplateName", ""),+ "Version": lt.get("Version", "$Default"),+ }+ tags = []+ for t in props.get("Tags", []):+ tags.append({+ "Key": t.get("Key", ""),+ "Value": t.get("Value", ""),+ "ResourceId": name,+ "ResourceType": "auto-scaling-group",+ "PropagateAtLaunch": t.get("PropagateAtLaunch", False),+ })+ asg["Tags"] = tags+ _asg._asgs[name] = asg+ _asg._tags[name] = tags+ return name, {"Arn": arn}+++def _asg_delete(physical_id, props):+ _asg._asgs.pop(physical_id, None)+ _asg._tags.pop(physical_id, None)+++def _asg_lc_create(logical_id, props, stack_name):+ name = props.get("LaunchConfigurationName") or _physical_name(stack_name, logical_id, max_len=255)+ arn = f"arn:aws:autoscaling:{REGION}:{get_account_id()}:launchConfiguration:{new_uuid()}:launchConfigurationName/{name}"+ _asg._launch_configs[name] = {+ "LaunchConfigurationName": name,+ "LaunchConfigurationARN": arn,+ "ImageId": props.get("ImageId", "ami-00000000"),+ "InstanceType": props.get("InstanceType", "t2.micro"),+ "KeyName": props.get("KeyName", ""),+ "SecurityGroups": props.get("SecurityGroups", []),+ "UserData": props.get("UserData", ""),+ "CreatedTime": now_iso(),+ }+ return name, {"Arn": arn}+++def _asg_lc_delete(physical_id, props):+ _asg._launch_configs.pop(physical_id, None)+++def _asg_policy_create(logical_id, props, stack_name):+ asg_name = props.get("AutoScalingGroupName", "")+ policy_name = props.get("PolicyName") or _physical_name(stack_name, logical_id, max_len=255)+ arn = f"arn:aws:autoscaling:{REGION}:{get_account_id()}:scalingPolicy:{new_uuid()}:autoScalingGroupName/{asg_name}:policyName/{policy_name}"+ key = f"{asg_name}/{policy_name}"+ _asg._policies[key] = {+ "PolicyARN": arn,+ "PolicyName": policy_name,+ "AutoScalingGroupName": asg_name,+ "PolicyType": props.get("PolicyType", "SimpleScaling"),+ "AdjustmentType": props.get("AdjustmentType", "ChangeInCapacity"),+ "ScalingAdjustment": int(props.get("ScalingAdjustment", 0)),+ "Cooldown": int(props.get("Cooldown", 300)),+ }+ return arn, {"Arn": arn, "PolicyName": policy_name}+++def _asg_policy_delete(physical_id, props):+ # physical_id is the ARN, find matching key+ for k, v in list(_asg._policies.items()):+ if v.get("PolicyARN") == physical_id:+ _asg._policies.pop(k, None)+ break+++def _asg_hook_create(logical_id, props, stack_name):+ asg_name = props.get("AutoScalingGroupName", "")+ hook_name = props.get("LifecycleHookName") or _physical_name(stack_name, logical_id, max_len=255)+ key = f"{asg_name}/{hook_name}"+ _asg._hooks[key] = {+ "LifecycleHookName": hook_name,+ "AutoScalingGroupName": asg_name,+ "LifecycleTransition": props.get("LifecycleTransition", "autoscaling:EC2_INSTANCE_LAUNCHING"),+ "HeartbeatTimeout": int(props.get("HeartbeatTimeout", 3600)),+ "DefaultResult": props.get("DefaultResult", "ABANDON"),+ "NotificationTargetARN": props.get("NotificationTargetARN", ""),+ "RoleARN": props.get("RoleARN", ""),+ }+ return hook_name, {"LifecycleHookName": hook_name}+++def _asg_hook_delete(physical_id, props):+ asg_name = props.get("AutoScalingGroupName", "")+ _asg._hooks.pop(f"{asg_name}/{physical_id}", None)+++def _asg_scheduled_create(logical_id, props, stack_name):+ asg_name = props.get("AutoScalingGroupName", "")+ action_name = props.get("ScheduledActionName") or _physical_name(stack_name, logical_id, max_len=255)+ arn = f"arn:aws:autoscaling:{REGION}:{get_account_id()}:scheduledUpdateGroupAction:{new_uuid()}:autoScalingGroupName/{asg_name}:scheduledActionName/{action_name}"+ key = f"{asg_name}/{action_name}"+ _asg._scheduled_actions[key] = {+ "ScheduledActionARN": arn,+ "ScheduledActionName": action_name,+ "AutoScalingGroupName": asg_name,+ "Recurrence": props.get("Recurrence", ""),+ "MinSize": int(props.get("MinSize", -1)),+ "MaxSize": int(props.get("MaxSize", -1)),+ "DesiredCapacity": int(props.get("DesiredCapacity", -1)),+ }+ return arn, {"Arn": arn, "ScheduledActionName": action_name}+++def _asg_scheduled_delete(physical_id, props):+ for k, v in list(_asg._scheduled_actions.items()):+ if v.get("ScheduledActionARN") == physical_id:+ _asg._scheduled_actions.pop(k, None)+ break++# Resource Handler Registry# ===========================================================================@@ -1967,12 +2425,21 @@ _RESOURCE_HANDLERS = {"AWS::EC2::LaunchTemplate": {"create": _ec2_launch_template_create, "delete": _ec2_launch_template_delete},"AWS::ElasticLoadBalancingV2::LoadBalancer": {"create": _elbv2_load_balancer_create, "delete": _elbv2_load_balancer_delete,},"AWS::ElasticLoadBalancingV2::Listener": {"create": _elbv2_listener_create, "delete": _elbv2_listener_delete,},+ "AWS::Lambda::LayerVersion": {"create": _lambda_layer_create, "delete": _lambda_layer_delete},+ "AWS::StepFunctions::StateMachine": {"create": _sfn_state_machine_create, "delete": _sfn_state_machine_delete},+ "AWS::Route53::HostedZone": {"create": _r53_hosted_zone_create, "delete": _r53_hosted_zone_delete},+ "AWS::ApiGatewayV2::Api": {"create": _apigw_v2_api_create, "delete": _apigw_v2_api_delete},+ "AWS::ApiGatewayV2::Stage": {"create": _apigw_v2_stage_create, "delete": _apigw_v2_stage_delete},+ "AWS::SES::EmailIdentity": {"create": _ses_email_identity_create, "delete": _ses_email_identity_delete},+ "AWS::WAFv2::WebACL": {"create": _waf_web_acl_create, "delete": _waf_web_acl_delete},+ "AWS::CloudFront::Distribution": {"create": _cf_distribution_create, "delete": _cf_distribution_delete},+ "AWS::RDS::DBCluster": {"create": _rds_db_cluster_create, "delete": _rds_db_cluster_delete},# CDK metadata — safe to ignore"AWS::CDK::Metadata": {"create": lambda lid, props, sn: (f"CDKMetadata-{lid}", {}), "delete": lambda pid, props: None},- # AutoScaling stubs — allow CDK/CFN stacks with ASGs to deploy- "AWS::AutoScaling::AutoScalingGroup": {"create": lambda lid, props, sn: (f"asg-{lid}", {}), "delete": lambda pid, props: None},- "AWS::AutoScaling::LaunchConfiguration": {"create": lambda lid, props, sn: (f"lc-{lid}", {}), "delete": lambda pid, props: None},- "AWS::AutoScaling::ScalingPolicy": {"create": lambda lid, props, sn: (f"sp-{lid}", {}), "delete": lambda pid, props: None},- "AWS::AutoScaling::LifecycleHook": {"create": lambda lid, props, sn: (f"lh-{lid}", {}), "delete": lambda pid, props: None},- "AWS::AutoScaling::ScheduledAction": {"create": lambda lid, props, sn: (f"sa-{lid}", {}), "delete": lambda pid, props: None},+ # AutoScaling+ "AWS::AutoScaling::AutoScalingGroup": {"create": _asg_create, "delete": _asg_delete},+ "AWS::AutoScaling::LaunchConfiguration": {"create": _asg_lc_create, "delete": _asg_lc_delete},+ "AWS::AutoScaling::ScalingPolicy": {"create": _asg_policy_create, "delete": _asg_policy_delete},+ "AWS::AutoScaling::LifecycleHook": {"create": _asg_hook_create, "delete": _asg_hook_delete},+ "AWS::AutoScaling::ScheduledAction": {"create": _asg_scheduled_create, "delete": _asg_scheduled_delete},}diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex f3b11b75..ad77bd90 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -485,7 +485,6 @@ def _create_user_pool(data):"EmailVerificationSubject": data.get("EmailVerificationSubject", ""),"SmsAuthenticationMessage": data.get("SmsAuthenticationMessage", ""),"MfaConfiguration": data.get("MfaConfiguration", "OFF"),- "DeviceConfiguration": data.get("DeviceConfiguration", {}),"EstimatedNumberOfUsers": 0,"EmailConfiguration": data.get("EmailConfiguration", {}),"SmsConfiguration": data.get("SmsConfiguration", {}),@@ -494,15 +493,21 @@ def _create_user_pool(data):"AllowAdminCreateUserOnly": False,"UnusedAccountValidityDays": 7,}),- "UsernameConfiguration": data.get("UsernameConfiguration", {"CaseSensitive": False}),"AccountRecoverySetting": data.get("AccountRecoverySetting", {}),- "UserPoolAddOns": data.get("UserPoolAddOns", {}),- "VerificationMessageTemplate": data.get("VerificationMessageTemplate", {}),+ "DeletionProtection": data.get("DeletionProtection", "INACTIVE"),"Domain": None,"_clients": {},"_users": {},"_groups": {},}+ if data.get("DeviceConfiguration"):+ pool["DeviceConfiguration"] = data["DeviceConfiguration"]+ if data.get("UsernameConfiguration"):+ pool["UsernameConfiguration"] = data["UsernameConfiguration"]+ if data.get("UserPoolAddOns"):+ pool["UserPoolAddOns"] = data["UserPoolAddOns"]+ if data.get("VerificationMessageTemplate"):+ pool["VerificationMessageTemplate"] = data["VerificationMessageTemplate"]_user_pools[pid] = poollogger.info("Cognito: CreateUserPool %s (%s)", name, pid)return json_response({"UserPool": _pool_out(pool)})diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.pyindex 5549dfd6..15c0b344 100644--- a/ministack/services/dynamodb.py+++ b/ministack/services/dynamodb.py@@ -264,6 +264,8 @@ def _create_table(data):"StreamSpecification": data.get("StreamSpecification"),"SSEDescription": data.get("SSESpecification"),}+ if data.get("Tags"):+ _tags[_tables[name]["TableArn"]] = data["Tags"]return json_response({"TableDescription": _table_description(name)})diff --git a/ministack/services/ec2.py b/ministack/services/ec2.pyindex b96c9d35..76435f89 100644--- a/ministack/services/ec2.py+++ b/ministack/services/ec2.py@@ -4,7 +4,7 @@ Query API (Action=...) — instances exist in memory only, no real VMs launched.Supports:Instances: RunInstances, TerminateInstances, DescribeInstances,- StartInstances, StopInstances, RebootInstances+ DescribeInstanceStatus, StartInstances, StopInstances, RebootInstancesImages: DescribeImages (stub — returns common AMI IDs)Security Groups: CreateSecurityGroup, DeleteSecurityGroup, DescribeSecurityGroups,AuthorizeSecurityGroupIngress, RevokeSecurityGroupIngress,@@ -355,6 +355,43 @@ def _describe_instances(p):return _xml(200, "DescribeInstancesResponse", f"<reservationSet>{items}</reservationSet>")+def _describe_instance_status(p):+ filter_ids = _parse_member_list(p, "InstanceId")+ raw = p.get("IncludeAllInstances", "false")+ if isinstance(raw, list):+ raw = raw[0] if raw else "false"+ include_all = raw.lower() == "true"++ results = []+ for iid, inst in _instances.items():+ if filter_ids and iid not in filter_ids:+ continue+ state = inst["State"]["Name"]+ if not include_all and state != "running":+ continue+ az = inst.get("Placement", {}).get("AvailabilityZone", "us-east-1a")+ results.append(f"""<item>+ <instanceId>{iid}</instanceId>+ <availabilityZone>{az}</availabilityZone>+ <instanceState>+ <code>{inst['State']['Code']}</code>+ <name>{state}</name>+ </instanceState>+ <systemStatus>+ <status>ok</status>+ <details><item><name>reachability</name><status>passed</status></item></details>+ </systemStatus>+ <instanceStatus>+ <status>ok</status>+ <details><item><name>reachability</name><status>passed</status></item></details>+ </instanceStatus>+ </item>""")++ items = "".join(results)+ return _xml(200, "DescribeInstanceStatusResponse",+ f"<instanceStatusSet>{items}</instanceStatusSet>")++def _terminate_instances(p):ids = _parse_member_list(p, "InstanceId")items = ""@@ -825,6 +862,16 @@ def _describe_vpc_attribute(p):return _xml(200, "DescribeVpcAttributeResponse", f"<vpcId>{vpc_id}</vpcId>")+def _describe_vpc_classic_link(p):+ """Stub — ClassicLink is deprecated, return empty set."""+ return _xml(200, "DescribeVpcClassicLinkResponse", "<vpcSet/>")+++def _describe_vpc_classic_link_dns_support(p):+ """Stub — ClassicLink DNS support, return empty set."""+ return _xml(200, "DescribeVpcClassicLinkDnsSupportResponse", "<vpcs/>")++def _modify_subnet_attribute(p):subnet_id = _p(p, "SubnetId")if subnet_id not in _subnets:@@ -3596,6 +3643,7 @@ def _delete_launch_template(p):_ACTION_MAP = {"RunInstances": _run_instances,"DescribeInstances": _describe_instances,+ "DescribeInstanceStatus": _describe_instance_status,"DescribeInstanceAttribute": _describe_instance_attribute,"DescribeInstanceCreditSpecifications": _describe_instance_credit_specifications,"DescribeInstanceMaintenanceOptions": _describe_instance_maintenance_options,@@ -3643,6 +3691,8 @@ _ACTION_MAP = {"DescribeTags": _describe_tags,"ModifyVpcAttribute": _modify_vpc_attribute,"DescribeVpcAttribute": _describe_vpc_attribute,+ "DescribeVpcClassicLink": _describe_vpc_classic_link,+ "DescribeVpcClassicLinkDnsSupport": _describe_vpc_classic_link_dns_support,"DescribeAddressesAttribute": _describe_addresses_attribute,"DescribeSecurityGroupRules": _describe_security_group_rules,"ModifySubnetAttribute": _modify_subnet_attribute,diff --git a/ministack/services/ecs.py b/ministack/services/ecs.pyindex 25573f9e..790de219 100644--- a/ministack/services/ecs.py+++ b/ministack/services/ecs.py@@ -381,14 +381,7 @@ def _register_task_definition(data):return error_response_json("ClientException",f"Container definition {idx} ({cdef['name']}): image is required.", 400)cdef.setdefault("cpu", 0)- cdef.setdefault("memory", 0)- cdef.setdefault("memoryReservation", 0)cdef.setdefault("essential", True)- cdef.setdefault("portMappings", [])- cdef.setdefault("environment", [])- cdef.setdefault("mountPoints", [])- cdef.setdefault("volumesFrom", [])- cdef.setdefault("logConfiguration", None)rev = _task_def_latest.get(family, 0) + 1_task_def_latest[family] = revdiff --git a/ministack/services/kinesis.py b/ministack/services/kinesis.pyindex 1a71b906..9f4e35b1 100644--- a/ministack/services/kinesis.py+++ b/ministack/services/kinesis.py@@ -577,7 +577,9 @@ def _increase_retention(data):if hours is None:return error_response_json("ValidationException", "RetentionPeriodHours is required", 400)hours = int(hours)- if hours <= stream["RetentionPeriodHours"]:+ if hours == stream["RetentionPeriodHours"]:+ return json_response({}) # no-op: same value is fine+ if hours < stream["RetentionPeriodHours"]:return error_response_json("ValidationException","RetentionPeriodHours must be greater than current value", 400)if hours > 8760:diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex ddac2a85..818a5bd1 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -373,12 +373,10 @@ def _build_config(name: str, data: dict, code_zip: bytes | None = None) -> dict:layers_cfg.append(layer)env = data.get("Environment")- if env is None:- env = {"Variables": {}}- elif "Variables" not in env:+ if env is not None and "Variables" not in env:env["Variables"] = {}- return {+ config = {"FunctionName": name,"FunctionArn": _func_arn(name),"Runtime": data.get("Runtime", "" if is_image else "python3.9"),@@ -399,7 +397,6 @@ def _build_config(name: str, data: dict, code_zip: bytes | None = None) -> dict:"LastUpdateStatusReasonCode": "","PackageType": data.get("PackageType", "Zip"),"Architectures": data.get("Architectures", ["x86_64"]),- "Environment": env,"Layers": layers_cfg,"TracingConfig": data.get("TracingConfig", {"Mode": "PassThrough"}),"VpcConfig": data.get(@@ -410,7 +407,6 @@ def _build_config(name: str, data: dict, code_zip: bytes | None = None) -> dict:"VpcId": "",},),- "DeadLetterConfig": data.get("DeadLetterConfig", {}),"KMSKeyArn": data.get("KMSKeyArn", ""),"RevisionId": new_uuid(),"EphemeralStorage": data.get("EphemeralStorage", {"Size": 512}),@@ -426,6 +422,14 @@ def _build_config(name: str, data: dict, code_zip: bytes | None = None) -> dict:"RuntimeVersionArn": "",},}+ if env is not None:+ config["Environment"] = env+ dlc = data.get("DeadLetterConfig")+ if dlc and dlc.get("TargetArn"):+ config["DeadLetterConfig"] = dlc+ return config++def _qp_first(query_params: dict, key: str, default: str = "") -> str:@@ -2585,7 +2589,7 @@ def _delete_provisioned_concurrency(func_name: str, qualifier: str):def _esm_response(esm: dict) -> dict:"""Return ESM dict without internal-only fields."""- return {k: v for k, v in esm.items() if k != "FunctionName"}+ return {k: v for k, v in esm.items() if k not in ("FunctionName", "Enabled")}def _create_esm(data: dict):@@ -2593,18 +2597,21 @@ def _create_esm(data: dict):func_name = _resolve_name(data.get("FunctionName", ""))event_source_arn = data.get("EventSourceArn", "")+ enabled = data.get("Enabled", True)+ if isinstance(enabled, str):+ enabled = enabled.lower() != "false"esm = {"UUID": esm_id,"EventSourceArn": event_source_arn,"FunctionArn": _func_arn(func_name),"FunctionName": func_name,- "State": "Enabled",+ "State": "Enabled" if enabled else "Disabled","StateTransitionReason": "USER_INITIATED","BatchSize": data.get("BatchSize", 10),"MaximumBatchingWindowInSeconds": data.get("MaximumBatchingWindowInSeconds", 0),"LastModified": time.time(),"LastProcessingResult": "No records processed",- "Enabled": True,+ "Enabled": enabled,"FunctionResponseTypes": data.get("FunctionResponseTypes", []),}if ":sqs:" not in event_source_arn:@@ -2984,10 +2991,12 @@ def _create_function_url_config(func_name: str, data: dict, qualifier: str | Non"FunctionUrl": f"https://{new_uuid()}.lambda-url.{REGION}.on.aws/","FunctionArn": _func_arn(func_name),"AuthType": data.get("AuthType", "NONE"),- "Cors": data.get("Cors", {}),+ "InvokeMode": data.get("InvokeMode", "BUFFERED"),"CreationTime": _now_iso(),"LastModifiedTime": _now_iso(),}+ if data.get("Cors"):+ cfg["Cors"] = data["Cors"]_function_urls[key] = cfgreturn json_response(cfg, status=201)diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex e5245bfc..15367c73 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -71,6 +71,7 @@ _bucket_accelerate_config = AccountScopedDict()_bucket_request_payment_config = AccountScopedDict()_object_tags = AccountScopedDict()+_object_versions = AccountScopedDict() # (bucket, key) -> [{version_id, obj_record}, ...]_bucket_object_lock = AccountScopedDict()_bucket_replication = AccountScopedDict()@@ -1038,22 +1039,52 @@ def _list_object_versions(bucket_name: str, query_params: dict):keys = sorted(k for k in bucket["objects"] if k.startswith(prefix) and k > key_marker)- is_truncated = len(keys) > max_keys- SubElement(root, "IsTruncated").text = "true" if is_truncated else "false"+ is_truncated = False+ SubElement(root, "IsTruncated").text = "false"- for k in keys[:max_keys]:- obj = bucket["objects"][k]- ver = SubElement(root, "Version")- SubElement(ver, "Key").text = k- SubElement(ver, "VersionId").text = "1"- SubElement(ver, "IsLatest").text = "true"- SubElement(ver, "LastModified").text = obj["last_modified"]- SubElement(ver, "ETag").text = obj["etag"]- SubElement(ver, "Size").text = str(obj["size"])- SubElement(ver, "StorageClass").text = "STANDARD"- owner = SubElement(ver, "Owner")- SubElement(owner, "ID").text = "owner-id"- SubElement(owner, "DisplayName").text = "ministack"+ count = 0+ for k in keys:+ if count >= max_keys:+ is_truncated = True+ break+ vkey = (bucket_name, k)+ versions = _object_versions.get(vkey)+ if versions:+ # Return all stored versions (newest first)+ for v in reversed(versions):+ if count >= max_keys:+ is_truncated = True+ break+ ver = SubElement(root, "Version")+ SubElement(ver, "Key").text = k+ SubElement(ver, "VersionId").text = v["version_id"]+ SubElement(ver, "IsLatest").text = "true" if v["is_latest"] else "false"+ SubElement(ver, "LastModified").text = v["last_modified"]+ SubElement(ver, "ETag").text = v["etag"]+ SubElement(ver, "Size").text = str(v["size"])+ SubElement(ver, "StorageClass").text = "STANDARD"+ owner = SubElement(ver, "Owner")+ SubElement(owner, "ID").text = "owner-id"+ SubElement(owner, "DisplayName").text = "ministack"+ count += 1+ else:+ # No version history — return current object with null version+ obj = bucket["objects"][k]+ ver = SubElement(root, "Version")+ SubElement(ver, "Key").text = k+ SubElement(ver, "VersionId").text = obj.get("version_id", "null")+ SubElement(ver, "IsLatest").text = "true"+ SubElement(ver, "LastModified").text = obj["last_modified"]+ SubElement(ver, "ETag").text = obj["etag"]+ SubElement(ver, "Size").text = str(obj["size"])+ SubElement(ver, "StorageClass").text = "STANDARD"+ owner = SubElement(ver, "Owner")+ SubElement(owner, "ID").text = "owner-id"+ SubElement(owner, "DisplayName").text = "ministack"+ count += 1++ # Update IsTruncated after actual count+ root.find("IsTruncated").text = "true" if is_truncated else "false"return 200, {"Content-Type": "application/xml"}, _xml_body(root)@@ -1381,6 +1412,20 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):version_id = new_uuid()obj["version_id"] = version_idresp_headers["x-amz-version-id"] = version_id+ vkey = (bucket_name, key)+ if vkey not in _object_versions:+ _object_versions[vkey] = []+ _object_versions[vkey].append({+ "version_id": version_id,+ "last_modified": obj["last_modified"],+ "etag": obj["etag"],+ "size": obj["size"],+ "is_latest": True,+ "data": obj.get("data", body if len(body) < 10_000_000 else None),+ })+ # Mark all previous versions as not latest+ for v in _object_versions[vkey][:-1]:+ v["is_latest"] = Falsereturn 200, resp_headers, b""@@ -1494,6 +1539,7 @@ def _delete_object(bucket_name: str, key: str, headers: dict | None = None):_object_tags.pop((bucket_name, key), None)_object_retention.pop((bucket_name, key), None)_object_legal_hold.pop((bucket_name, key), None)+ _object_versions.pop((bucket_name, key), None)if existed:_fire_s3_event_async(bucket_name, key, "s3:ObjectRemoved:Delete")diff --git a/ministack/services/ses.py b/ministack/services/ses.pyindex f91624fa..b85ef79b 100644--- a/ministack/services/ses.py+++ b/ministack/services/ses.py@@ -378,7 +378,7 @@ def _get_identity_verification_attributes(params):def _delete_identity(params):identity = _p(params, "Identity")_identities.pop(identity, None)- return _xml(200, "DeleteIdentityResponse", "")+ return _xml(200, "DeleteIdentityResponse", "<DeleteIdentityResult/>")def _list_verified_emails(params):@@ -419,7 +419,7 @@ def _set_identity_notification_topic(params):sns_topic = _p(params, "SnsTopic")if identity in _identities:_identities[identity]["NotificationTopics"][notification_type] = sns_topic- return _xml(200, "SetIdentityNotificationTopicResponse", "")+ return _xml(200, "SetIdentityNotificationTopicResponse", "<SetIdentityNotificationTopicResult/>")def _set_identity_feedback_forwarding(params):@@ -427,7 +427,7 @@ def _set_identity_feedback_forwarding(params):enabled = _p(params, "ForwardingEnabled").lower() == "true"if identity in _identities:_identities[identity]["FeedbackForwardingEnabled"] = enabled- return _xml(200, "SetIdentityFeedbackForwardingEnabledResponse", "")+ return _xml(200, "SetIdentityFeedbackForwardingEnabledResponse", "<SetIdentityFeedbackForwardingEnabledResult/>")# ---------------------------------------------------------------------------diff --git a/ministack/services/sns.py b/ministack/services/sns.pyindex f13c3a82..f7dbdaa7 100644--- a/ministack/services/sns.py+++ b/ministack/services/sns.py@@ -31,6 +31,18 @@ logger = logging.getLogger("sns")REGION = os.environ.get("MINISTACK_REGION", "us-east-1")+import re as _re++def _normalize_arn(arn: str) -> str:+ """Normalize an SNS ARN that has an empty account ID.+ Some SDKs (Go v2 with skipRequestingAccountId) construct ARNs with empty+ account like arn:aws:sns:us-east-1::topic-name. Replace the empty account+ with the current request's account ID so the lookup succeeds.+ """+ if arn and _re.match(r"arn:aws:sns:[^:]+::[^:]+", arn):+ return _re.sub(r"(arn:aws:sns:[^:]+)::", rf"\1:{get_account_id()}:", arn)+ return arn+from ministack.core.persistence import load_state, PERSIST_STATE_topics = AccountScopedDict()@@ -120,7 +132,7 @@ def _create_topic(params):"arn": arn,"attributes": {"TopicArn": arn,- "DisplayName": name,+ "DisplayName": "","Owner": get_account_id(),"Policy": default_policy,"SubscriptionsConfirmed": "0",@@ -148,12 +160,20 @@ def _create_topic(params):_topics[arn]["attributes"][key] = vali += 1+ # Store tags from CreateTopic+ i = 1+ while _p(params, f"Tag.member.{i}.Key"):+ key = _p(params, f"Tag.member.{i}.Key")+ val = _p(params, f"Tag.member.{i}.Value")+ _topics[arn]["tags"][key] = val+ i += 1+return _xml(200, "CreateTopicResponse",f"<CreateTopicResult><TopicArn>{arn}</TopicArn></CreateTopicResult>")def _delete_topic(params):- arn = _p(params, "TopicArn")+ arn = _normalize_arn(_p(params, "TopicArn"))topic = _topics.pop(arn, None)if topic:for sub in topic.get("subscriptions", []):@@ -182,7 +202,7 @@ def _list_topics(params):def _get_topic_attributes(params):- arn = _p(params, "TopicArn")+ arn = _normalize_arn(_p(params, "TopicArn"))topic = _topics.get(arn)if not topic:return _error("NotFoundException", f"Topic does not exist: {arn}", 404)@@ -196,7 +216,7 @@ def _get_topic_attributes(params):def _set_topic_attributes(params):- arn = _p(params, "TopicArn")+ arn = _normalize_arn(_p(params, "TopicArn"))topic = _topics.get(arn)if not topic:return _error("NotFoundException", f"Topic does not exist: {arn}", 404)@@ -212,7 +232,7 @@ def _set_topic_attributes(params):# ---------------------------------------------------------------------------def _subscribe(params):- topic_arn = _p(params, "TopicArn")+ topic_arn = _normalize_arn(_p(params, "TopicArn"))protocol = _p(params, "Protocol")endpoint = _p(params, "Endpoint")@@ -274,7 +294,7 @@ def _subscribe(params):def _confirm_subscription(params):- topic_arn = _p(params, "TopicArn")+ topic_arn = _normalize_arn(_p(params, "TopicArn"))token = _p(params, "Token")topic = _topics.get(topic_arn)@@ -340,7 +360,7 @@ def _list_subscriptions(params):def _list_subscriptions_by_topic(params):- topic_arn = _p(params, "TopicArn")+ topic_arn = _normalize_arn(_p(params, "TopicArn"))topic = _topics.get(topic_arn)if not topic:return _error("NotFoundException", f"Topic does not exist: {topic_arn}", 404)@@ -411,7 +431,7 @@ def _set_subscription_attributes(params):# ---------------------------------------------------------------------------def _publish(params):- topic_arn = _p(params, "TopicArn") or _p(params, "TargetArn")+ topic_arn = _normalize_arn(_p(params, "TopicArn") or _p(params, "TargetArn"))phone_number = _p(params, "PhoneNumber")message = _p(params, "Message")subject = _p(params, "Subject")@@ -453,7 +473,7 @@ def _publish(params):def _publish_batch(params):- topic_arn = _p(params, "TopicArn")+ topic_arn = _normalize_arn(_p(params, "TopicArn"))if not topic_arn:return _error("InvalidParameterException", "TopicArn is required", 400)if topic_arn not in _topics:@@ -674,7 +694,7 @@ async def _send_subscription_confirmation(topic_arn: str, sub: dict):# ---------------------------------------------------------------------------def _list_tags_for_resource(params):- arn = _p(params, "ResourceArn")+ arn = _normalize_arn(_p(params, "ResourceArn"))topic = _topics.get(arn)tags_xml = ""if topic:@@ -685,7 +705,7 @@ def _list_tags_for_resource(params):def _tag_resource(params):- arn = _p(params, "ResourceArn")+ arn = _normalize_arn(_p(params, "ResourceArn"))topic = _topics.get(arn)if not topic:return _error("ResourceNotFoundException", "Resource not found", 404)@@ -699,7 +719,7 @@ def _tag_resource(params):def _untag_resource(params):- arn = _p(params, "ResourceArn")+ arn = _normalize_arn(_p(params, "ResourceArn"))topic = _topics.get(arn)if topic:i = 1diff --git a/ministack/services/ssm.py b/ministack/services/ssm.pyindex 8a0dd22b..12709a55 100644--- a/ministack/services/ssm.py+++ b/ministack/services/ssm.py@@ -165,6 +165,9 @@ def _put_parameter(data):_parameter_history[name] = []_parameter_history[name].append(history_entry)+ if data.get("Tags"):+ _tags[arn] = data["Tags"]+logger.info("SSM PutParameter: %s v%s type=%s", name, version, param_type)return json_response({"Version": version, "Tier": record["Tier"]})diff --git a/pyproject.toml b/pyproject.tomlindex 3ddeb983..3dab5456 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "ministack"-version = "1.1.62"+version = "1.2.0"description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"readme = "README.md"license = { file = "LICENSE" }diff --git a/tests/test_ec2.py b/tests/test_ec2.pyindex 3771809b..f390de86 100644--- a/tests/test_ec2.py+++ b/tests/test_ec2.py@@ -36,6 +36,32 @@ def test_ec2_run_describe_terminate_instances(ec2):term = ec2.terminate_instances(InstanceIds=[instance_id])assert term["TerminatingInstances"][0]["CurrentState"]["Name"] == "terminated"+def test_ec2_describe_instance_status(ec2):+ resp = ec2.run_instances(ImageId="ami-00000000", MinCount=1, MaxCount=1, InstanceType="t2.micro")+ iid = resp["Instances"][0]["InstanceId"]++ # Running instance should appear by default+ status = ec2.describe_instance_status(InstanceIds=[iid])+ assert len(status["InstanceStatuses"]) == 1+ s = status["InstanceStatuses"][0]+ assert s["InstanceId"] == iid+ assert s["InstanceState"]["Name"] == "running"+ assert s["SystemStatus"]["Status"] == "ok"+ assert s["InstanceStatus"]["Status"] == "ok"++ # Stopped instance should NOT appear without IncludeAllInstances+ ec2.stop_instances(InstanceIds=[iid])+ status2 = ec2.describe_instance_status(InstanceIds=[iid])+ assert len(status2["InstanceStatuses"]) == 0++ # With IncludeAllInstances=True it should appear+ status3 = ec2.describe_instance_status(InstanceIds=[iid], IncludeAllInstances=True)+ assert len(status3["InstanceStatuses"]) == 1+ assert status3["InstanceStatuses"][0]["InstanceState"]["Name"] == "stopped"++ ec2.terminate_instances(InstanceIds=[iid])++def test_ec2_stop_start_instances(ec2):resp = ec2.run_instances(ImageId="ami-00000000", MinCount=1, MaxCount=1)iid = resp["Instances"][0]["InstanceId"]diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex b50786f9..0a309e85 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -1518,6 +1518,10 @@ def test_lambda_nodejs_esm_mjs_handler(lam):assert body["message"] == "Hello, MiniStack from ESM!"assert body["version"] == "1.0.0"assert body["esm"] is True+ finally:+ lam.delete_function(FunctionName=fname)++def test_lambda_warm_worker_uses_layer(lam):"""Warm worker should extract layers and make their code available to the handler."""# Create a layer with a Python module@@ -1577,6 +1581,24 @@ def test_lambda_nodejs_esm_type_module(lam):z.writestr("index.js", handler_code)z.writestr("package.json", '{"type": "module"}')+ lam.create_function(+ FunctionName=fname,+ Runtime="nodejs20.x",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": buf.getvalue()},+ )+ try:+ resp = lam.invoke(FunctionName=fname, Payload=b"{}")+ assert resp["StatusCode"] == 200+ assert "FunctionError" not in resp, f"Lambda error: {resp['Payload'].read().decode()}"+ payload = json.loads(resp["Payload"].read())+ assert payload["statusCode"] == 200+ assert payload["body"] == "type-module-works"+ finally:+ lam.delete_function(FunctionName=fname)++def test_lambda_warm_worker_nodejs_uses_layer(lam):"""Warm worker should extract Node.js layers and make packages available via require()."""# Create a layer with a Node.js module under nodejs/node_modules/@@ -1610,8 +1632,6 @@ def test_lambda_warm_worker_nodejs_uses_layer(lam):Runtime="nodejs20.x",Role=_LAMBDA_ROLE,Handler="index.handler",- Code={"ZipFile": buf.getvalue()},- )Code={"ZipFile": func_buf.getvalue()},Layers=[layer_arn],)@@ -1621,8 +1641,6 @@ def test_lambda_warm_worker_nodejs_uses_layer(lam):assert resp["StatusCode"] == 200assert "FunctionError" not in resp, f"Lambda error: {resp['Payload'].read().decode()}"payload = json.loads(resp["Payload"].read())- assert payload["statusCode"] == 200- assert payload["body"] == "type-module-works"assert payload["value"] == "from-node-layer"finally:lam.delete_function(FunctionName=fname)diff --git a/tests/test_s3.py b/tests/test_s3.pyindex c335a972..93e41dc8 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -876,6 +876,33 @@ def test_s3_list_object_versions(s3):keys = [v["Key"] for v in versions]assert "v1.txt" in keys and "v2.txt" in keys+def test_s3_list_object_versions_multiple_puts_same_key(s3):+ """Multiple PUTs to the same key with versioning enabled should return all versions."""+ bkt = "s3-ver-multi"+ s3.create_bucket(Bucket=bkt)+ s3.put_bucket_versioning(Bucket=bkt, VersioningConfiguration={"Status": "Enabled"})++ r1 = s3.put_object(Bucket=bkt, Key="doc.txt", Body=b"v1")+ r2 = s3.put_object(Bucket=bkt, Key="doc.txt", Body=b"v2")+ r3 = s3.put_object(Bucket=bkt, Key="doc.txt", Body=b"v3")++ assert r1["VersionId"] != r2["VersionId"]+ assert r2["VersionId"] != r3["VersionId"]++ resp = s3.list_object_versions(Bucket=bkt)+ versions = resp.get("Versions", [])+ assert len(versions) == 3++ version_ids = [v["VersionId"] for v in versions]+ assert r1["VersionId"] in version_ids+ assert r2["VersionId"] in version_ids+ assert r3["VersionId"] in version_ids++ latest = [v for v in versions if v["IsLatest"]]+ assert len(latest) == 1+ assert latest[0]["VersionId"] == r3["VersionId"]++def test_s3_bucket_website(s3):s3.create_bucket(Bucket="s3-web-bkt")s3.put_bucket_website(diff --git a/tests/test_sns.py b/tests/test_sns.pyindex ee49104e..571e70eb 100644--- a/tests/test_sns.py+++ b/tests/test_sns.py@@ -39,7 +39,7 @@ def test_sns_get_topic_attributes(sns):arn = sns.create_topic(Name="intg-sns-getattr")["TopicArn"]resp = sns.get_topic_attributes(TopicArn=arn)assert resp["Attributes"]["TopicArn"] == arn- assert resp["Attributes"]["DisplayName"] == "intg-sns-getattr"+ assert resp["Attributes"]["DisplayName"] == "" # AWS default is empty, not topic namedef test_sns_set_topic_attributes(sns):arn = sns.create_topic(Name="intg-sns-setattr")["TopicArn"]