Skip to content

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

release v1.5.18

Nahuel990bbf02ed38aae
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3e24dd58..cafd422e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,29 +5,29 @@ All notable changes to MiniStack will be documented here.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
Versioning follows [Semantic Versioning](https://semver.org/).
-## [Unreleased]
+## [1.5.18] — 2026-09-28
### Added
-- **Cognito — OIDC discovery through the real issuer host (`USE_SSL=1`)** — the generated certificate now names `cognito-idp.<region>.amazonaws.com` for every region, the gateway also listens on 443 when it can, and Lambda containers resolve those hosts to MiniStack and trust its certificate. With an `/etc/hosts` entry and the certificate trusted, an unmodified client follows the token's `iss` to MiniStack while `iss` stays exactly as AWS issues it. Reported by @epcap90.
-- **Bedrock AgentCore — `InvokeAgentRuntime` runs the runtime's container** — with Docker available (full image), the runtime's `containerConfiguration.containerUri` image is started once, checked on `/ping`, and invocations are forwarded to `/invocations` on port 8080; worker and container failures answer `RuntimeClientError` (424). The container is removed on update, delete or reset. Without Docker, or for a code artifact, the deterministic echo remains. Contributed by @pingedbrain.
+- **Bedrock AgentCore — `InvokeAgentRuntime` runs the runtime's container** — with Docker available (full image), the runtime's `containerConfiguration.containerUri` image is started, checked on `/ping`, and invocations are forwarded to its `/invocations` on port 8080; container failures answer `RuntimeClientError` (424). The container is removed on update, delete or reset. Without Docker, or for a code artifact, the deterministic echo remains. Contributed by @pingedbrain.
+- **CloudWatch Logs — delivery destination policy** — `PutDeliveryDestinationPolicy`, `GetDeliveryDestinationPolicy` and `DeleteDeliveryDestinationPolicy`, so a delivery that needs a destination policy can be created. Contributed by @fabio-andre-rodrigues.
+- **Cognito — OIDC discovery through the real issuer host (`USE_SSL=1`)** — the generated certificate covers `cognito-idp.<region>.amazonaws.com` for every region and Lambda containers resolve those hosts to MiniStack and trust it. With an `/etc/hosts` entry and the certificate trusted, an unmodified client follows the token's `iss` to MiniStack while `iss` stays exactly as AWS issues it. Reported by @epcap90.
+- **KMS — `ListGrants`** — it answered `InvalidAction`. It now lists the key's grants (empty, since grants are not modelled) and answers `NotFoundException` for an unknown key. Reported by @DaviReisVieira.
+- **S3 — object annotations** — `PutObjectAnnotation`, `GetObjectAnnotation`, `ListObjectAnnotations` and `DeleteObjectAnnotation`: up to 1,000 UTF-8 payloads per object version, carried by `CopyObject` unless the directive is `EXCLUDE`, removed with their version, and announced with `s3:ObjectAnnotation:*` events. Under `AUTH=true`, Object Lock refuses annotation writes with 403 `AccessDenied`. Previously a `PUT ?annotation` replaced the object with the payload. Contributed by @BoLaMN.
- **SNS — `AddPermission` and `RemovePermission`** — they add and remove labelled statements in the topic's `Policy`; a duplicate label answers `InvalidParameter`. Contributed by @AdrianAcala.
### Fixed
-- **SQS/SNS — queue and topic policies are enforced under `AUTH=true`** — the `Policy` attributes were stored but never evaluated. Same-account calls pass unless the policy explicitly denies them; cross-account calls need an explicit Allow (`AccessDenied` for SQS, `AuthorizationError` for SNS). S3→SQS, S3→SNS and SNS→SQS deliveries need the destination policy to allow the calling service. With `AUTH=false` every path stays permissive. `GetQueueUrl` accepts `QueueOwnerAWSAccountId`. Contributed by @AdrianAcala.
-- **S3 — notification destinations are validated at PUT time** — under `AUTH=true`, `PutBucketNotificationConfiguration` fails with `InvalidArgument` ("Unable to validate the following destination configurations") when an SQS/SNS destination's policy does not let S3 publish; with `AUTH=false` only existence is checked. Cross-account SQS/SNS destinations are accepted, and `SkipDestinationValidation` skips the check. Contributed by @AdrianAcala.
-- **Bedrock AgentCore — opt-in Docker runtime** — set `MINISTACK_AGENTCORE_DOCKER=1` to start the declared `containerConfiguration.containerUri` image on first invocation, connect via a localhost port when MiniStack runs on the host or via MiniStack's Docker network when containerized, call `/ping`, and forward `InvokeAgentRuntime` to `/invocations` on port 8080. The container is reused and removed on update, delete, or reset. Container and worker HTTP errors become `RuntimeClientError` (424); caller credentials are not forwarded. Without Docker mode, the existing deterministic echo remains for SDK tests. This covers HTTP only and does not emulate AWS IAM/VPC isolation or model inference.
-- **CloudWatch Logs — delivery destination policy** — `PutDeliveryDestinationPolicy`, `GetDeliveryDestinationPolicy`, `DeleteDeliveryDestinationPolicy`. Required by an operator that authorizes `delivery.logs.amazonaws.com` to create deliveries to a `DeliveryDestination` (e.g. CloudFront access-log delivery to a log group) — `PutDeliveryDestinationPolicy` previously had no route, blocking the delivery from ever being created. Contributed by @fabio-andre-rodrigues.
-- **S3 — object annotations** — `PutObjectAnnotation`, `GetObjectAnnotation`, `ListObjectAnnotations` and `DeleteObjectAnnotation`: up to 1,000 named UTF-8 payloads (1 byte to 1 MiB) per object version, with S3's naming rules and errors. `CopyObject` carries them unless `x-amz-object-annotation-directive: EXCLUDE`; checksums default to CRC64NVME (XXHASH3 and XXHASH128 are refused); annotations take the object's encryption (refused on SSE-C), replicate, persist with `S3_PERSIST=1`, and send `s3:ObjectAnnotation:Put` / `s3:ObjectAnnotation:Delete` events. Under `AUTH=true`, Object Lock refuses annotation writes with 403 `AccessDenied` (governance retention unless `x-amz-bypass-governance-retention: true`, which also needs `s3:BypassGovernanceRetention`; compliance retention and a legal hold always), and the operations authorize as `s3:PutObjectAnnotation`, `s3:GetObjectAnnotation`, `s3:ListObjectAnnotations` and `s3:DeleteObjectAnnotation`. Previously a `PUT ?annotation` replaced the object with the payload. Contributed by @BoLaMN.
-
-### Fixed
-
-- **API Gateway v1 — REQUEST authorizer events carry `requestContext.identity`** — the event had no `identity` block, so an authorizer reading `sourceIp` or `userAgent` crashed. It now carries both, as the `AWS_PROXY` integration event does. Contributed by @yosriady.
-- **DynamoDB — `DescribeTable` accepts a table ARN** — `TableName` given as the table's ARN answered `ResourceNotFoundException`, where AWS accepts either form. It now resolves through the same ARN normalization the other table operations use, and an ARN from another account or region still answers `ResourceNotFoundException`. This unblocks OpenSearch Data Prepper's DynamoDB source, which always describes the table by ARN.
-- **S3 — event notification records match S3's** — the key is URL-encoded (`red flower.jpg` → `red+flower.jpg`), `versionId` names the version the write made or removed, `sequencer` grows with every create and delete (it was always `"0"`), and `eventVersion` is `2.6`. A delete that leaves a delete marker is `ObjectRemoved:DeleteMarkerCreated` (it was `ObjectRemoved:Delete`), and `DeleteObjects` sends an event for each object it removes (it sent none). Contributed by @BoLaMN.
-- **STS — `GetCallerIdentity` resolves IAM-user callers** — keys created with `CreateAccessKey` returned the `root` ARN; they now return the user's ARN and ID. Under `AUTH=true`, unknown and inactive keys are refused with 403 `InvalidClientTokenId` instead of reported as root. Contributed by @AdrianAcala.
-- **STS — an unknown access key answers `InvalidClientTokenId`** — under `AUTH=true`, STS operations refused an unknown key with `UnrecognizedClientException`; real STS answers `InvalidClientTokenId`.
+- **API Gateway v1 — REQUEST authorizer events carry `requestContext.identity`** — an authorizer reading `sourceIp` or `userAgent` crashed; both are now present, as in the `AWS_PROXY` event. Contributed by @yosriady.
+- **DynamoDB — a table ARN is accepted wherever `TableName` is** — item, query, scan, batch, transaction and table operations answered `ValidationException` or `ResourceNotFoundException` for the table's ARN. Batch responses keep the key form the request used. Contributed by @valeryan.
+- **Gateway — the soft open-file limit is raised to the hard limit at startup** — a burst of about a thousand client connections exhausted the default 1024 descriptors. Reported by @fabio-andre-rodrigues.
+- **KMS — `ListAliases` entries carry `CreationDate` and `LastUpdatedDate`** — both were missing; `UpdateAlias` moves `LastUpdatedDate` and keeps `CreationDate`. Reported by @DaviReisVieira.
+- **Lambda — `ReservedConcurrentExecutions` is shared across versions** — `$LATEST` and published versions each counted separately and could exceed the reservation together. Contributed by @jgrumboe.
+- **S3 — event notification records match S3's** — the key is URL-encoded, `versionId` and a growing `sequencer` are set, `eventVersion` is `2.6`, a delete marker is `ObjectRemoved:DeleteMarkerCreated`, and `DeleteObjects` sends one event per object it removes. Contributed by @BoLaMN.
+- **S3 — notification destinations are validated at PUT time** — under `AUTH=true`, `PutBucketNotificationConfiguration` fails with `InvalidArgument` when an SQS/SNS destination's policy does not let S3 publish; cross-account destinations are accepted. Contributed by @AdrianAcala.
+- **SQS/SNS — queue and topic policies are enforced under `AUTH=true`** — they were stored but never evaluated. Cross-account calls need an explicit Allow (`AccessDenied` for SQS, `AuthorizationError` for SNS), and S3 and SNS deliveries need the destination policy to allow them. With `AUTH=false` nothing changes. Contributed by @AdrianAcala.
+- **STS — `GetCallerIdentity` resolves IAM-user callers** — keys from `CreateAccessKey` reported `root`; they now return the user's ARN and ID. Contributed by @AdrianAcala.
+- **STS — an unknown access key answers `InvalidClientTokenId`** — under `AUTH=true`, STS answered `UnrecognizedClientException`.
## [1.5.17] — 2026-09-25
diff --git a/README.md b/README.md
index 8dbfdd73..907db614 100644
--- a/README.md
+++ b/README.md
@@ -402,9 +402,9 @@ subnet = ec2.create_subnet(
| Service | Operations | Notes |
|---------|-----------|-------|
-| **S3** | CreateBucket, DeleteBucket, ListBuckets, HeadBucket, PutObject, GetObject, DeleteObject, HeadObject, CopyObject, ListObjects v1/v2, DeleteObjects, GetBucketVersioning, PutBucketVersioning, GetBucketEncryption, PutBucketEncryption, DeleteBucketEncryption, GetBucketLifecycleConfiguration, PutBucketLifecycleConfiguration, DeleteBucketLifecycle, GetBucketCors, PutBucketCors, DeleteBucketCors, GetBucketAcl, PutBucketAcl, GetBucketTagging, PutBucketTagging, DeleteBucketTagging, GetBucketPolicy, PutBucketPolicy, DeleteBucketPolicy, GetBucketNotificationConfiguration, PutBucketNotificationConfiguration, GetBucketLogging, PutBucketLogging, ListObjectVersions, CreateMultipartUpload, UploadPart, CompleteMultipartUpload, AbortMultipartUpload, PutObjectLockConfiguration, GetObjectLockConfiguration, PutObjectRetention, GetObjectRetention, PutObjectLegalHold, GetObjectLegalHold, PutBucketReplication, GetBucketReplication, DeleteBucketReplication, GetObjectTagging, PutObjectTagging, DeleteObjectTagging, PutObjectAnnotation, GetObjectAnnotation, ListObjectAnnotations, DeleteObjectAnnotation | Optional disk persistence via `S3_PERSIST=1`; Object Lock with retention & legal hold enforcement on delete and on annotation writes (governance mode yields to `x-amz-bypass-governance-retention`); object annotations are per version (up to 1,000, 1 byte–1 MiB each), carried by `CopyObject` and removed with their version; object tags are versioned (`?tagging&versionId=…` reads, writes, and deletes the per-version tag set); Multi-Region Access Points provision from CloudFormation (`AWS::S3::MultiRegionAccessPoint`) and `<alias>.accesspoint.s3-global.amazonaws.com` serves the member buckets through the regular S3 path |
+| **S3** | CreateBucket, DeleteBucket, ListBuckets, HeadBucket, PutObject, GetObject, DeleteObject, HeadObject, CopyObject, ListObjects v1/v2, DeleteObjects, GetBucketVersioning, PutBucketVersioning, GetBucketEncryption, PutBucketEncryption, DeleteBucketEncryption, GetBucketLifecycleConfiguration, PutBucketLifecycleConfiguration, DeleteBucketLifecycle, GetBucketCors, PutBucketCors, DeleteBucketCors, GetBucketAcl, PutBucketAcl, GetBucketTagging, PutBucketTagging, DeleteBucketTagging, GetBucketPolicy, PutBucketPolicy, DeleteBucketPolicy, GetBucketNotificationConfiguration, PutBucketNotificationConfiguration, GetBucketLogging, PutBucketLogging, ListObjectVersions, CreateMultipartUpload, UploadPart, CompleteMultipartUpload, AbortMultipartUpload, PutObjectLockConfiguration, GetObjectLockConfiguration, PutObjectRetention, GetObjectRetention, PutObjectLegalHold, GetObjectLegalHold, PutBucketReplication, GetBucketReplication, DeleteBucketReplication, GetObjectTagging, PutObjectTagging, DeleteObjectTagging, PutObjectAnnotation, GetObjectAnnotation, ListObjectAnnotations, DeleteObjectAnnotation | Optional disk persistence via `S3_PERSIST=1`; Object Lock with retention & legal hold enforcement on delete, and on annotation writes under `AUTH=true` (governance mode yields to `x-amz-bypass-governance-retention`); object annotations are per version (up to 1,000, 1 byte–1 MiB each), carried by `CopyObject` and removed with their version; object tags are versioned (`?tagging&versionId=…` reads, writes, and deletes the per-version tag set); Multi-Region Access Points provision from CloudFormation (`AWS::S3::MultiRegionAccessPoint`) and `<alias>.accesspoint.s3-global.amazonaws.com` serves the member buckets through the regular S3 path |
| **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; the batch actions apply AWS's request-level validation (empty batch, more than ten entries, repeated or malformed entry ids) before any entry is processed |
-| **SNS** | CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes, Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, GetSubscriptionAttributes, SetSubscriptionAttributes, ConfirmSubscription, Publish, PublishBatch, TagResource, UntagResource, ListTagsForResource, CreatePlatformApplication, ListPlatformApplications, GetPlatformApplicationAttributes, SetPlatformApplicationAttributes, CreatePlatformEndpoint, GetEndpointAttributes, SetEndpointAttributes, DeleteEndpoint, DeletePlatformApplication | SNS→SQS fanout delivery; SNS→Lambda fanout (asynchronous delivery); FIFO topics with 5-minute deduplication, sequence numbers, content-based deduplication, and subscription validation; mobile-push endpoint lifecycle with device-token dedup and `Publish` to platform-endpoint `TargetArn` |
+| **SNS** | CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes, AddPermission, RemovePermission, Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, GetSubscriptionAttributes, SetSubscriptionAttributes, ConfirmSubscription, Publish, PublishBatch, TagResource, UntagResource, ListTagsForResource, CreatePlatformApplication, ListPlatformApplications, GetPlatformApplicationAttributes, SetPlatformApplicationAttributes, CreatePlatformEndpoint, GetEndpointAttributes, SetEndpointAttributes, DeleteEndpoint, DeletePlatformApplication | SNS→SQS fanout delivery; SNS→Lambda fanout (asynchronous delivery); FIFO topics with 5-minute deduplication, sequence numbers, content-based deduplication, and subscription validation; mobile-push endpoint lifecycle with device-token dedup and `Publish` to platform-endpoint `TargetArn` |
| **DynamoDB** | CreateTable, UpdateTable, DeleteTable, DescribeTable, ListTables, PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem, TransactWriteItems, TransactGetItems, DescribeTimeToLive, UpdateTimeToLive, DescribeContinuousBackups, UpdateContinuousBackups, DescribeEndpoints, TagResource, UntagResource, ListTagsOfResource, EnableKinesisStreamingDestination, DisableKinesisStreamingDestination, DescribeKinesisStreamingDestination, UpdateKinesisStreamingDestination | TTL enforced via thread-safe background reaper (60s cadence); DynamoDB Streams — `StreamSpecification` emits INSERT/MODIFY/REMOVE records on all write operations, respects `StreamViewType`; Kinesis streaming destinations (`aws_dynamodb_kinesis_streaming_destination`) fan item mutations out into any Kinesis stream by ARN while the destination is ACTIVE |
| **DynamoDB Streams** | ListStreams, DescribeStream, GetShardIterator, GetRecords | Reads records emitted by the main DynamoDB service via `boto3.client("dynamodbstreams")` — single synthetic shard per stream; `TRIM_HORIZON`/`LATEST`/`AT_SEQUENCE_NUMBER`/`AFTER_SEQUENCE_NUMBER` iterator types; `NEW_AND_OLD_IMAGES`, `NEW_IMAGE`, `OLD_IMAGE`, `KEYS_ONLY` view types; opaque base64 iterator tokens |
| **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, CheckpointDurableExecution, GetDurableExecution, GetDurableExecutionState, GetDurableExecutionHistory, ListDurableExecutionsByFunction, StopDurableExecution, SendDurableExecutionCallbackSuccess, SendDurableExecutionCallbackFailure, SendDurableExecutionCallbackHeartbeat | Python and Node.js runtimes execute with warm worker pool; `provided.al2023`/`provided.al2` runtimes reuse local bootstrap processes via the Lambda Runtime API (Go, Rust, C++ support), or use Docker RIE when configured; `Publish=True` creates immutable numbered versions; Code via `ZipFile`, `S3Bucket`/`S3Key` (with optional `S3ObjectVersion`), or `ImageUri` (Docker image); `PackageType: Image` pulls and invokes user-provided Docker images via Lambda RIE; SQS, Kinesis, and DynamoDB Streams event source mappings; Function URL CRUD; Lambda Layers CRUD; Aliases; Concurrency; EventInvokeConfig; **SnapStart** — `SnapStart.ApplyOn=PublishedVersions` round-trips on `CreateFunction`/`UpdateFunctionConfiguration` (Java 11+/Python 3.12+/.NET 8+ and container images, per AWS's constraints); publishing a version initializes its execution environment then and there, so the version reports `OptimizationStatus: On`, walks `Pending` → `Active`, answers `ResourceConflictException` while `Pending`, fails the publish on a broken init, and runs `snapshot-restore-py` before-snapshot/after-restore hooks during init (Python); **Durable Functions** — `CreateFunction` accepts `DurableConfig`; checkpoint/state/history/list/stop ops at the preview API (`2025-12-01`); external `SendCallback{Success,Failure,Heartbeat}` resume the SDK across invocations; resume scheduler fires WAIT expiries, callback timeouts, and step-retry backoffs; verified against the official `aws-durable-execution-sdk-python` and `aws-durable-execution-sdk-java`; **X-Ray active tracing** — `TracingConfig.Mode=Active` injects `_X_AMZN_TRACE_ID` (`Root=1-<hex>-<hex>;Parent=<hex>;Sampled=1`) into the runtime per invocation so the AWS X-Ray SDK runs without `Missing AWS Lambda trace data`; supported on the warm Python / Node executor, provided runtimes, and the local subprocess fallback (docker RIE upstream does not implement X-Ray and is logged but unsupported) |
@@ -414,7 +414,7 @@ subnet = ec2.create_subnet(
| **ECS Task Metadata V4** | `GET /v4/<token>`, `GET /v4/<token>/task`, `GET /v4/<token>/stats`, `GET /v4/<token>/task/stats` | Per-container token injected as `ECS_CONTAINER_METADATA_URI_V4` on every container started by `RunTask`. `/task` returns sibling containers in the same task. Containers reach the gateway via `host.docker.internal` (mapped through `extra_hosts: host-gateway`, so it works on user-defined Docker networks); `networkMode: host` containers use loopback. Volatile by design (stripped on persistence, cleared by `/_ministack/reset`) |
| **ECS Container Credentials** | `GET /v2/credentials/<uuid>` | The path real ECS exposes via `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=/v2/credentials/<uuid>` (resolved by SDKs against `169.254.170.2`). MiniStack serves the same path on the gateway and returns the AWS-strict 5-field credentials document (`AccessKeyId`, `SecretAccessKey`, `Token`, `Expiration`, `RoleArn`) — distinct from the IMDS shape served at `/latest/meta-data/iam/security-credentials/<role>`. `RunTask` injects `AWS_CONTAINER_CREDENTIALS_FULL_URI`, `AWS_CONTAINER_AUTHORIZATION_TOKEN` (satisfies botocore's allow-list for non-loopback gateway hosts), and `AWS_ENDPOINT_URL` so unmodified SDKs inside the task fetch credentials and route service calls through MiniStack with no client config |
| **SecretsManager** | CreateSecret, GetSecretValue, ListSecrets, DeleteSecret, UpdateSecret, DescribeSecret, PutSecretValue, UpdateSecretVersionStage, RestoreSecret, RotateSecret, GetRandomPassword, ListSecretVersionIds, ReplicateSecretToRegions, TagResource, UntagResource, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy, ValidateResourcePolicy | |
-| **CloudWatch Logs** | CreateLogGroup, DeleteLogGroup, DescribeLogGroups, CreateLogStream, DeleteLogStream, DescribeLogStreams, PutLogEvents, GetLogEvents, FilterLogEvents, GetLogRecord, GetLogGroupFields, StartLiveTail, 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; `GetLogRecord` resolves Insights `@ptr` values issued at `PutLogEvents`; `GetLogGroupFields` scans recent stored events (optional `time` ±8m, else last 15m) and returns field names with rough presence percent, including system `@*` fields and flattened JSON message keys; Insights CWLI subset: `fields`, chained `| filter` (`=` / `like /regex/`), `| sort @timestamp`, post-filter `| limit` as `min(query, API)`; `StartLiveTail` holds an AWS eventstream open until client disconnect and fans matching `PutLogEvents` into `sessionUpdate` frames (1s idle heartbeats; buffer of 10 updates, oldest dropped when full); use `Config(inject_host_prefix=False)` with a custom endpoint so boto3 does not prepend `stream-` to the hostname; `DescribeLogGroups` includes both `arn` (`:*`) and `logGroupArn` (no star) |
+| **CloudWatch Logs** | CreateLogGroup, DeleteLogGroup, DescribeLogGroups, CreateLogStream, DeleteLogStream, DescribeLogStreams, PutLogEvents, GetLogEvents, FilterLogEvents, GetLogRecord, GetLogGroupFields, StartLiveTail, PutRetentionPolicy, DeleteRetentionPolicy, PutSubscriptionFilter, DeleteSubscriptionFilter, DescribeSubscriptionFilters, PutMetricFilter, DeleteMetricFilter, DescribeMetricFilters, TagLogGroup, UntagLogGroup, ListTagsLogGroup, TagResource, UntagResource, ListTagsForResource, StartQuery, GetQueryResults, StopQuery, PutDestination, DeleteDestination, DescribeDestinations, PutDestinationPolicy, PutDeliverySource, GetDeliverySource, DeleteDeliverySource, DescribeDeliverySources, PutDeliveryDestination, GetDeliveryDestination, DeleteDeliveryDestination, DescribeDeliveryDestinations, PutDeliveryDestinationPolicy, GetDeliveryDestinationPolicy, DeleteDeliveryDestinationPolicy, CreateDelivery, GetDelivery, DeleteDelivery, DescribeDeliveries | `FilterLogEvents` supports `*`/`?` globs, multi-term AND, `-term` exclusion; `GetLogRecord` resolves Insights `@ptr` values issued at `PutLogEvents`; `GetLogGroupFields` scans recent stored events (optional `time` ±8m, else last 15m) and returns field names with rough presence percent, including system `@*` fields and flattened JSON message keys; Insights CWLI subset: `fields`, chained `| filter` (`=` / `like /regex/`), `| sort @timestamp`, post-filter `| limit` as `min(query, API)`; `StartLiveTail` holds an AWS eventstream open until client disconnect and fans matching `PutLogEvents` into `sessionUpdate` frames (1s idle heartbeats; buffer of 10 updates, oldest dropped when full); use `Config(inject_host_prefix=False)` with a custom endpoint so boto3 does not prepend `stream-` to the hostname; `DescribeLogGroups` includes both `arn` (`:*`) and `logGroupArn` (no star) |
### Extended Services
@@ -441,7 +441,7 @@ subnet = ec2.create_subnet(
| **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateRouteResponse, GetRouteResponse, GetRouteResponses, UpdateRouteResponse, DeleteRouteResponse, CreateIntegrationResponse, GetIntegrationResponse, GetIntegrationResponses, UpdateIntegrationResponse, DeleteIntegrationResponse, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, TagResource, UntagResource, GetTags, PostToConnection, GetConnection, DeleteConnection | **HTTP API** and **WebSocket API** (`protocolType=WEBSOCKET`); Lambda proxy (`AWS_PROXY`), HTTP proxy (`HTTP_PROXY`), and MOCK integrations; HTTP data plane via `{apiId}.execute-api.localhost` Host header or path-based `/_aws/execute-api/{apiId}/{stage}/{path}` (no DNS/Host override needed — works from browsers on macOS and strict clients); `$default` stage served from the URL root (no stage segment in the path); per-API `corsConfiguration` applied to preflights + dispatched responses; request parameter mapping for HTTP_PROXY (`append/overwrite/remove` for headers/querystring plus `overwrite:path`) with context variables including `$context.authorizer.jwt.claims`; JWT data-plane authorization for HTTP routes (issuer/audience/time/scope checks) and claim propagation to integrations; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; WebSocket data plane on the same two URL forms, with `$connect` / `$disconnect` / `$default` / custom-action routing, `$request.body.*` RouteSelectionExpression, `@connections` management API (PostToConnection / GetConnection / DeleteConnection), per-connection outbox for server-side push; `{param}` / `{proxy+}` matching; JWT/Lambda authorizer CRUD; pin `apiId` across runs with the `ms-custom-id` tag |
| **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateDocumentationPart, GetDocumentationPart, GetDocumentationParts, UpdateDocumentationPart, DeleteDocumentationPart, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags, CreateRequestValidator, GetRequestValidators, GetRequestValidator, UpdateRequestValidator, DeleteRequestValidator | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), non-proxy Lambda (AWS — the handler's output is the response body, mapping templates not modeled), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost` Host header, path-based `/_aws/execute-api/{apiId}/{stage}/{path}`, or legacy `/restapis/{apiId}/{stage}/_user_request_/{path}`; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; resource tree with `{param}` and `{proxy+}` path matching; routing is on the resource+method pair, so a request the matched resource does not serve falls through to a `{proxy+}` elsewhere in the tree (a methodless intermediate, a CORS-preflight-only node, or any undeclared verb), as it does on AWS; TOKEN and REQUEST Lambda authorizers on the data plane, with the returned IAM policy evaluated against each request's own method ARN and `authorizerResultTtlInSeconds` caching the policy per stage and identity source; JSON Patch for all PATCH operations; state persistence; pin `id` across runs with the `ms-custom-id` tag |
| **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, SetSubnets, SetIpAddressType, SetSecurityGroups, RegisterTargets, DeregisterTargets, DescribeTargetHealth, AddTags, RemoveTags, DescribeTags | Control plane + data plane; ALB→Lambda live traffic routing; `path-pattern`, `host-header`, `http-method`, `query-string`, `http-header` rule conditions; `forward`, `redirect`, `fixed-response`, `authenticate-oidc` actions; data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix |
-| **KMS** | CreateKey, ReplicateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateMac, VerifyMac, GenerateDataKey, GenerateDataKeyWithoutPlaintext, GenerateDataKeyPair, GenerateDataKeyPairWithoutPlaintext, GenerateRandom, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, UpdateKeyDescription, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags, GetParametersForImport, ImportKeyMaterial, DeleteImportedKeyMaterial | 34 actions; multi-Region keys: `CreateKey` with `MultiRegion` mints an `mrk-` key and `ReplicateKey` creates a same-id replica in another region sharing the key material (ciphertext from the primary decrypts against the replica; a primary with live replicas waits in `PendingReplicaDeletion`); CMK specs: RSA (2048/3072/4096), ECC (SECG_P256K1, NIST P-256/384/521), Edwards25519 (`ECC_NIST_EDWARDS25519` — pure Ed25519 via `ED25519_SHA_512` with `MessageType=RAW`; `ED25519_PH_SHA_512` advertised in `SigningAlgorithms` but returns `UnsupportedOperationException` until Ed25519ph lands), HMAC (`HMAC_224`/`HMAC_256`/`HMAC_384`/`HMAC_512` with `KeyUsage=GENERATE_VERIFY_MAC`), and symmetric keys; PKCS1v15, PSS, and ECDSA signing; real RFC 2104 HMAC via `GenerateMac`/`VerifyMac` (4096-byte message cap, `KMSInvalidMacException` on mismatch, `DryRun` supported); envelope encryption, incl. asymmetric data key pairs (`KeyPairSpec` adds RSA_3072); alias resolution; key rotation; key policies; tags; enable/disable/schedule deletion; full Terraform `aws_kms_key` compatible; `cryptography` package included in Docker image |
+| **KMS** | CreateKey, ReplicateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateMac, VerifyMac, GenerateDataKey, GenerateDataKeyWithoutPlaintext, GenerateDataKeyPair, GenerateDataKeyPairWithoutPlaintext, GenerateRandom, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, UpdateKeyDescription, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags, GetParametersForImport, ImportKeyMaterial, DeleteImportedKeyMaterial, ListGrants | 38 actions; multi-Region keys: `CreateKey` with `MultiRegion` mints an `mrk-` key and `ReplicateKey` creates a same-id replica in another region sharing the key material (ciphertext from the primary decrypts against the replica; a primary with live replicas waits in `PendingReplicaDeletion`); CMK specs: RSA (2048/3072/4096), ECC (SECG_P256K1, NIST P-256/384/521), Edwards25519 (`ECC_NIST_EDWARDS25519` — pure Ed25519 via `ED25519_SHA_512` with `MessageType=RAW`; `ED25519_PH_SHA_512` advertised in `SigningAlgorithms` but returns `UnsupportedOperationException` until Ed25519ph lands), HMAC (`HMAC_224`/`HMAC_256`/`HMAC_384`/`HMAC_512` with `KeyUsage=GENERATE_VERIFY_MAC`), and symmetric keys; PKCS1v15, PSS, and ECDSA signing; real RFC 2104 HMAC via `GenerateMac`/`VerifyMac` (4096-byte message cap, `KMSInvalidMacException` on mismatch, `DryRun` supported); envelope encryption, incl. asymmetric data key pairs (`KeyPairSpec` adds RSA_3072); alias resolution; key rotation; key policies; tags; enable/disable/schedule deletion; full Terraform `aws_kms_key` compatible; `cryptography` package included in Docker image |
| **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, CreateFunction, DeleteFunction, DescribeFunction, GetFunction, ListFunctions, PublishFunction, UpdateFunction, **KeyValueStore (mgmt)**: CreateKeyValueStore, DescribeKeyValueStore, ListKeyValueStores, UpdateKeyValueStore, DeleteKeyValueStore, **Policies**: CreateCachePolicy, GetCachePolicy, GetCachePolicyConfig, UpdateCachePolicy, DeleteCachePolicy, ListDistributionsByCachePolicyId, CreateOriginRequestPolicy, GetOriginRequestPolicy, GetOriginRequestPolicyConfig, UpdateOriginRequestPolicy, DeleteOriginRequestPolicy, ListDistributionsByOriginRequestPolicyId, CreateResponseHeadersPolicy, GetResponseHeadersPolicy, GetResponseHeadersPolicyConfig, UpdateResponseHeadersPolicy, DeleteResponseHeadersPolicy, ListDistributionsByResponseHeadersPolicyId, **Public keys / key groups**: CreatePublicKey, GetPublicKey, GetPublicKeyConfig, UpdatePublicKey, DeletePublicKey, ListPublicKeys, CreateKeyGroup, GetKeyGroup, GetKeyGroupConfig, UpdateKeyGroup, DeleteKeyGroup, ListKeyGroups, **SaaS Manager**: CreateConnectionGroup, GetConnectionGroup, GetConnectionGroupByRoutingEndpoint, UpdateConnectionGroup, DeleteConnectionGroup, ListConnectionGroups, CreateDistributionTenant, GetDistributionTenant, GetDistributionTenantByDomain, UpdateDistributionTenant, DeleteDistributionTenant, ListDistributionTenants, ListDistributionTenantsByCustomization, AssociateDistributionTenantWebACL, DisassociateDistributionTenantWebACL, CreateInvalidationForDistributionTenant, GetInvalidationForDistributionTenant, ListInvalidationsForDistributionTenant, VerifyDnsConfiguration, GetManagedCertificateDetails, ListDomainConflicts, UpdateDomainAssociation, ListDistributionsByConnectionMode, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin config round-trip; cache / origin request / response headers policies round-trip their full config with `ETag` / `If-Match` optimistic concurrency; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; **CloudFront Functions** are API stubs (in-memory code + DEVELOPMENT/LIVE ETags for Terraform `aws_cloudfront_function`) with `KeyValueStoreAssociations` round-tripped — no `TestFunction`, no viewer-request JS execution at the edge; `UpdateFunction` clears the emulated LIVE stage until `PublishFunction` runs again; **SaaS Manager** multi-tenant distributions: `DistributionConfig` round-trips `ConnectionMode` / `TenantConfig`, tenants require a `tenant-only` distribution, CNAMEs are unique across tenants and distribution aliases, a tenant without an explicit connection group lazily gets the account default group, and MiniStack collapses async workflows (tenants deploy, domains activate, DNS verifies, managed certificates issue immediately); key groups validate `Items` against real public keys, and deleting either while still referenced (`PublicKeyInUse` / `ResourceInUse`) is rejected |
| **CloudFront KeyValueStore (data plane)** | DescribeKeyValueStore, ListKeys, GetKey, PutKey, DeleteKey, UpdateKeys | Separate `cloudfront-keyvaluestore` SDK service (REST/JSON, signing name `cloudfront-keyvaluestore`); ETag-based optimistic concurrency on every mutating op; `UpdateKeys` is atomic (validates whole batch, rejects on first invalid entry); `ListKeys` paginates with opaque `NextToken` capped at 50 results per AWS spec; bridges to the management plane via the shared KVS ARN |
| **CloudTrail** | LookupEvents, CreateTrail, DeleteTrail, GetTrail, DescribeTrails, ListTrails, UpdateTrail, GetTrailStatus, StartLogging, StopLogging, PutEventSelectors, GetEventSelectors, AddTags, ListTags, RemoveTags | In-memory audit log; recording opt-in via `CLOUDTRAIL_RECORDING=1` (or runtime config endpoint); per-account ring buffer (`CLOUDTRAIL_MAX_EVENTS=10000`); `LookupEvents` supports all 8 AWS `LookupAttributes`; `IsLogging` flips on Start/StopLogging; `CreateTrail`/`UpdateTrail` persist `KmsKeyId` (normalized to a key ARN; omitted when unset) so `aws_cloudtrail` converges without drift |
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 5bea6a9e..f9dd6434 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -6844,6 +6844,7 @@ def _kms_alias_create(logical_id, props, stack_name):
if not target_key:
raise ValueError("AWS::KMS::Alias requires TargetKeyId")
_kms._aliases[_kms._alias_arn(alias_name)] = _kms_alias_target(target_key)
+ _kms._stamp_alias(_kms._alias_arn(alias_name), created=True)
return alias_name, {}
@@ -6866,11 +6867,13 @@ def _kms_alias_update(physical_id, old_props, new_props, stack_name, logical_id=
if not target_key:
raise ValueError("AWS::KMS::Alias requires TargetKeyId")
_kms._aliases[_kms._alias_arn(physical_id)] = _kms_alias_target(target_key)
+ _kms._stamp_alias(_kms._alias_arn(physical_id), created=False)
return physical_id, {}
def _kms_alias_delete(physical_id, props):
_kms._aliases.pop(_kms._alias_arn(physical_id), None)
+ _kms._alias_dates.pop(_kms._alias_arn(physical_id), None)
# --- EC2 resource provisioners ---
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index 9087678c..cdc6bf76 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -938,6 +938,8 @@ def _validate_data_plane_table_name(name) -> tuple | None:
if len(name) < 1:
return error_response_json("ValidationException",
f"1 validation error detected: Value '{name}' at 'tableName' failed to satisfy constraint: Member must have length greater than or equal to 1", 400)
+ if name.startswith("arn:"):
+ return None # A table ARN not in this account and region answers ResourceNotFoundException.
if len(name) > 255:
return error_response_json("ValidationException",
f"1 validation error detected: Value '{name}' at 'tableName' failed to satisfy constraint: Member must have length less than or equal to 255", 400)
@@ -1257,7 +1259,7 @@ def _create_table(data):
def _delete_table(data):
- name = data.get("TableName")
+ name = _normalize_table_name(data.get("TableName"))
if name not in _tables:
return error_response_json("ResourceNotFoundException", f"Requested resource not found: Table: {name} not found", 400)
if _tables[name].get("DeletionProtectionEnabled"):
@@ -1295,7 +1297,7 @@ def _list_tables(data):
def _update_table(data):
- name = data.get("TableName")
+ name = _normalize_table_name(data.get("TableName"))
if name not in _tables:
return error_response_json("ResourceNotFoundException", f"Requested resource not found: Table: {name} not found", 400)
table = _tables[name]
@@ -1636,7 +1638,7 @@ def _add_item_collection_metrics(result: dict, data: dict, table: dict, item: di
def _put_item(data):
- name = data.get("TableName")
+ name = _normalize_table_name(data.get("TableName"))
err = _validate_data_plane_table_name(name)
if err:
return err
@@ -1706,7 +1708,7 @@ def _put_item(data):
def _get_item(data):
- name = data.get("TableName")
+ name = _normalize_table_name(data.get("TableName"))
err = _validate_data_plane_table_name(name)
if err:
return err
@@ -1746,7 +1748,7 @@ def _get_item(data):
def _delete_item(data):
- name = data.get("TableName")
+ name = _normalize_table_name(data.get("TableName"))
err = _validate_data_plane_table_name(name)
if err:
return err
@@ -1806,7 +1808,7 @@ def _key_attribute_update_error(table, updated_attrs):
def _update_item(data):
- name = data.get("TableName")
+ name = _normalize_table_name(data.get("TableName"))
err = _validate_data_plane_table_name(name)
if err:
return err
@@ -1947,7 +1949,7 @@ def _update_item(data):
# ---------------------------------------------------------------------------
def _query(data):
- name = data.get("TableName")
+ name = _normalize_table_name(data.get("TableName"))
err = _validate_data_plane_table_name(name)
if err:
return err
@@ -2246,7 +2248,7 @@ def _query(data):
def _scan(data):
- name = data.get("TableName")
+ name = _normalize_table_name(data.get("TableName"))
err = _validate_data_plane_table_name(name)
if err:
return err
@@ -3854,7 +3856,7 @@ def _batch_write_item(data):
# in a single BatchWriteItem call.
seen_keys = set()
for table_name, requests in request_items.items():
- table = _tables.get(table_name)
+ table = _tables.get(_normalize_table_name(table_name))
if not table:
return error_response_json(
"ResourceNotFoundException",
@@ -3895,7 +3897,7 @@ def _batch_write_item(data):
seen_keys.add(key_repr)
unprocessed = {}
for table_name, requests in request_items.items():
- table = _tables.get(table_name)
+ table = _tables.get(_normalize_table_name(table_name))
if not table:
return error_response_json(
"ResourceNotFoundException",
@@ -3914,7 +3916,7 @@ def _batch_write_item(data):
return key_err
old_item = table["items"].get(pk_val, {}).get(sk_val)
table["items"][pk_val][sk_val] = item
- _emit_stream_event(table_name, "MODIFY" if old_item else "INSERT", old_item, item)
+ _emit_stream_event(_normalize_table_name(table_name), "MODIFY" if old_item else "INSERT", old_item, item)
_accumulate_write_capacity(cap, table, old_item, item)
elif "DeleteRequest" in req:
key = req["DeleteRequest"]["Key"]
@@ -3924,7 +3926,7 @@ def _batch_write_item(data):
old_item = table["items"].get(pk_val, {}).get(sk_val)
table["items"].get(pk_val, {}).pop(sk_val, None)
if old_item:
- _emit_stream_event(table_name, "REMOVE", old_item, None)
+ _emit_stream_event(_normalize_table_name(table_name), "REMOVE", old_item, None)
_accumulate_write_capacity(cap, table, old_item, None)
_update_counts(table)
result = {"UnprocessedItems": unprocessed}
@@ -3961,12 +3963,12 @@ def _batch_get_item(data):
f"1 validation error detected: Value at 'RequestItems.{_bg_table_name}.member.Keys' failed to satisfy constraint: Member must have length less than or equal to {_DDB_BATCH_GET_MAX}", 400)
# Non-existent table check before processing (AWS validates upfront).
for table_name in request_items:
- if table_name not in _tables:
+ if _normalize_table_name(table_name) not in _tables:
return error_response_json("ResourceNotFoundException",
"Requested resource not found", 400)
# Duplicate-key rejection.
for table_name, cfg in request_items.items():
- table = _tables[table_name]
+ table = _tables[_normalize_table_name(table_name)]
seen = set()
for key in cfg.get("Keys", []):
key_repr = (
@@ -3980,7 +3982,7 @@ def _batch_get_item(data):
responses = {}
unprocessed = {}
for table_name, config in request_items.items():
- table = _tables.get(table_name)
+ table = _tables.get(_normalize_table_name(table_name))
if not table:
unprocessed[table_name] = config
continue
@@ -4011,6 +4013,10 @@ def _batch_get_item(data):
def _transact_write_items(data):
items_list = data.get("TransactItems", [])
+ for _txn_item in items_list if isinstance(items_list, list) else []:
+ for _txn_op in (_txn_item.values() if isinstance(_txn_item, dict) else []):
+ if isinstance(_txn_op, dict) and "TableName" in _txn_op:
+ _txn_op["TableName"] = _normalize_table_name(_txn_op["TableName"])
if not items_list:
return error_response_json("ValidationException",
"1 validation error detected: Value '[]' at 'transactItems' failed to satisfy constraint: Member must have length greater than or equal to 1", 400)
@@ -4270,6 +4276,10 @@ _txn_idempotency = AccountRegionScopedDict()
def _transact_get_items(data):
items_list = data.get("TransactItems", [])
+ for _txn_item in items_list if isinstance(items_list, list) else []:
+ for _txn_op in (_txn_item.values() if isinstance(_txn_item, dict) else []):
+ if isinstance(_txn_op, dict) and "TableName" in _txn_op:
+ _txn_op["TableName"] = _normalize_table_name(_txn_op["TableName"])
if not items_list:
return error_response_json("ValidationException",
"1 validation error detected: Value '[]' at 'transactItems' failed to satisfy constraint: Member must have length greater than or equal to 1", 400)
@@ -4415,7 +4425,7 @@ def _transact_cancel_response(total, failures):
# ---------------------------------------------------------------------------
def _describe_ttl(data):
- name = data.get("TableName")
+ name = _normalize_table_name(data.get("TableName"))
if name not in _tables:
return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)
setting = _ttl_settings.get(name, {"TimeToLiveStatus": "DISABLED"})
@@ -4426,7 +4436,7 @@ def _describe_ttl(data):
def _update_ttl(data):
- name = data.get("TableName")
+ name = _normalize_table_name(data.get("TableName"))
if name not in _tables:
return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)
spec = data.get("TimeToLiveSpecification", {})
@@ -4447,7 +4457,7 @@ def _update_ttl(data):
# ---------------------------------------------------------------------------
def _describe_continuous_backups(data):
- name = data.get("TableName")
+ name = _normalize_table_name(data.get("TableName"))
if name not in _tables:
return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)
pitr_enabled = _pitr_settings.get(name, False)
@@ -4470,7 +4480,7 @@ def _describe_continuous_backups(data):
def _update_continuous_backups(data):
- name = data.get("TableName")
+ name = _normalize_table_name(data.get("TableName"))
if name not in _tables:
return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)
spec = data.get("PointInTimeRecoverySpecification", {})
@@ -4589,7 +4599,7 @@ _VALID_PRECISIONS = {"MILLISECOND", "MICROSECOND"}
def _validate_kinesis_destination_request(data: dict) -> tuple[str | None, str | None, dict | None]:
- table_name = data.get("TableName")
+ table_name = _normalize_table_name(data.get("TableName"))
stream_arn = data.get("StreamArn")
if not table_name:
return None, None, error_response_json("ValidationException", "The parameter 'TableName' is required but was not present in the request", 400)
@@ -4700,7 +4710,7 @@ def _disable_kinesis_streaming_destination(data):
def _describe_kinesis_streaming_destination(data):
- table_name = data.get("TableName")
+ table_name = _normalize_table_name(data.get("TableName"))
if not table_name:
return error_response_json("ValidationException", "The parameter 'TableName' is required but was not present in the request", 400)
if table_name not in _tables:
diff --git a/ministack/services/kms.py b/ministack/services/kms.py
index 270b8f54..b03b78a3 100644
--- a/ministack/services/kms.py
+++ b/ministack/services/kms.py
@@ -60,6 +60,7 @@ _keys = AccountRegionScopedDict()
# _hmac_key (bytes, HMAC_* only),
# }
_aliases = AccountRegionScopedDict() # alias ARN -> key_id
+_alias_dates = AccountRegionScopedDict() # alias ARN -> {CreationDate, LastUpdatedDate}
_HMAC_KEY_SPECS = {
"HMAC_224": ("HMAC_SHA_224", 28),
@@ -138,7 +139,7 @@ def get_state():
except Exception:
pass
serializable_keys._data[scoped_key] = entry
- return {"keys": serializable_keys, "aliases": _aliases}
+ return {"keys": serializable_keys, "aliases": _aliases, "alias_dates": _alias_dates}
def load_persisted_state(data):
@@ -224,6 +225,9 @@ def _restore_state(data):
else:
for alias_key, target_id in aliases_data.items():
_store_alias(get_account_id(), alias_key, target_id)
+ alias_dates = data.get("alias_dates")
+ if isinstance(alias_dates, AccountRegionScopedDict):
+ _alias_dates.update(alias_dates)
@@ -1395,6 +1399,7 @@ def _create_alias(data):
if alias_arn in _aliases:
return error_response_json("AlreadyExistsException", f"Alias {alias_name} already exists", 400)
_aliases[alias_arn] = rec["KeyId"]
+ _stamp_alias(alias_arn, created=True)
logger.info("Created alias %s -> %s", alias_name, rec["KeyId"])
return json_response({})
@@ -1405,6 +1410,7 @@ def _delete_alias(data):
if alias_arn not in _aliases:
return error_response_json("NotFoundException", f"Alias {alias_name} not found", 400)
del _aliases[alias_arn]
+ _alias_dates.pop(alias_arn, None)
return json_response({})
@@ -1422,10 +1428,13 @@ def _list_aliases(data):
rec = _resolve_key(key_id)
if not rec or rec["KeyId"] != target_id:
continue
+ dates = _alias_dates.get(alias_arn) or _stamp_alias(alias_arn, created=True)
items.append({
"AliasName": spec.resource,
"AliasArn": alias_arn,
"TargetKeyId": target_id,
+ "CreationDate": dates["CreationDate"],
+ "LastUpdatedDate": dates["LastUpdatedDate"],
})
return json_response({"Aliases": items, "Truncated": False})
@@ -1440,9 +1449,29 @@ def _update_alias(data):
if not rec:
return error_response_json("NotFoundException", f"Key {target_key_id} not found", 400)
_aliases[alias_arn] = rec["KeyId"]
+ _stamp_alias(alias_arn, created=False)
return json_response({})
+def _stamp_alias(alias_arn, created):
+ """Record an alias's CreationDate (kept on update) and LastUpdatedDate."""
+ now = int(time.time())
+ previous = None if created else _alias_dates.get(alias_arn)
+ dates = {"CreationDate": (previous or {}).get("CreationDate", now), "LastUpdatedDate": now}
+ _alias_dates[alias_arn] = dates
+ return dates
+
+
+def _list_grants(data):
+ # KeyId takes a key ID or key ARN only, not an alias. Grants are not
+ # modelled, so a key that exists has none.
+ key_id = data.get("KeyId", "")
+ rec = None if "alias/" in key_id else _resolve_key(key_id)
+ if not rec:
+ return error_response_json("NotFoundException", f"Key {key_id} not found", 400)
+ return json_response({"Grants": [], "Truncated": False})
+
+
# ---- Key Rotation ----
@@ -2011,6 +2040,7 @@ async def handle_request(method, path, headers, body, query_params):
"CreateAlias": _create_alias,
"DeleteAlias": _delete_alias,
"ListAliases": _list_aliases,
+ "ListGrants": _list_grants,
"UpdateAlias": _update_alias,
"EnableKeyRotation": _enable_key_rotation,
"DisableKeyRotation": _disable_key_rotation,
@@ -2043,3 +2073,4 @@ async def handle_request(method, path, headers, body, query_params):
def reset():
_keys.clear()
_aliases.clear()
+ _alias_dates.clear()
diff --git a/pyproject.toml b/pyproject.toml
index b6181e69..5e8a732d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.5.17"
+version = "1.5.18"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.py
index d25ec6db..ad0dbb41 100644
--- a/tests/test_dynamodb.py
+++ b/tests/test_dynamodb.py
@@ -134,6 +134,51 @@ def test_dynamodb_describe_table_accepts_table_arn(ddb):
pass
+def test_dynamodb_table_arn_accepted_by_every_table_name_operation(ddb):
+ """Every operation whose TableName is a TableArn in the model takes the ARN;
+ batch responses keep the caller's key form, and a foreign ARN is not found."""
+ name = f"arn-ops-{_uuid_mod.uuid4().hex[:8]}"
+ ddb.create_table(
+ TableName=name,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ arn = ddb.describe_table(TableName=name)["Table"]["TableArn"]
+ key = {"pk": {"S": "a"}}
+ try:
+ ddb.put_item(TableName=arn, Item={"pk": {"S": "a"}, "v": {"S": "1"}})
+ assert ddb.get_item(TableName=arn, Key=key)["Item"]["v"] == {"S": "1"}
+ ddb.update_item(TableName=arn, Key=key, UpdateExpression="SET v = :v",
+ ExpressionAttributeValues={":v": {"S": "2"}})
+ assert ddb.query(TableName=arn, KeyConditionExpression="pk = :p",
+ ExpressionAttributeValues={":p": {"S": "a"}})["Count"] == 1
+ assert ddb.scan(TableName=arn)["Count"] == 1
+ got = ddb.batch_get_item(RequestItems={arn: {"Keys": [key]}})
+ assert list(got["Responses"]) == [arn]
+ ddb.batch_write_item(RequestItems={arn: [{"PutRequest": {"Item": {"pk": {"S": "b"}}}}]})
+ ddb.transact_write_items(TransactItems=[{"Put": {"TableName": arn, "Item": {"pk": {"S": "c"}}}}])
+ items = ddb.transact_get_items(TransactItems=[{"Get": {"TableName": arn, "Key": {"pk": {"S": "c"}}}}])
+ assert items["Responses"][0]["Item"]["pk"] == {"S": "c"}
+ ddb.delete_item(TableName=arn, Key=key)
+ ddb.update_time_to_live(TableName=arn, TimeToLiveSpecification={"Enabled": True, "AttributeName": "ttl"})
+ assert ddb.describe_time_to_live(TableName=arn)["TimeToLiveDescription"]["AttributeName"] == "ttl"
+ ddb.update_continuous_backups(TableName=arn, PointInTimeRecoverySpecification={"PointInTimeRecoveryEnabled": True})
+ assert ddb.describe_continuous_backups(TableName=arn)["ContinuousBackupsDescription"]
+ assert ddb.describe_kinesis_streaming_destination(TableName=arn)["TableName"] == name
+ ddb.update_table(TableName=arn, BillingMode="PAY_PER_REQUEST")
+ other_region_arn = arn.replace(":us-east-1:", ":eu-west-1:")
+ with pytest.raises(ClientError) as e:
+ ddb.get_item(TableName=other_region_arn, Key=key)
+ assert e.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ ddb.delete_table(TableName=arn)
+ finally:
+ try:
+ ddb.delete_table(TableName=name)
+ except ClientError:
+ pass
+
+
def test_dynamodb_same_name_table_metadata_is_region_scoped(ddb):
east = _ddb_client("us-east-1")
west = _ddb_client("us-west-2")
@@ -2574,8 +2619,10 @@ def test_ddb_sse_description_shape_matches_aws(ddb, kms_client):
key_id = kms_client.create_key(Description="ddb-sse-t")["KeyMetadata"]["KeyId"]
key_arn = f"arn:aws:kms:us-east-1:000000000000:key/{key_id}"
tname = "t-sse-shape"
- try: ddb.delete_table(TableName=tname)
- except Exception: pass
+ try:
+ ddb.delete_table(TableName=tname)
+ except Exception:
+ pass
ddb.create_table(
TableName=tname,
diff --git a/tests/test_firehose.py b/tests/test_firehose.py
index 0dc427c3..bde325f6 100644
--- a/tests/test_firehose.py
+++ b/tests/test_firehose.py
@@ -575,10 +575,14 @@ def test_firehose_lambda_processor_transforms_record(fh, s3, lam):
body = s3.get_object(Bucket=bucket, Key=objs[0]["Key"])["Body"].read()
assert body == b"HELLO", body
finally:
- try: fh.delete_delivery_stream(DeliveryStreamName=delivery)
- except Exception: pass
- try: lam.delete_function(FunctionName=fn)
- except Exception: pass
+ try:
+ fh.delete_delivery_stream(DeliveryStreamName=delivery)
+ except Exception:
+ pass
+ try:
+ lam.delete_function(FunctionName=fn)
+ except Exception:
+ pass
def test_firehose_lambda_processor_dropped_record_not_written(fh, s3, lam):
@@ -603,10 +607,14 @@ def test_firehose_lambda_processor_dropped_record_not_written(fh, s3, lam):
objs = s3.list_objects_v2(Bucket=bucket, Prefix="out/").get("Contents", [])
assert objs == [], f"expected no S3 objects, got {objs}"
finally:
- try: fh.delete_delivery_stream(DeliveryStreamName=delivery)
- except Exception: pass
- try: lam.delete_function(FunctionName=fn)
- except Exception: pass
+ try:
+ fh.delete_delivery_stream(DeliveryStreamName=delivery)
+ except Exception:
+ pass
+ try:
+ lam.delete_function(FunctionName=fn)
+ except Exception:
+ pass
def test_firehose_lambda_processor_not_found_passes_through(fh, s3):
@@ -632,8 +640,10 @@ def test_firehose_lambda_processor_not_found_passes_through(fh, s3):
body = s3.get_object(Bucket=bucket, Key=objs[0]["Key"])["Body"].read()
assert body == b"untouched"
finally:
- try: fh.delete_delivery_stream(DeliveryStreamName=delivery)
- except Exception: pass
+ try:
+ fh.delete_delivery_stream(DeliveryStreamName=delivery)
+ except Exception:
+ pass
def test_firehose_kinesis_source_with_lambda_processor(fh, s3, lam, kin):
@@ -682,12 +692,18 @@ def test_firehose_kinesis_source_with_lambda_processor(fh, s3, lam, kin):
body = s3.get_object(Bucket=bucket, Key=objs[0]["Key"])["Body"].read()
assert body == b"proc:payload", body
finally:
- try: fh.delete_delivery_stream(DeliveryStreamName=delivery)
- except Exception: pass
- try: lam.delete_function(FunctionName=fn)
- except Exception: pass
- try: kin.delete_stream(StreamName=stream)
- except Exception: pass
+ try:
+ fh.delete_delivery_stream(DeliveryStreamName=delivery)
+ except Exception:
+ pass
+ try:
+ lam.delete_function(FunctionName=fn)
+ except Exception:
+ pass
+ try:
+ kin.delete_stream(StreamName=stream)
+ except Exception:
+ pass
def test_firehose_same_name_streams_are_region_scoped(fh):
diff --git a/tests/test_kms.py b/tests/test_kms.py
index f95c326e..87967f14 100644
--- a/tests/test_kms.py
+++ b/tests/test_kms.py
@@ -2421,3 +2421,32 @@ def test_kms_delete_imported_material_clears_the_asymmetric_key():
with pytest.raises(ClientError) as exc:
kms.get_public_key(KeyId=key_id)
assert exc.value.response["Error"]["Code"] == "KMSInvalidStateException"
+
+
+def test_kms_alias_carries_creation_and_last_updated_dates(kms_client):
+ first = kms_client.create_key()["KeyMetadata"]["KeyId"]
+ second = kms_client.create_key()["KeyMetadata"]["KeyId"]
+ alias = f"alias/dates-{_uuid_mod.uuid4().hex[:8]}"
+ kms_client.create_alias(AliasName=alias, TargetKeyId=first)
+ try:
+ entry = next(a for a in kms_client.list_aliases()["Aliases"] if a["AliasName"] == alias)
+ assert isinstance(entry["CreationDate"], _dt.datetime)
+ assert entry["LastUpdatedDate"] == entry["CreationDate"]
+ time.sleep(1.1)
+ kms_client.update_alias(AliasName=alias, TargetKeyId=second)
+ updated = next(a for a in kms_client.list_aliases()["Aliases"] if a["AliasName"] == alias)
+ assert updated["CreationDate"] == entry["CreationDate"]
+ assert updated["LastUpdatedDate"] > entry["LastUpdatedDate"]
+ finally:
+ kms_client.delete_alias(AliasName=alias)
+
+
+def test_kms_list_grants(kms_client):
+ meta = kms_client.create_key()["KeyMetadata"]
+ for key_ref in (meta["KeyId"], meta["Arn"]):
+ resp = kms_client.list_grants(KeyId=key_ref)
+ assert resp["Grants"] == [] and resp["Truncated"] is False
+ for missing in ("00000000-0000-0000-0000-000000000000", "alias/does-not-matter"):
+ with pytest.raises(ClientError) as exc:
+ kms_client.list_grants(KeyId=missing)
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
diff --git a/tests/test_multitenancy.py b/tests/test_multitenancy.py
index a295d584..d11e4a82 100644
--- a/tests/test_multitenancy.py
+++ b/tests/test_multitenancy.py
@@ -172,8 +172,10 @@ def test_athena_workgroups_isolated_per_account():
assert wg not in names_b, \
f"CRITICAL: Athena workgroup leaking cross-account; B saw: {names_b}"
finally:
- try: a.delete_work_group(WorkGroup=wg)
- except Exception: pass
+ try:
+ a.delete_work_group(WorkGroup=wg)
+ except Exception:
+ pass
def test_ses_sent_emails_isolated_per_account():
@@ -229,8 +231,10 @@ def test_apigateway_v1_stages_isolated_per_account():
assert all(api["id"] != a_api for api in apis_b), \
f"CRITICAL: APIGW v1 REST api leaking cross-account; B saw: {apis_b}"
finally:
- try: a.delete_rest_api(restApiId=a_api)
- except Exception: pass
+ try:
+ a.delete_rest_api(restApiId=a_api)
+ except Exception:
+ pass
def test_post_object_uses_the_account_from_the_form_credentials():
import requests
diff --git a/tests/test_rds.py b/tests/test_rds.py
index 27d23476..40380945 100644
--- a/tests/test_rds.py
+++ b/tests/test_rds.py
@@ -1,8 +1,8 @@
import asyncio
import contextlib
import datetime
-import ipaddress
import io
+import ipaddress
import json
import os
import socket
diff --git a/tests/test_sns.py b/tests/test_sns.py
index 73ca60ed..fc975050 100644
--- a/tests/test_sns.py
+++ b/tests/test_sns.py
@@ -12,7 +12,6 @@ import boto3
import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
-
from conftest import sqs_policy_allow_sns
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")