Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

Fix/audit fixes v1.1.23 (#83)

Nahuel Nucera1a1f459241e2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9b24f840..2050bf43 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,10 +7,32 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
-## [Unreleased]
+## [1.1.24] — 2026-04-03
+
+### Fixed
+- **KMS aliases** — CreateAlias, DeleteAlias, ListAliases, UpdateAlias; `alias/my-key` resolves in Encrypt, Decrypt, Sign, Verify, DescribeKey and all other KMS operations
+- **KMS `REGION` hardcoded** — now reads `MINISTACK_REGION` env var like all other services
+- **S3 hardcoded `us-east-1`** — bucket region header, location constraint, and event notifications now use `MINISTACK_REGION`
+- **Router `extract_region` fallback** — now uses `MINISTACK_REGION` instead of hardcoded `us-east-1`
+- **EC2/RDS XML escaping** — user-controlled values (tags, descriptions) now escaped with `xml.sax.saxutils.escape()`
+- **SQS thread safety** — added `_queues_lock` for ESM poller access
+- **EC2 terminated instances cleaned up** — removed from memory after 60s
+- **Step Functions execution cleanup** — cleaned up when parent state machine is deleted
+- **Lambda ESM poller idle optimization** — polls every 5s when no ESMs configured
+- **DynamoDB `REGION` variable ordering** — moved before `_emit_stream_event`
+- **README: 55+ undocumented operations** — updated all service tables
+- **README: `SFN_MOCK_CONFIG`** — added to Configuration table
+- **README: KMS in Terraform endpoints**
+
+### Tests
+- 876 tests total, all passing
+
+---
+
+## [1.1.23] — 2026-04-03
### Added
-- **KMS service** — CreateKey (RSA_2048, RSA_4096, SYMMETRIC_DEFAULT), ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateDataKey, GenerateDataKeyWithoutPlaintext. In-memory key storage with RSA signing via the `cryptography` package (optional dependency, guarded import). Supports JWT signing flows and S3 SSE-KMS encryption patterns.
+- **KMS service** — CreateKey (RSA_2048, RSA_4096, SYMMETRIC_DEFAULT), ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateDataKey, GenerateDataKeyWithoutPlaintext. In-memory key storage with RSA signing via the `cryptography` package (optional dependency, guarded import). Supports JWT signing flows and S3 SSE-KMS encryption patterns. Contributed by @Jolley71717
---
diff --git a/README.md b/README.md
index 243c7670..efec2c8c 100644
--- a/README.md
+++ b/README.md
@@ -202,21 +202,21 @@ subnet = ec2.create_subnet(
| **SQS** | CreateQueue, DeleteQueue, ListQueues, GetQueueUrl, GetQueueAttributes, SetQueueAttributes, PurgeQueue, SendMessage, ReceiveMessage, DeleteMessage, ChangeMessageVisibility, ChangeMessageVisibilityBatch, SendMessageBatch, DeleteMessageBatch, TagQueue, UntagQueue, ListQueueTags | Both Query API and JSON protocol; FIFO queues with deduplication; DLQ support |
| **SNS** | CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes, Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, GetSubscriptionAttributes, SetSubscriptionAttributes, ConfirmSubscription, Publish, PublishBatch, TagResource, UntagResource, ListTagsForResource, CreatePlatformApplication, CreatePlatformEndpoint | SNS→SQS fanout delivery; SNS→Lambda fanout (synchronous invocation) |
| **DynamoDB** | CreateTable, UpdateTable, DeleteTable, DescribeTable, ListTables, PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem, TransactWriteItems, TransactGetItems, DescribeTimeToLive, UpdateTimeToLive, DescribeContinuousBackups, UpdateContinuousBackups, DescribeEndpoints, TagResource, UntagResource, ListTagsOfResource | TTL enforced via thread-safe background reaper (60s cadence); DynamoDB Streams — `StreamSpecification` emits INSERT/MODIFY/REMOVE records on all write operations, respects `StreamViewType` |
-| **Lambda** | CreateFunction, DeleteFunction, GetFunction, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration, AddPermission, RemovePermission, ListVersionsByFunction, PublishVersion, TagResource, UntagResource, ListTags, CreateEventSourceMapping, DeleteEventSourceMapping, GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping, CreateFunctionUrlConfig, GetFunctionUrlConfig, UpdateFunctionUrlConfig, DeleteFunctionUrlConfig, ListFunctionUrlConfigs, PublishLayerVersion, GetLayerVersion, ListLayerVersions, DeleteLayerVersion, ListLayers | Python and Node.js runtimes execute with warm worker pool; `Publish=True` creates immutable numbered versions; Code via `ZipFile` or `S3Bucket`/`S3Key`; SQS, Kinesis, and DynamoDB Streams event source mappings; Function URL CRUD; Lambda Layers CRUD |
+| **Lambda** | CreateFunction, DeleteFunction, GetFunction, GetFunctionConfiguration, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration, AddPermission, RemovePermission, GetPolicy, ListVersionsByFunction, PublishVersion, CreateAlias, GetAlias, UpdateAlias, DeleteAlias, ListAliases, TagResource, UntagResource, ListTags, CreateEventSourceMapping, DeleteEventSourceMapping, GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping, CreateFunctionUrlConfig, GetFunctionUrlConfig, UpdateFunctionUrlConfig, DeleteFunctionUrlConfig, ListFunctionUrlConfigs, PutFunctionConcurrency, GetFunctionConcurrency, DeleteFunctionConcurrency, PutFunctionEventInvokeConfig, GetFunctionEventInvokeConfig, DeleteFunctionEventInvokeConfig, PublishLayerVersion, GetLayerVersion, GetLayerVersionByArn, ListLayerVersions, DeleteLayerVersion, ListLayers, AddLayerVersionPermission, RemoveLayerVersionPermission, GetLayerVersionPolicy | Python and Node.js runtimes execute with warm worker pool; `Publish=True` creates immutable numbered versions; Code via `ZipFile` or `S3Bucket`/`S3Key`; SQS, Kinesis, and DynamoDB Streams event source mappings; Function URL CRUD; Lambda Layers CRUD; Aliases; Concurrency; EventInvokeConfig |
| **IAM** | CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles, DeleteRole, CreatePolicy, GetPolicy, DeletePolicy, AttachRolePolicy, DetachRolePolicy, PutRolePolicy, GetRolePolicy, DeleteRolePolicy, ListRolePolicies, ListAttachedRolePolicies, CreateAccessKey, ListAccessKeys, DeleteAccessKey, CreateInstanceProfile, GetInstanceProfile, DeleteInstanceProfile, AddRoleToInstanceProfile, RemoveRoleFromInstanceProfile, ListInstanceProfiles, CreateGroup, GetGroup, AddUserToGroup, RemoveUserFromGroup, CreateServiceLinkedRole, CreateOpenIDConnectProvider, TagRole, UntagRole, TagUser, UntagUser, TagPolicy, UntagPolicy | |
| **STS** | GetCallerIdentity, AssumeRole, GetSessionToken, AssumeRoleWithWebIdentity | |
-| **SecretsManager** | CreateSecret, GetSecretValue, ListSecrets, DeleteSecret, UpdateSecret, DescribeSecret, PutSecretValue, RestoreSecret, RotateSecret, GetRandomPassword, ListSecretVersionIds, TagResource, UntagResource, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy, ValidateResourcePolicy | |
-| **CloudWatch Logs** | CreateLogGroup, DeleteLogGroup, DescribeLogGroups, CreateLogStream, DeleteLogStream, DescribeLogStreams, PutLogEvents, GetLogEvents, FilterLogEvents, PutRetentionPolicy, DeleteRetentionPolicy, PutSubscriptionFilter, DeleteSubscriptionFilter, DescribeSubscriptionFilters, PutMetricFilter, DeleteMetricFilter, DescribeMetricFilters, TagLogGroup, UntagLogGroup, ListTagsLogGroup, TagResource, UntagResource, ListTagsForResource, StartQuery, GetQueryResults, StopQuery, PutDestination, DeleteDestination, DescribeDestinations | `FilterLogEvents` supports `*`/`?` globs, multi-term AND, `-term` exclusion |
+| **SecretsManager** | CreateSecret, GetSecretValue, ListSecrets, DeleteSecret, UpdateSecret, DescribeSecret, PutSecretValue, RestoreSecret, RotateSecret, GetRandomPassword, ListSecretVersionIds, ReplicateSecretToRegions, TagResource, UntagResource, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy, ValidateResourcePolicy | |
+| **CloudWatch Logs** | CreateLogGroup, DeleteLogGroup, DescribeLogGroups, CreateLogStream, DeleteLogStream, DescribeLogStreams, PutLogEvents, GetLogEvents, FilterLogEvents, PutRetentionPolicy, DeleteRetentionPolicy, PutSubscriptionFilter, DeleteSubscriptionFilter, DescribeSubscriptionFilters, PutMetricFilter, DeleteMetricFilter, DescribeMetricFilters, TagLogGroup, UntagLogGroup, ListTagsLogGroup, TagResource, UntagResource, ListTagsForResource, StartQuery, GetQueryResults, StopQuery, PutDestination, DeleteDestination, DescribeDestinations, PutDestinationPolicy | `FilterLogEvents` supports `*`/`?` globs, multi-term AND, `-term` exclusion |
### Extended Services
| Service | Operations | Notes |
|---------|-----------|-------|
| **SSM Parameter Store** | PutParameter, GetParameter, GetParameters, GetParametersByPath, DeleteParameter, DeleteParameters, DescribeParameters, GetParameterHistory, LabelParameterVersion, AddTagsToResource, RemoveTagsFromResource, ListTagsForResource | Supports String, SecureString, StringList |
-| **EventBridge** | CreateEventBus, DeleteEventBus, ListEventBuses, PutRule, DeleteRule, ListRules, DescribeRule, EnableRule, DisableRule, PutTargets, RemoveTargets, ListTargetsByRule, PutEvents, TagResource, UntagResource, ListTagsForResource, CreateArchive, DeleteArchive, DescribeArchive, ListArchives, PutPermission, RemovePermission, CreateConnection, DescribeConnection, DeleteConnection, ListConnections, CreateApiDestination, DescribeApiDestination, DeleteApiDestination, ListApiDestinations | Lambda target dispatch on PutEvents |
-| **Kinesis** | CreateStream, DeleteStream, DescribeStream, ListStreams, ListShards, PutRecord, PutRecords, GetShardIterator, GetRecords, MergeShards, SplitShard, UpdateShardCount, StartStreamEncryption, StopStreamEncryption, EnableEnhancedMonitoring, DisableEnhancedMonitoring, RegisterStreamConsumer, DeregisterStreamConsumer, ListStreamConsumers, DescribeStreamConsumer, AddTagsToStream, RemoveTagsFromStream, ListTagsForStream | Partition key → shard routing; AWS limits enforced (1 MB/record, 500 records/batch, 5 MB payload, 256-char partition key) |
+| **EventBridge** | CreateEventBus, DeleteEventBus, ListEventBuses, DescribeEventBus, PutRule, DeleteRule, ListRules, DescribeRule, EnableRule, DisableRule, PutTargets, RemoveTargets, ListTargetsByRule, PutEvents, TagResource, UntagResource, ListTagsForResource, CreateArchive, DeleteArchive, DescribeArchive, ListArchives, PutPermission, RemovePermission, CreateConnection, DescribeConnection, DeleteConnection, UpdateConnection, ListConnections, CreateApiDestination, DescribeApiDestination, DeleteApiDestination, UpdateApiDestination, ListApiDestinations | Lambda target dispatch on PutEvents; S3 EventBridge notifications |
+| **Kinesis** | CreateStream, DeleteStream, DescribeStream, DescribeStreamSummary, ListStreams, ListShards, PutRecord, PutRecords, GetShardIterator, GetRecords, IncreaseStreamRetentionPeriod, DecreaseStreamRetentionPeriod, MergeShards, SplitShard, UpdateShardCount, StartStreamEncryption, StopStreamEncryption, EnableEnhancedMonitoring, DisableEnhancedMonitoring, RegisterStreamConsumer, DeregisterStreamConsumer, ListStreamConsumers, DescribeStreamConsumer, AddTagsToStream, RemoveTagsFromStream, ListTagsForStream | Partition key → shard routing; AWS limits enforced (1 MB/record, 500 records/batch, 5 MB payload, 256-char partition key) |
| **CloudWatch Metrics** | PutMetricData, GetMetricStatistics, GetMetricData, ListMetrics, PutMetricAlarm, PutCompositeAlarm, DescribeAlarms, DescribeAlarmsForMetric, DescribeAlarmHistory, DeleteAlarms, SetAlarmState, EnableAlarmActions, DisableAlarmActions, TagResource, UntagResource, ListTagsForResource, PutDashboard, GetDashboard, DeleteDashboards, ListDashboards | CBOR and JSON protocol |
-| **SES** | SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail, VerifyEmailIdentity, VerifyEmailAddress, VerifyDomainIdentity, VerifyDomainDkim, ListIdentities, GetIdentityVerificationAttributes, GetIdentityDkimAttributes, DeleteIdentity, GetSendQuota, GetSendStatistics, CreateConfigurationSet, DeleteConfigurationSet, DescribeConfigurationSet, ListConfigurationSets, CreateTemplate, GetTemplate, UpdateTemplate, DeleteTemplate, ListTemplates | Emails stored in-memory, not sent |
+| **SES** | SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail, VerifyEmailIdentity, VerifyEmailAddress, VerifyDomainIdentity, VerifyDomainDkim, ListIdentities, ListVerifiedEmailAddresses, GetIdentityVerificationAttributes, GetIdentityDkimAttributes, DeleteIdentity, GetSendQuota, GetSendStatistics, SetIdentityNotificationTopic, SetIdentityFeedbackForwardingEnabled, CreateConfigurationSet, DeleteConfigurationSet, DescribeConfigurationSet, ListConfigurationSets, CreateTemplate, GetTemplate, UpdateTemplate, DeleteTemplate, ListTemplates | Emails stored in-memory, not sent |
| **SES v2** | SendEmail, CreateEmailIdentity, GetEmailIdentity, DeleteEmailIdentity, ListEmailIdentities, CreateConfigurationSet, GetConfigurationSet, DeleteConfigurationSet, ListConfigurationSets, GetAccount, PutAccountSuppressionAttributes, ListSuppressedDestinations | REST API (`/v2/email/`); identities auto-verified; emails stored in-memory, not sent |
| **ACM** | RequestCertificate, DescribeCertificate, ListCertificates, DeleteCertificate, GetCertificate, ImportCertificate, AddTagsToCertificate, RemoveTagsFromCertificate, ListTagsForCertificate, UpdateCertificateOptions, RenewCertificate, ResendValidationEmail | Certificates auto-issued; DNS validation records generated; supports SANs |
| **WAF v2** | CreateWebACL, GetWebACL, UpdateWebACL, DeleteWebACL, ListWebACLs, AssociateWebACL, DisassociateWebACL, GetWebACLForResource, ListResourcesForWebACL, CreateIPSet, GetIPSet, UpdateIPSet, DeleteIPSet, ListIPSets, CreateRuleGroup, GetRuleGroup, UpdateRuleGroup, DeleteRuleGroup, ListRuleGroups, TagResource, UntagResource, ListTagsForResource, CheckCapacity, DescribeManagedRuleGroup | LockToken enforced on Update/Delete; resource associations tracked |
@@ -225,7 +225,7 @@ subnet = ec2.create_subnet(
| **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost`; resource tree with `{param}` and `{proxy+}` path matching; JSON Patch for all PATCH operations; state persistence |
| **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, RegisterTargets, DeregisterTargets, DescribeTargetHealth, AddTags, RemoveTags, DescribeTags | Control plane + data plane; ALB→Lambda live traffic routing; `path-pattern`, `host-header`, `http-method`, `query-string`, `http-header` rule conditions; `forward`, `redirect`, `fixed-response` actions; data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix |
-| **KMS** | CreateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateDataKey, GenerateDataKeyWithoutPlaintext | RSA (2048/4096) and symmetric keys; PKCS1v15 and PSS signing; envelope encryption; requires `cryptography` package (optional) |
+| **KMS** | CreateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateDataKey, GenerateDataKeyWithoutPlaintext, CreateAlias, DeleteAlias, ListAliases, UpdateAlias | RSA (2048/4096) and symmetric keys; PKCS1v15 and PSS signing; envelope encryption; alias resolution (`alias/my-key`); requires `cryptography` package (optional) |
### CloudFormation
@@ -265,10 +265,10 @@ Unsupported resource types fail with `CREATE_FAILED` (or `ROLLBACK_COMPLETE` if
| Service | Operations | Notes |
|---------|-----------|-------|
-| **ECS** | CreateCluster, UpdateCluster, DeleteCluster, DescribeClusters, ListClusters, RegisterTaskDefinition, DeregisterTaskDefinition, DescribeTaskDefinition, ListTaskDefinitions, CreateService, DeleteService, DescribeServices, UpdateService, ListServices, RunTask, StopTask, DescribeTasks, ListTasks, CreateCapacityProvider, DeleteCapacityProvider, DescribeCapacityProviders, PutClusterCapacityProviders, TagResource, UntagResource, ListTagsForResource | `RunTask` starts real Docker containers via Docker socket |
-| **RDS** | CreateDBInstance, DeleteDBInstance, DescribeDBInstances, StartDBInstance, StopDBInstance, RebootDBInstance, ModifyDBInstance, CreateDBCluster, DeleteDBCluster, DescribeDBClusters, StartDBCluster, StopDBCluster, CreateDBSubnetGroup, DescribeDBSubnetGroups, ModifyDBSubnetGroup, DeleteDBSubnetGroup, CreateDBParameterGroup, DescribeDBParameterGroups, ModifyDBParameterGroup, DeleteDBParameterGroup, DescribeDBParameters, CreateDBClusterParameterGroup, DescribeDBEngineVersions, DescribeOrderableDBInstanceOptions, CreateDBSnapshot, DeleteDBSnapshot, DescribeDBSnapshots, CreateDBClusterSnapshot, DeleteDBClusterSnapshot, DescribeDBClusterSnapshots, CreateDBInstanceReadReplica, RestoreDBInstanceFromDBSnapshot, CreateOptionGroup, DescribeOptionGroups, AddTagsToResource, RemoveTagsFromResource, ListTagsForResource | `CreateDBInstance` spins up real Postgres/MySQL Docker container, returns actual `host:port` endpoint |
-| **ElastiCache** | CreateCacheCluster, DeleteCacheCluster, DescribeCacheClusters, ModifyCacheCluster, RebootCacheCluster, CreateReplicationGroup, DeleteReplicationGroup, DescribeReplicationGroups, ModifyReplicationGroup, IncreaseReplicaCount, DecreaseReplicaCount, CreateCacheSubnetGroup, DescribeCacheSubnetGroups, ModifyCacheSubnetGroup, DeleteCacheSubnetGroup, CreateCacheParameterGroup, DescribeCacheParameterGroups, ModifyCacheParameterGroup, ResetCacheParameterGroup, DeleteCacheParameterGroup, DescribeCacheParameters, DescribeCacheEngineVersions, CreateUser, DescribeUsers, DeleteUser, ModifyUser, CreateUserGroup, DescribeUserGroups, DeleteUserGroup, ModifyUserGroup, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, DescribeEvents | `CreateCacheCluster` spins up real Redis/Memcached Docker container |
-| **Glue** | CreateDatabase, DeleteDatabase, GetDatabase, GetDatabases, CreateTable, DeleteTable, GetTable, GetTables, UpdateTable, BatchDeleteTable, CreatePartition, GetPartitions, BatchCreatePartition, BatchGetPartition, CreatePartitionIndex, GetPartitionIndexes, CreateConnection, GetConnections, CreateCrawler, UpdateCrawler, GetCrawler, GetCrawlerMetrics, StartCrawler, CreateJob, GetJob, GetJobs, StartJobRun, GetJobRun, GetJobRuns, CreateTrigger, GetTrigger, DeleteTrigger, UpdateTrigger, StartTrigger, StopTrigger, ListTriggers, GetTriggers, CreateWorkflow, GetWorkflow, DeleteWorkflow, UpdateWorkflow, StartWorkflowRun, CreateSecurityConfiguration, GetSecurityConfiguration, GetSecurityConfigurations, DeleteSecurityConfiguration, CreateClassifier, GetClassifier, GetClassifiers, DeleteClassifier, TagResource, UntagResource, GetTags | Python shell jobs actually execute via subprocess |
+| **ECS** | CreateCluster, DeleteCluster, DescribeClusters, ListClusters, UpdateCluster, UpdateClusterSettings, RegisterTaskDefinition, DeregisterTaskDefinition, DescribeTaskDefinition, ListTaskDefinitions, CreateService, DeleteService, DescribeServices, UpdateService, ListServices, RunTask, StopTask, DescribeTasks, ListTasks, TagResource, UntagResource, ListTagsForResource, ExecuteCommand, ListAccountSettings, PutAccountSetting, CreateCapacityProvider, DeleteCapacityProvider, DescribeCapacityProviders, PutClusterCapacityProviders | `RunTask` starts real Docker containers via Docker socket |
+| **RDS** | CreateDBInstance, DeleteDBInstance, DescribeDBInstances, ModifyDBInstance, StartDBInstance, StopDBInstance, RebootDBInstance, CreateDBInstanceReadReplica, RestoreDBInstanceFromDBSnapshot, CreateDBCluster, DeleteDBCluster, DescribeDBClusters, ModifyDBCluster, StartDBCluster, StopDBCluster, CreateDBSnapshot, DeleteDBSnapshot, DescribeDBSnapshots, CreateDBClusterSnapshot, DescribeDBClusterSnapshots, DeleteDBClusterSnapshot, CreateDBSubnetGroup, DeleteDBSubnetGroup, DescribeDBSubnetGroups, ModifyDBSubnetGroup, CreateDBParameterGroup, DeleteDBParameterGroup, DescribeDBParameterGroups, DescribeDBParameters, ModifyDBParameterGroup, CreateDBClusterParameterGroup, DescribeDBClusterParameterGroups, DeleteDBClusterParameterGroup, DescribeDBClusterParameters, ModifyDBClusterParameterGroup, CreateOptionGroup, DeleteOptionGroup, DescribeOptionGroups, DescribeOptionGroupOptions, ListTagsForResource, AddTagsToResource, RemoveTagsFromResource, DescribeDBEngineVersions, DescribeOrderableDBInstanceOptions | `CreateDBInstance` spins up real Postgres/MySQL Docker container, returns actual `host:port` endpoint |
+| **ElastiCache** | CreateCacheCluster, DeleteCacheCluster, DescribeCacheClusters, ModifyCacheCluster, RebootCacheCluster, CreateReplicationGroup, DeleteReplicationGroup, DescribeReplicationGroups, ModifyReplicationGroup, IncreaseReplicaCount, DecreaseReplicaCount, CreateCacheSubnetGroup, DescribeCacheSubnetGroups, ModifyCacheSubnetGroup, DeleteCacheSubnetGroup, CreateCacheParameterGroup, DescribeCacheParameterGroups, ModifyCacheParameterGroup, ResetCacheParameterGroup, DeleteCacheParameterGroup, DescribeCacheParameters, DescribeCacheEngineVersions, CreateUser, DescribeUsers, DeleteUser, ModifyUser, CreateUserGroup, DescribeUserGroups, DeleteUserGroup, ModifyUserGroup, ListTagsForResource, AddTagsToResource, RemoveTagsFromResource, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, DescribeEvents | `CreateCacheCluster` spins up real Redis/Memcached Docker container |
+| **Glue** | CreateDatabase, DeleteDatabase, GetDatabase, GetDatabases, UpdateDatabase, CreateTable, DeleteTable, GetTable, GetTables, UpdateTable, BatchDeleteTable, CreatePartition, DeletePartition, GetPartition, GetPartitions, BatchCreatePartition, BatchGetPartition, CreatePartitionIndex, GetPartitionIndexes, CreateConnection, DeleteConnection, GetConnection, GetConnections, CreateCrawler, DeleteCrawler, GetCrawler, GetCrawlers, UpdateCrawler, StartCrawler, StopCrawler, GetCrawlerMetrics, CreateJob, DeleteJob, GetJob, GetJobs, UpdateJob, StartJobRun, GetJobRun, GetJobRuns, BatchStopJobRun, CreateTrigger, GetTrigger, DeleteTrigger, UpdateTrigger, StartTrigger, StopTrigger, ListTriggers, BatchGetTriggers, GetTriggers, CreateWorkflow, GetWorkflow, DeleteWorkflow, UpdateWorkflow, StartWorkflowRun, CreateSecurityConfiguration, DeleteSecurityConfiguration, GetSecurityConfiguration, GetSecurityConfigurations, CreateClassifier, GetClassifier, GetClassifiers, DeleteClassifier, TagResource, UntagResource, GetTags | Python shell jobs actually execute via subprocess |
| **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 |
@@ -422,6 +422,7 @@ ecs.stop_task(cluster="dev", task=task_arn)
| `PERSIST_STATE` | `0` | Set `1` to persist service state across restarts |
| `STATE_DIR` | `/tmp/ministack-state` | Directory for persisted state files |
| `LAMBDA_EXECUTOR` | `local` | Lambda execution mode: `local` (subprocess) or `docker` (container) |
+| `SFN_MOCK_CONFIG` | _(unset)_ | Path to JSON file for Step Functions mock testing; compatible with AWS SFN Local format. Also accepts `LOCALSTACK_SFN_MOCK_CONFIG` |
| `ATHENA_ENGINE` | `auto` | SQL engine for Athena: `auto`, `duckdb`, `mock` |
### Athena SQL Engines
@@ -592,6 +593,7 @@ provider "aws" {
glue = "http://localhost:4566"
iam = "http://localhost:4566"
kinesis = "http://localhost:4566"
+ kms = "http://localhost:4566"
lambda = "http://localhost:4566"
logs = "http://localhost:4566"
rds = "http://localhost:4566"
diff --git a/ministack/core/router.py b/ministack/core/router.py
index f8dc03e9..2686a08d 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -8,6 +8,7 @@ Routes incoming requests to the correct service handler based on:
"""
import logging
+import os
import re
logger = logging.getLogger("ministack")
@@ -429,7 +430,7 @@ def extract_region(headers: dict) -> str:
match = re.search(r"Credential=[^/]+/[^/]+/([^/]+)/", auth)
if match:
return match.group(1)
- return "us-east-1"
+ return os.environ.get("MINISTACK_REGION", "us-east-1")
def extract_account_id(headers: dict) -> str:
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index 5d8b38ab..7c249625 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -28,6 +28,9 @@ from ministack.core.responses import (
logger = logging.getLogger("dynamodb")
+ACCOUNT_ID = "000000000000"
+REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+
_tables: dict = {}
_tags: dict = {}
_ttl_settings: dict = {}
@@ -132,9 +135,6 @@ def _ttl_reaper():
threading.Thread(target=_ttl_reaper, daemon=True, name="dynamodb-ttl-reaper").start()
-REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
-ACCOUNT_ID = "000000000000"
-
async def handle_request(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:
target = headers.get("x-amz-target", "")
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index 41688d03..73610d0d 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -48,6 +48,7 @@ import random
import string
import time
from urllib.parse import parse_qs
+from xml.sax.saxutils import escape as _esc
from ministack.core.responses import new_uuid
@@ -234,6 +235,13 @@ def _describe_instances(p):
filter_ids = _parse_member_list(p, "InstanceId")
filters = _parse_filters(p)
+ # Clean up instances terminated more than 60s ago (AWS removes after ~1 hour)
+ stale = [k for k, v in _instances.items()
+ if v["State"]["Name"] == "terminated"
+ and time.time() - v.get("_terminated_at", 0) > 60]
+ for k in stale:
+ _instances.pop(k, None)
+
results = []
for inst in _instances.values():
if filter_ids and inst["InstanceId"] not in filter_ids:
@@ -262,6 +270,7 @@ def _terminate_instances(p):
if inst:
prev = inst["State"].copy()
inst["State"] = {"Code": 48, "Name": "terminated"}
+ inst["_terminated_at"] = time.time()
items += f"""<item>
<instanceId>{iid}</instanceId>
<previousState><code>{prev['Code']}</code><name>{prev['Name']}</name></previousState>
@@ -1034,8 +1043,8 @@ def _describe_tags(p):
items += f"""<item>
<resourceId>{rid}</resourceId>
<resourceType>{resource_type}</resourceType>
- <key>{tag['Key']}</key>
- <value>{tag['Value']}</value>
+ <key>{_esc(tag['Key'])}</key>
+ <value>{_esc(tag['Value'])}</value>
</item>"""
return _xml(200, "DescribeTagsResponse", f"<tagSet>{items}</tagSet>")
@@ -1330,7 +1339,7 @@ def _snapshot_inner_xml(snap):
<progress>{snap['Progress']}</progress>
<ownerId>{snap['OwnerId']}</ownerId>
<volumeSize>{snap['VolumeSize']}</volumeSize>
- <description>{snap['Description']}</description>
+ <description>{_esc(snap['Description'])}</description>
<encrypted>{'true' if snap['Encrypted'] else 'false'}</encrypted>
<storageTier>{snap['StorageTier']}</storageTier>
<tagSet/>"""
@@ -1346,7 +1355,7 @@ def _instance_xml(inst):
for sg in inst.get("SecurityGroups", [])
)
tags = "".join(
- f"<item><key>{t['Key']}</key><value>{t['Value']}</value></item>"
+ f"<item><key>{_esc(t['Key'])}</key><value>{_esc(t['Value'])}</value></item>"
for t in _tags.get(inst["InstanceId"], [])
)
return f"""<item>
diff --git a/ministack/services/kms.py b/ministack/services/kms.py
index 42331263..eb39dbc7 100644
--- a/ministack/services/kms.py
+++ b/ministack/services/kms.py
@@ -32,7 +32,7 @@ except ImportError:
)
ACCOUNT_ID = "000000000000"
-REGION = "us-east-1"
+REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
_keys: dict = {}
# key_id -> {
@@ -42,6 +42,7 @@ _keys: dict = {}
# _public_key_der (bytes, RSA only),
# _symmetric_key (bytes, SYMMETRIC_DEFAULT only),
# }
+_aliases: dict = {} # alias_name -> key_id (e.g. "alias/my-key" -> "uuid")
def _arn(key_id):
@@ -69,11 +70,19 @@ def _key_metadata(rec):
def _resolve_key(key_id_or_arn):
if not key_id_or_arn:
return None
+ # Direct key ID lookup
if key_id_or_arn in _keys:
return _keys[key_id_or_arn]
+ # ARN lookup
for rec in _keys.values():
if rec["Arn"] == key_id_or_arn:
return rec
+ # Alias lookup: "alias/my-key" or "arn:aws:kms:...:alias/my-key"
+ alias_name = key_id_or_arn
+ if ":alias/" in alias_name:
+ alias_name = "alias/" + alias_name.split(":alias/")[-1]
+ if alias_name in _aliases:
+ return _keys.get(_aliases[alias_name])
return None
@@ -540,6 +549,62 @@ def _expand_key(key_bytes, length):
return result[:length]
+# ---- Alias operations ----
+
+
+def _create_alias(data):
+ alias_name = data.get("AliasName", "")
+ target_key_id = data.get("TargetKeyId", "")
+ if not alias_name or not alias_name.startswith("alias/"):
+ return error_response_json("ValidationException", "AliasName must start with alias/", 400)
+ if not target_key_id:
+ return error_response_json("ValidationException", "TargetKeyId is required", 400)
+ rec = _resolve_key(target_key_id)
+ if not rec:
+ return error_response_json("NotFoundException", f"Key {target_key_id} not found", 400)
+ if alias_name in _aliases:
+ return error_response_json("AlreadyExistsException", f"Alias {alias_name} already exists", 400)
+ _aliases[alias_name] = rec["KeyId"]
+ logger.info("Created alias %s -> %s", alias_name, rec["KeyId"])
+ return json_response({})
+
+
+def _delete_alias(data):
+ alias_name = data.get("AliasName", "")
+ if alias_name not in _aliases:
+ return error_response_json("NotFoundException", f"Alias {alias_name} not found", 400)
+ del _aliases[alias_name]
+ return json_response({})
+
+
+def _list_aliases(data):
+ key_id = data.get("KeyId")
+ items = []
+ for alias_name, target_id in _aliases.items():
+ if key_id and target_id != key_id:
+ rec = _resolve_key(key_id)
+ if not rec or rec["KeyId"] != target_id:
+ continue
+ items.append({
+ "AliasName": alias_name,
+ "AliasArn": f"arn:aws:kms:{REGION}:{ACCOUNT_ID}:{alias_name}",
+ "TargetKeyId": target_id,
+ })
+ return json_response({"Aliases": items, "Truncated": False})
+
+
+def _update_alias(data):
+ alias_name = data.get("AliasName", "")
+ target_key_id = data.get("TargetKeyId", "")
+ if alias_name not in _aliases:
+ return error_response_json("NotFoundException", f"Alias {alias_name} not found", 400)
+ rec = _resolve_key(target_key_id)
+ if not rec:
+ return error_response_json("NotFoundException", f"Key {target_key_id} not found", 400)
+ _aliases[alias_name] = rec["KeyId"]
+ return json_response({})
+
+
# ---- Request handler ----
async def handle_request(method, path, headers, body, query_params):
@@ -562,6 +627,10 @@ async def handle_request(method, path, headers, body, query_params):
"Decrypt": _decrypt,
"GenerateDataKey": _generate_data_key,
"GenerateDataKeyWithoutPlaintext": _generate_data_key_without_plaintext,
+ "CreateAlias": _create_alias,
+ "DeleteAlias": _delete_alias,
+ "ListAliases": _list_aliases,
+ "UpdateAlias": _update_alias,
}
handler = handlers.get(action)
@@ -575,3 +644,4 @@ async def handle_request(method, path, headers, body, query_params):
def reset():
_keys.clear()
+ _aliases.clear()
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index c11c9dd5..011588f8 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -2244,7 +2244,7 @@ def _poll_loop():
_poll_dynamodb_streams()
except Exception as e:
logger.error("ESM DynamoDB streams poller error: %s", e)
- time.sleep(1)
+ time.sleep(1 if _esms else 5)
def _poll_sqs():
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index 3f77be25..ee51bba1 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -26,6 +26,7 @@ import logging
import os
import time
from urllib.parse import parse_qs
+from xml.sax.saxutils import escape as _esc
from ministack.core.responses import new_uuid
@@ -854,7 +855,7 @@ def _create_param_group(p):
f"""<CreateDBParameterGroupResult><DBParameterGroup>
<DBParameterGroupName>{name}</DBParameterGroupName>
<DBParameterGroupFamily>{family}</DBParameterGroupFamily>
- <Description>{desc}</Description>
+ <Description>{_esc(desc)}</Description>
<DBParameterGroupArn>{arn}</DBParameterGroupArn>
</DBParameterGroup></CreateDBParameterGroupResult>""")
@@ -881,7 +882,7 @@ def _describe_param_groups(p):
members = "".join(f"""<DBParameterGroup>
<DBParameterGroupName>{g['DBParameterGroupName']}</DBParameterGroupName>
<DBParameterGroupFamily>{g['DBParameterGroupFamily']}</DBParameterGroupFamily>
- <Description>{g['Description']}</Description>
+ <Description>{_esc(g['Description'])}</Description>
<DBParameterGroupArn>{g.get('DBParameterGroupArn','')}</DBParameterGroupArn>
</DBParameterGroup>""" for g in groups)
return _xml(200, "DescribeDBParameterGroupsResponse",
@@ -906,7 +907,7 @@ def _describe_db_parameters(p):
params_xml += f"""<Parameter>
<ParameterName>{pname}</ParameterName>
<ParameterValue>{value}</ParameterValue>
- <Description>{param.get('description', '')}</Description>
+ <Description>{_esc(param.get('description', ''))}</Description>
<Source>{source}</Source>
<ApplyType>{param.get('apply_type', 'dynamic')}</ApplyType>
<DataType>{param.get('data_type', 'string')}</DataType>
@@ -968,7 +969,7 @@ def _create_db_cluster_param_group(p):
f"""<CreateDBClusterParameterGroupResult><DBClusterParameterGroup>
<DBClusterParameterGroupName>{name}</DBClusterParameterGroupName>
<DBParameterGroupFamily>{family}</DBParameterGroupFamily>
- <Description>{desc}</Description>
+ <Description>{_esc(desc)}</Description>
<DBClusterParameterGroupArn>{arn}</DBClusterParameterGroupArn>
</DBClusterParameterGroup></CreateDBClusterParameterGroupResult>""")
@@ -987,7 +988,7 @@ def _describe_db_cluster_param_groups(p):
members = "".join(f"""<DBClusterParameterGroup>
<DBClusterParameterGroupName>{g['DBClusterParameterGroupName']}</DBClusterParameterGroupName>
<DBParameterGroupFamily>{g['DBParameterGroupFamily']}</DBParameterGroupFamily>
- <Description>{g['Description']}</Description>
+ <Description>{_esc(g['Description'])}</Description>
<DBClusterParameterGroupArn>{g.get('DBClusterParameterGroupArn','')}</DBClusterParameterGroupArn>
</DBClusterParameterGroup>""" for g in groups)
return _xml(200, "DescribeDBClusterParameterGroupsResponse",
@@ -1291,7 +1292,7 @@ def _list_tags(p):
"<ListTagsForResourceResult><TagList/></ListTagsForResourceResult>")
tag_list = _tags.get(arn, [])
- members = "".join(f"<Tag><Key>{t['Key']}</Key><Value>{t['Value']}</Value></Tag>" for t in tag_list)
+ members = "".join(f"<Tag><Key>{_esc(t['Key'])}</Key><Value>{_esc(t['Value'])}</Value></Tag>" for t in tag_list)
return _xml(200, "ListTagsForResourceResponse",
f"<ListTagsForResourceResult><TagList>{members}</TagList></ListTagsForResourceResult>")
@@ -1450,7 +1451,7 @@ def _instance_xml(i):
tag_xml = ""
for t in i.get("TagList", []):
- tag_xml += f"<Tag><Key>{t['Key']}</Key><Value>{t['Value']}</Value></Tag>"
+ tag_xml += f"<Tag><Key>{_esc(t['Key'])}</Key><Value>{_esc(t['Value'])}</Value></Tag>"
read_replica_xml = ""
for rr in i.get("ReadReplicaDBInstanceIdentifiers", []):
@@ -1578,7 +1579,7 @@ def _cluster_xml(c):
tag_xml = ""
for t in c.get("TagList", []):
- tag_xml += f"<Tag><Key>{t['Key']}</Key><Value>{t['Value']}</Value></Tag>"
+ tag_xml += f"<Tag><Key>{_esc(t['Key'])}</Key><Value>{_esc(t['Value'])}</Value></Tag>"
return f"""<DBClusterIdentifier>{c['DBClusterIdentifier']}</DBClusterIdentifier>
<DBClusterArn>{c['DBClusterArn']}</DBClusterArn>
@@ -1621,7 +1622,7 @@ def _cluster_xml(c):
def _snapshot_xml(s):
tag_xml = ""
for t in s.get("TagList", []):
- tag_xml += f"<Tag><Key>{t['Key']}</Key><Value>{t['Value']}</Value></Tag>"
+ tag_xml += f"<Tag><Key>{_esc(t['Key'])}</Key><Value>{_esc(t['Value'])}</Value></Tag>"
return f"""<DBSnapshotIdentifier>{s['DBSnapshotIdentifier']}</DBSnapshotIdentifier>
<DBInstanceIdentifier>{s['DBInstanceIdentifier']}</DBInstanceIdentifier>
<DBSnapshotArn>{s.get('DBSnapshotArn','')}</DBSnapshotArn>
@@ -1674,7 +1675,7 @@ def _subnet_group_xml(sg):
def _cluster_snapshot_xml(s):
tag_xml = ""
for t in s.get("TagList", []):
- tag_xml += f"<Tag><Key>{t['Key']}</Key><Value>{t['Value']}</Value></Tag>"
+ tag_xml += f"<Tag><Key>{_esc(t['Key'])}</Key><Value>{_esc(t['Value'])}</Value></Tag>"
az_xml = ""
for az in s.get("AvailabilityZones", []):
az_xml += f"<AvailabilityZone>{az}</AvailabilityZone>"
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 17a5980b..a5c0bc90 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -587,7 +587,7 @@ def _head_bucket(name: str):
200,
{
"Content-Type": "application/xml",
- "x-amz-bucket-region": _buckets[name].get("region") or "us-east-1",
+ "x-amz-bucket-region": _buckets[name].get("region") or os.environ.get("MINISTACK_REGION", "us-east-1"),
},
b"",
)
@@ -599,7 +599,7 @@ def _get_bucket_location(name: str):
root = Element("LocationConstraint", xmlns=S3_NS)
region = _buckets[name].get("region")
# AWS returns empty LocationConstraint for us-east-1.
- if region and region != "us-east-1":
+ if region and region != os.environ.get("MINISTACK_REGION", "us-east-1"):
root.text = region
return 200, {"Content-Type": "application/xml"}, _xml_body(root)
@@ -1122,7 +1122,7 @@ def _fire_s3_event(
{
"eventVersion": "2.1",
"eventSource": "aws:s3",
- "awsRegion": "us-east-1",
+ "awsRegion": os.environ.get("MINISTACK_REGION", "us-east-1"),
"eventTime": event_time,
"eventName": short_event,
"userIdentity": {"principalId": "EXAMPLE"},
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index cdb5ab49..da85986b 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -28,6 +28,7 @@ import json
import logging
import os
import struct
+import threading
import time
from urllib.parse import parse_qs
from xml.sax.saxutils import escape as _esc
@@ -40,6 +41,7 @@ logger = logging.getLogger("sqs")
_queues: dict = {}
_queue_name_to_url: dict = {}
+_queues_lock = threading.Lock()
ACCOUNT_ID = "000000000000"
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
@@ -1250,24 +1252,22 @@ def reset():
def _receive_messages_for_esm(queue_url: str, max_number: int) -> list[dict]:
- """Receive up to max_number messages for ESM consumption.
-
- Returns the *internal* message dicts (with receipt_handle set) so the ESM poller
- can build AWS Lambda SQS event payloads and then delete via receipt handles.
- """
- q = _get_q(queue_url)
- max_n = min(int(max_number or 1), 10)
- vis = int(q["attributes"].get("VisibilityTimeout", "30"))
- _dlq_sweep(q)
- return _collect_msgs(q, max_n, vis)
+ """Receive up to max_number messages for ESM consumption (thread-safe)."""
+ with _queues_lock:
+ q = _get_q(queue_url)
+ max_n = min(int(max_number or 1), 10)
+ vis = int(q["attributes"].get("VisibilityTimeout", "30"))
+ _dlq_sweep(q)
+ return _collect_msgs(q, max_n, vis)
def _delete_messages_for_esm(queue_url: str, receipt_handles: set[str]) -> None:
- """Best-effort delete of messages received by ESM."""
+ """Best-effort delete of messages received by ESM (thread-safe)."""
if not receipt_handles:
return
- q = _get_q(queue_url)
- q["messages"] = [
- m for m in q["messages"]
- if not (m.get("receipt_handle") is not None and m.get("receipt_handle") in receipt_handles)
- ]
+ with _queues_lock:
+ q = _get_q(queue_url)
+ q["messages"] = [
+ m for m in q["messages"]
+ if not (m.get("receipt_handle") is not None and m.get("receipt_handle") in receipt_handles)
+ ]
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index 43ee43ef..9cdf62ec 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -191,6 +191,10 @@ def _delete_state_machine(data):
f"State machine {arn} not found", 400)
del _state_machines[arn]
_tags.pop(arn, None)
+ # Clean up executions for this state machine
+ stale = [k for k, v in _executions.items() if v.get("stateMachineArn") == arn]
+ for k in stale:
+ _executions.pop(k, None)
return json_response({})
diff --git a/pyproject.toml b/pyproject.toml
index fcd217b0..14fa6902 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.1.23"
+version = "1.1.24"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_services.py b/tests/test_services.py
index 9b496526..3c9b1ce7 100644
--- a/tests/test_services.py
+++ b/tests/test_services.py
@@ -16748,3 +16748,48 @@ def test_kms_decrypt_wrong_context_fails(kms_client):
EncryptionContext={"env": "dev"},
)
assert "InvalidCiphertextException" in str(exc_info.value)
+
+
+def test_kms_create_and_list_alias(kms_client):
+ key = kms_client.create_key(KeySpec="SYMMETRIC_DEFAULT")
+ key_id = key["KeyMetadata"]["KeyId"]
+ kms_client.create_alias(AliasName="alias/test-alias", TargetKeyId=key_id)
+ resp = kms_client.list_aliases()
+ alias_names = [a["AliasName"] for a in resp["Aliases"]]
+ assert "alias/test-alias" in alias_names
+
+
+def test_kms_use_alias_for_encrypt(kms_client):
+ """Encrypt/Decrypt using alias instead of key ID."""
+ key = kms_client.create_key(KeySpec="SYMMETRIC_DEFAULT", KeyUsage="ENCRYPT_DECRYPT")
+ key_id = key["KeyMetadata"]["KeyId"]
+ kms_client.create_alias(AliasName="alias/enc-alias", TargetKeyId=key_id)
+ enc = kms_client.encrypt(KeyId="alias/enc-alias", Plaintext=b"via alias")
+ dec = kms_client.decrypt(CiphertextBlob=enc["CiphertextBlob"])
+ assert dec["Plaintext"] == b"via alias"
+
+
+def test_kms_describe_key_by_alias(kms_client):
+ key = kms_client.create_key(KeySpec="SYMMETRIC_DEFAULT")
+ key_id = key["KeyMetadata"]["KeyId"]
+ kms_client.create_alias(AliasName="alias/desc-alias", TargetKeyId=key_id)
+ resp = kms_client.describe_key(KeyId="alias/desc-alias")
+ assert resp["KeyMetadata"]["KeyId"] == key_id
+
+
+def test_kms_update_alias(kms_client):
+ key1 = kms_client.create_key(KeySpec="SYMMETRIC_DEFAULT")
+ key2 = kms_client.create_key(KeySpec="SYMMETRIC_DEFAULT")
+ kms_client.create_alias(AliasName="alias/upd-alias", TargetKeyId=key1["KeyMetadata"]["KeyId"])
+ kms_client.update_alias(AliasName="alias/upd-alias", TargetKeyId=key2["KeyMetadata"]["KeyId"])
+ resp = kms_client.describe_key(KeyId="alias/upd-alias")
+ assert resp["KeyMetadata"]["KeyId"] == key2["KeyMetadata"]["KeyId"]
+
+
+def test_kms_delete_alias(kms_client):
+ key = kms_client.create_key(KeySpec="SYMMETRIC_DEFAULT")
+ kms_client.create_alias(AliasName="alias/del-alias", TargetKeyId=key["KeyMetadata"]["KeyId"])
+ kms_client.delete_alias(AliasName="alias/del-alias")
+ with pytest.raises(ClientError) as exc:
+ kms_client.describe_key(KeyId="alias/del-alias")
+ assert "NotFoundException" in str(exc.value)