Skip to content

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

release v1.5.24 (#2105)

Nahuel Nucera22753eccba36
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8d9798e6..fe58d9b5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,9 +7,24 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
-### Fixed
+## [1.5.24] — 2026-10-08
+
+### Added
+- **API Gateway v1 — richer SQS request templates** — templates now support `#set`, `##` and `#* *#` comments, quiet `$!` references, double-quoted strings with interpolation and `""` escapes, and `$context.authorizer` values including Cognito claims. Reported by @teruyukisuda.
-- **Lambda — local Node.js console logs** — the one-shot local executor mixed `console.log()`, `console.info()` and other stdout output into the Invoke response, and omitted them from invocation logs. It now sends handler stdout/stderr output, including `fs.writeSync(1, ...)` and `fs.write(1, ...)`, to the log channel and reserves stdout for the JSON return value, including logs written during module initialization.
+### Fixed
+- **API Gateway — `CreateApiKey` keeps `value` and `customerId`** — the key always got a generated value. A value under 20 characters returns `BadRequestException` "API Key value should be at least 20 characters". Reported by @mjuen.
+- **CloudWatch — CBOR timestamps** — timestamps from clients using the CBOR protocol are now read as UTC. Reported by @DimQ1.
+- **Container reaping — failed removals are logged** — containers the reaper could not remove are logged at `WARNING` with their ids. Reported by @iot-rocket.
+- **DynamoDB Streams — iterator expiry and `GetRecords` limits** — shard iterators expire after 15 minutes with `ExpiredIteratorException`, a page stops at 1 MB, a position behind the trim horizon returns `TrimmedDataAccessException`, and an unknown shard returns `ResourceNotFoundException`. Reported by @DimQ1.
+- **Lambda — a returned string is JSON-encoded** — `Invoke` returned `hello` instead of `"hello"`. Reported by @edu-shippo.
+- **Lambda — local Node.js console logs** — the one-shot local executor mixed stdout into the `Invoke` response. Logs now go to the invocation log and stdout carries only the return value. Contributed by @gakuto-cw21.
+- **Pipes — SNS FIFO targets are refused** — `CreatePipe` and `UpdatePipe` now return "SNS FIFO topics are not supported as a pipe target.". Reported by @DimQ1.
+- **S3 Tables — Iceberg REST catalogs and commits** — every catalog read the first catalog's warehouse; each is now scoped to its table bucket ARN. Commits now check update requirements (`CommitFailedException`, 409) and keep snapshot sequence numbers consistent.
+- **SES — non-ASCII addresses** — an address with non-ASCII characters returns `InvalidParameterValue` "Missing final '@domain'". Reported by @DimQ1.
+- **SNS — filter policies** — `FilterPolicyScope` `MessageBody` was ignored and `suffix` and `equals-ignore-case` never matched. Both scopes now apply, with `wildcard`, `cidr` and `"exists": false` too. Reported by @DimQ1.
+- **SQS — retention and dead-letter moves** — messages now expire after `MessageRetentionPeriod`. A message moved to a dead-letter queue keeps its enqueue time on standard queues and carries `DeadLetterQueueSourceArn`. Reported by @DimQ1.
+- **Step Functions — a Lambda that returns `null` outputs `null`** — the Task output was `{}`. Reported by @edu-shippo.
## [1.5.23] — 2026-10-07
diff --git a/README.md b/README.md
index 001b0594..f4974292 100644
--- a/README.md
+++ b/README.md
@@ -403,10 +403,10 @@ 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 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, 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` |
+| **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, with moved messages carrying `DeadLetterQueueSourceArn`; messages expire after `MessageRetentionPeriod`; 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, 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); subscription filter policies on message attributes or, with `FilterPolicyScope` `MessageBody`, the message body (`prefix`, `suffix`, `equals-ignore-case`, `wildcard`, `anything-but`, `numeric`, `cidr`, `exists`); 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 every write that changes an item, respects `StreamViewType`; `Query` and `Scan` pages stop at 1 MB of data read; GSIs accept multi-attribute keys (up to four `HASH` and four `RANGE` attributes); Kinesis streaming destinations (`aws_dynamodb_kinesis_streaming_destination`) fan item mutations out into any Kinesis stream by ARN while the destination is ACTIVE; global tables (version 2019.11.21) through `UpdateTable` `ReplicaUpdates`: a replica is a copy of the table in the other region, and writes replicate between them |
-| **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; a disabled stream, or the stream of a deleted table, stays readable for 24 hours as `DISABLED` |
+| **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 that expire after 15 minutes; `GetRecords` pages stop at 1,000 records or 1 MB; a disabled stream, or the stream of a deleted table, stays readable for 24 hours as `DISABLED` |
| **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) |
| **IAM** | CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles, DeleteRole, UpdateRoleDescription, PutRolePermissionsBoundary, DeleteRolePermissionsBoundary, CreatePolicy, GetPolicy, DeletePolicy, AttachRolePolicy, DetachRolePolicy, PutRolePolicy, GetRolePolicy, DeleteRolePolicy, ListRolePolicies, ListAttachedRolePolicies, CreateAccessKey, ListAccessKeys, DeleteAccessKey, UpdateAccessKey, GetAccessKeyLastUsed, CreateInstanceProfile, GetInstanceProfile, DeleteInstanceProfile, AddRoleToInstanceProfile, RemoveRoleFromInstanceProfile, ListInstanceProfiles, TagInstanceProfile, UntagInstanceProfile, ListInstanceProfileTags, CreateGroup, GetGroup, AddUserToGroup, RemoveUserFromGroup, AttachGroupPolicy, DetachGroupPolicy, ListAttachedGroupPolicies, PutGroupPolicy, GetGroupPolicy, DeleteGroupPolicy, ListGroupPolicies, CreateServiceLinkedRole, DeleteServiceLinkedRole, GetServiceLinkedRoleDeletionStatus, CreateOpenIDConnectProvider, ListOpenIDConnectProviders, CreateSAMLProvider, GetSAMLProvider, ListSAMLProviders, UpdateSAMLProvider, DeleteSAMLProvider, CreateLoginProfile, GetLoginProfile, UpdateLoginProfile, DeleteLoginProfile, CreateVirtualMFADevice, EnableMFADevice, DeactivateMFADevice, ResyncMFADevice, ListMFADevices, ListVirtualMFADevices, DeleteVirtualMFADevice, GetAccountAuthorizationDetails, GenerateServiceLastAccessedDetails, GetServiceLastAccessedDetails, TagRole, UntagRole, TagUser, UntagUser, TagPolicy, UntagPolicy, GenerateCredentialReport, GetCredentialReport, GetAccountSummary, GetAccountPasswordPolicy, UpdateAccountPasswordPolicy, DeleteAccountPasswordPolicy, ListAccountAliases, CreateAccountAlias, DeleteAccountAlias | Role descriptions and permissions boundaries round-trip through role reads; boundaries support put/delete updates. |
| **STS** | GetCallerIdentity, AssumeRole, GetSessionToken, AssumeRoleWithWebIdentity | |
@@ -439,7 +439,7 @@ subnet = ec2.create_subnet(
| **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 |
| **Step Functions** | CreateStateMachine, DeleteStateMachine, DescribeStateMachine, UpdateStateMachine, ListStateMachines, StartExecution, StartSyncExecution, StopExecution, DescribeExecution, DescribeStateMachineForExecution, ListExecutions, GetExecutionHistory, SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat, CreateActivity, DeleteActivity, DescribeActivity, ListActivities, GetActivityTask, TestState, TagResource, UntagResource, ListTagsForResource | Full ASL interpreter; Retry/Catch; waitForTaskToken; Activities (worker pattern); Pass/Task/Choice/Wait/Succeed/Fail/Map/Parallel; TestState API with mock and inspectionLevel support; SFN_MOCK_CONFIG for AWS SFN Local compatible mock testing; intrinsic functions (States.StringToJson, States.JsonToString, States.JsonMerge, States.Format); nested startExecution.sync |
| **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, CreateDomainName, GetDomainName, GetDomainNames, UpdateDomainName, DeleteDomainName, CreateApiMapping, GetApiMapping, GetApiMappings, UpdateApiMapping, DeleteApiMapping, 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; custom domain names and API mappings shared with API Gateway v1, routed by `Host`; 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, Lambda request mapping templates not modeled) and non-proxy `AWS` integrations whose URI targets SQS (`arn:aws:apigateway:{region}:sqs:path/{account}/{queue}`: the request template subset `$input.body` / `$input.json('…')` / `$input.params('…')` / `$util.urlEncode(…)` renders the form-encoded SQS Query call, run in the URI's account and region, and the backend result or error is mapped through `integrationResponses`), 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 |
+| **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, Lambda request mapping templates not modeled) and non-proxy `AWS` integrations whose URI targets SQS (`arn:aws:apigateway:{region}:sqs:path/{account}/{queue}`: a request template subset — `$input.body` / `$input.json('…')` / `$input.params('…')` / `$util.urlEncode(…)`, `$context.authorizer` values including Cognito claims, `#set`, comments and interpolated strings — renders the form-encoded SQS Query call, run in the URI's account and region, and the backend result or error is mapped through `integrationResponses`), 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, CreateGrant, ListGrants, RevokeGrant, RetireGrant | 41 actions; multi-Region keys: `CreateKey` with `MultiRegion` mints an `mrk-` key and `ReplicateKey` creates a same-id replica in another region sharing the key material (ciphertext from the primary decrypts against the replica; a primary with live replicas waits in `PendingReplicaDeletion`); CMK specs: RSA (2048/3072/4096), ECC (SECG_P256K1, NIST P-256/384/521), Edwards25519 (`ECC_NIST_EDWARDS25519` — pure Ed25519 via `ED25519_SHA_512` with `MessageType=RAW`; `ED25519_PH_SHA_512` advertised in `SigningAlgorithms` but returns `UnsupportedOperationException` until Ed25519ph lands), HMAC (`HMAC_224`/`HMAC_256`/`HMAC_384`/`HMAC_512` with `KeyUsage=GENERATE_VERIFY_MAC`), and symmetric keys; PKCS1v15, PSS, and ECDSA signing; real RFC 2104 HMAC via `GenerateMac`/`VerifyMac` (4096-byte message cap, `KMSInvalidMacException` on mismatch, `DryRun` supported); envelope encryption, incl. asymmetric data key pairs (`KeyPairSpec` adds RSA_3072); alias resolution; key rotation; key policies; tags; enable/disable/schedule deletion; grants (stored and listed, not evaluated for authorization); full Terraform `aws_kms_key` compatible; `cryptography` package included in Docker image |
| **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, CreateMonitoringSubscription, GetMonitoringSubscription, DeleteMonitoringSubscription, 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; the AWS-managed cache (7), origin request (8) and response headers (5) policies are listed and immutable; `CreateMonitoringSubscription` upserts; functions keep DEVELOPMENT/LIVE stages and `KeyValueStoreAssociations`, and `UpdateFunction` clears LIVE until `PublishFunction` runs again; **data plane**: a request to a distribution's `DomainName` (`d` + 13 characters, or `<label>.cloudfront.<MINISTACK_HOST>`) is served through its cache behaviors, policies, `viewer-request` / `viewer-response` CloudFront Functions (on Node) and an S3 or custom origin (read only as the bucket policy allows: OAC, OAI or public), with custom error responses for origin errors; not modelled: caching, WAF, logging, geo restrictions, signed URLs, Lambda@Edge, CORS preflight, and origins at AWS hostnames (502); **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 |
@@ -625,7 +625,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i
| **Aurora DSQL** | CreateCluster, GetCluster, UpdateCluster, DeleteCluster, ListClusters, PutClusterPolicy, GetClusterPolicy, DeleteClusterPolicy, CreateStream, GetStream, ListStreams, DeleteStream, GetVpcEndpointServiceName, TagResource, UntagResource, ListTagsForResource | `CreateCluster` spins up a real `postgres:16-alpine` Docker container fronted by a validating PG wire-protocol proxy that **fails like real DSQL** — rejects unsupported SQL (`serial`, extensions, temp tables, ...), accepts `CREATE INDEX ASYNC` + `sys.jobs`; endpoint is `localhost:<port>`; any password accepted |
| **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, CreateServerlessCache, DescribeServerlessCaches, ModifyServerlessCache, DeleteServerlessCache, DescribeEvents | `CreateCacheCluster` spins up a real Redis, Valkey, or Memcached Docker container (`Engine=redis`/`valkey`/`memcached`); a serverless cache gets a TLS-only, single-shard cluster-mode Valkey/Redis container whose certificate chains to the CA at `GET /_ministack/elasticache/ca.pem` |
| **Glue** | CreateDatabase, DeleteDatabase, GetDatabase, GetDatabases, UpdateDatabase, CreateTable, DeleteTable, GetTable, GetTables, UpdateTable, BatchDeleteTable, CreatePartition, DeletePartition, GetPartition, GetPartitions, BatchCreatePartition, BatchGetPartition, CreatePartitionIndex, GetPartitionIndexes, GetColumnStatisticsForTable, UpdateColumnStatisticsForTable, DeleteColumnStatisticsForTable, GetColumnStatisticsForPartition, UpdateColumnStatisticsForPartition, DeleteColumnStatisticsForPartition, 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, CreateUserDefinedFunction, UpdateUserDefinedFunction, DeleteUserDefinedFunction, GetUserDefinedFunction, GetUserDefinedFunctions, CreateSecurityConfiguration, DeleteSecurityConfiguration, GetSecurityConfiguration, GetSecurityConfigurations, CreateClassifier, GetClassifier, GetClassifiers, DeleteClassifier, TagResource, UntagResource, GetTags | Python shell jobs actually execute via subprocess; Spark jobs run on the official `amazon/aws-glue-libs` PySpark image (`GlueVersion: 4.0` / `3.0`) on MiniStack's Docker network; Glue-backed Iceberg REST catalog at `/iceberg` (signed with the `glue` credential scope, prefix `catalogs/{catalog}`) — read path for tables whose `metadata_location` parameter points at a metadata.json on MiniStack S3, e.g. DuckDB `ATTACH ... (TYPE iceberg, ENDPOINT 'localhost:4566/iceberg', AUTHORIZATION_TYPE 'sigv4')` with `USE_SSL=1` |
-| **S3 Tables** | CreateTableBucket, ListTableBuckets, GetTableBucket, DeleteTableBucket, CreateNamespace, ListNamespaces, GetNamespace, DeleteNamespace, CreateTable, ListTables, GetTable, DeleteTable, GetTableMetadataLocation, UpdateTableMetadataLocation | Iceberg-format tables; embedded Iceberg REST catalog at `/iceberg` so Spark jobs (`spark.sql.catalog.*.type=rest`) can create / load / commit without an external catalog; data files in S3, metadata in memory |
+| **S3 Tables** | CreateTableBucket, ListTableBuckets, GetTableBucket, DeleteTableBucket, CreateNamespace, ListNamespaces, GetNamespace, DeleteNamespace, CreateTable, ListTables, GetTable, DeleteTable, GetTableMetadataLocation, UpdateTableMetadataLocation | Iceberg-format tables; embedded Iceberg REST catalog at `/iceberg` so Spark jobs (`spark.sql.catalog.*.type=rest`) can create / load / commit without an external catalog, each catalog scoped to the table bucket ARN in its prefix and commits checked against their update requirements; data files in S3, metadata in memory |
| **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, GetDatabase, ListDatabases, GetTableMetadata, ListTableMetadata, TagResource, UntagResource, ListTagsForResource | Real SQL via **DuckDB** when installed (`pip install duckdb`), otherwise returns mock results; databases and tables come from the Glue Data Catalog, and `CREATE EXTERNAL TABLE` / `DROP TABLE` change it; 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`; `DeliveryStreamType=KinesisStreamAsSource` consumes records from the source Kinesis stream on `PutRecord` / `PutRecords` and forwards them to the configured S3 destination, honoring `Prefix` and `DeliveryStartTimestamp`; `ProcessingConfiguration.Processors[].Type=Lambda` invoked per-batch with the AWS-shape event (`{invocationId, deliveryStreamArn, region, records:[{recordId, approximateArrivalTimestamp, data}]}`) — `Ok` records ship the transformed data downstream, `Dropped`/`ProcessingFailed` are omitted, Lambda failures pass records through unchanged (best-effort per AWS) |
| **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 |
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 1eab1bb1..bec7a143 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -3156,9 +3156,11 @@ async def _invoke(name: str, event: dict, headers: dict, path_qualifier: str | N
payload = result.get("body")
if payload is None:
return 200, resp_headers, b"null"
- if isinstance(payload, (str, bytes)):
- raw = payload.encode("utf-8") if isinstance(payload, str) else payload
- return 200, resp_headers, raw
+ if isinstance(payload, bytes):
+ return 200, resp_headers, payload
+ if isinstance(payload, str) and (result.get("raw_payload") or result.get("error")):
+ return 200, resp_headers, payload.encode("utf-8")
+ # A returned string is serialized like any other value: "hello" -> "\"hello\"".
return 200, resp_headers, json.dumps(payload, ensure_ascii=False).encode("utf-8")
@@ -4029,16 +4031,19 @@ def _invoke_rie(container, event: dict, timeout: int, request_id: str) -> dict:
)
resp = urllib.request.urlopen(req, timeout=timeout)
body = resp.read().decode("utf-8", errors="replace")
+ raw_payload = False
try:
parsed = json.loads(body)
except json.JSONDecodeError:
- parsed = body
+ parsed, raw_payload = body, True
logs = container.logs(stdout=True, stderr=True, since=invoke_time).decode("utf-8", errors="replace").strip()
err_header = (resp.headers.get("X-Amz-Function-Error")
or resp.headers.get("Lambda-Runtime-Function-Error-Type") or "")
# RIE owns the platform lines, including handler errors returned as HTTP 200.
# Carry provenance separately so user output never controls log wrapping.
result = {"body": parsed, "log": logs, "log_source": "rie"}
+ if raw_payload:
+ result["raw_payload"] = True
function_error = _classify_function_error(parsed, err_header)
if function_error is not None:
result["error"] = True
@@ -5261,7 +5266,7 @@ def _execute_function_proxy(func: dict, event: dict, url: str, request_id: str)
try:
return {"body": json.loads(text)}
except json.JSONDecodeError:
- return {"body": text}
+ return {"body": text, "raw_payload": True}
def _execute_function_warm(func: dict, event: dict, request_id: str) -> dict:
@@ -5498,6 +5503,7 @@ def _execute_function_provided(func: dict, event: dict, request_id: str) -> dict
result_holder["response"] = json.loads(body)
except json.JSONDecodeError:
result_holder["response"] = body.decode("utf-8", errors="replace")
+ result_holder["raw_payload"] = True
self.send_response(202)
self.end_headers()
response_received.set()
@@ -5576,7 +5582,8 @@ def _execute_function_provided(func: dict, event: dict, request_id: str) -> dict
if isinstance(err, dict):
return {"body": err, "error": True}
return {"body": {"errorMessage": str(err), "errorType": "Runtime.HandlerError"}, "error": True}
- return {"body": result_holder["response"]}
+ return {"body": result_holder["response"],
+ "raw_payload": result_holder.get("raw_payload", False)}
else:
proc.kill()
stdout, stderr = proc.communicate(timeout=5)
@@ -5732,7 +5739,7 @@ def _execute_function_local(func: dict, event: dict, request_id: str) -> dict:
try:
return {"body": json.loads(stdout), "log": log_tail}
except json.JSONDecodeError:
- return {"body": stdout, "log": log_tail}
+ return {"body": stdout, "log": log_tail, "raw_payload": True}
else:
return {
"body": {
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index 025acc59..2dcd79b4 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -1996,7 +1996,7 @@ def _call_lambda(func_ref, event):
body = result.get("body")
if body is None:
- return {}
+ return None
if isinstance(body, (dict, list)):
return body
try:
diff --git a/pyproject.toml b/pyproject.toml
index d17b86e5..5b5f663d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.5.23"
+version = "1.5.24"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 3de3d7d5..4bf50f78 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -1152,6 +1152,24 @@ def test_lambda_invoke(lam):
assert payload["statusCode"] == 200
assert payload["body"] == "ok"
[email protected]("returned,expected", [
+ ("'hello'", b'"hello"'), ("None", b"null"), ("[1, 'a']", b'[1, "a"]'), ("7", b"7"),
+])
+def test_lambda_invoke_payload_is_the_json_of_the_return_value(lam, returned, expected):
+ fname = f"lam-json-ret-{_uuid_mod.uuid4().hex[:8]}"
+ lam.create_function(FunctionName=fname, Runtime="python3.12", Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(f"def handler(event, context):\n return {returned}\n")})
+ try:
+ assert lam.invoke(FunctionName=fname)["Payload"].read() == expected
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_invoke_node_string_return_is_json_encoded(lam):
+ with _nodejs_lambda(lam, "exports.handler = async () => 'hello';\n") as fname:
+ assert lam.invoke(FunctionName=fname)["Payload"].read() == b'"hello"'
+
def test_lambda_invoke_async(lam):
resp = lam.invoke(
FunctionName="lam-invoke-test",
@@ -14709,3 +14727,119 @@ def test_real_docker_invocations_have_one_platform_log_sequence(monkeypatch, log
spawn.assert_called_once() # The second invocation must reuse the environment.
finally:
_svc._pool_kill_function("000000000000", func["config"]["FunctionName"])
+
+
+# One-shot local Node executor, bypassing warm workers.
+
+def _local_node_function(source, *, filename="index.js"):
+ name = "local-node-logs-" + _uuid_mod.uuid4().hex
+ archive = io.BytesIO()
+ with zipfile.ZipFile(archive, "w") as package:
+ package.writestr(filename, source)
+ return {
+ "config": {
+ "FunctionName": name,
+ "FunctionArn": _svc._func_arn(name),
+ "Runtime": "nodejs20.x",
+ "Handler": "index.handler",
+ "MemorySize": 128,
+ "Timeout": 10,
+ },
+ "code_zip": archive.getvalue(),
+ }
+
+
+def _invoke_local_node(source, event=None, *, filename="index.js"):
+ # Dispatch normally prefers a warm worker for Node. Call the one-shot
+ # fallback directly so a working warm executor cannot hide this regression.
+ return _svc._execute_function_local(
+ _local_node_function(source, filename=filename),
+ event if event is not None else {},
+ request_id=_uuid_mod.uuid4().hex,
+ )
+
+
[email protected](shutil.which("node") is None, reason="Node.js is not installed")
[email protected]("filename,export", [("index.js", "exports.handler ="), ("index.mjs", "export const handler =")])
+def test_local_node_stdout_uses_log_channel(filename, export):
+ source = "console.log('module-initialization');\n" + export + """ async (event) => {
+ console.log('log-message');
+ console.info('info-message');
+ console.debug('debug-message');
+ console.warn('warn-message');
+ console.error('error-message');
+ process.stdout.write('stdout-message\\n');
+ process.stderr.write('stderr-message\\n');
+ await new Promise(resolve => setTimeout(resolve, 10));
+ console.log('after-await-message');
+ return {ok: true, event};
+};
+"""
+ result = _invoke_local_node(source, {"value": 42}, filename=filename)
+
+ assert not result.get("error")
+ assert result["body"] == {"ok": True, "event": {"value": 42}}
+ assert result["log"].splitlines() == [
+ "module-initialization", "log-message", "info-message", "debug-message", "warn-message",
+ "error-message", "stdout-message", "stderr-message", "after-await-message",
+ ]
+
+
[email protected](shutil.which("node") is None, reason="Node.js is not installed")
[email protected]("filename,imports,export", [
+ ("index.js", "const {writeSync, write} = require('fs');", "exports.handler ="),
+ ("index.mjs", "import {writeSync, write} from 'node:fs';", "export const handler ="),
+])
+def test_local_node_fd_stdout_uses_log_channel(filename, imports, export):
+ source = imports + "\n" + export + """ async () => {
+ writeSync(1, 'fd-message\\n');
+ writeSync(1, JSON.stringify({level: 30, msg: 'pino-message'}) + '\\n');
+ await new Promise((resolve, reject) =>
+ write(1, 'async-fd-message\\n', err => err ? reject(err) : resolve()));
+ const fs = await import('node:fs');
+ const fd = fs.openSync('fd-output.txt', 'w');
+ try {
+ writeSync(fd, 'sync-file');
+ await new Promise((resolve, reject) =>
+ write(fd, Buffer.from('-async-file'), err => err ? reject(err) : resolve()));
+ } finally {
+ fs.closeSync(fd);
+ }
+ return {ok: true, file: fs.readFileSync('fd-output.txt', 'utf8')};
+};
+"""
+ result = _invoke_local_node(source, filename=filename)
+
+ assert not result.get("error")
+ assert result["body"] == {"ok": True, "file": "sync-file-async-file"}
+ messages = result["log"].splitlines()
+ assert messages[0] == "fd-message"
+ assert json.loads(messages[1]) == {"level": 30, "msg": "pino-message"}
+ assert messages[2] == "async-fd-message"
+ assert len(messages) == 3
+
+
[email protected](shutil.which("node") is None, reason="Node.js is not installed")
+def test_local_node_logs_reach_invoke_tail(monkeypatch):
+ function = _local_node_function("""
+exports.handler = async () => {
+ console.log('invoke-console-message');
+ console.error('invoke-stderr-message');
+ return {ok: true};
+};
+""")
+ name = function["config"]["FunctionName"]
+ monkeypatch.setitem(_svc._functions, name, function)
+ monkeypatch.setattr(_svc, "LAMBDA_EXECUTOR", "local")
+ monkeypatch.setattr(_svc, "LAMBDA_STRICT", False)
+ monkeypatch.setattr(_svc, "_execute_function_warm", _svc._execute_function_local)
+ monkeypatch.setattr(_svc, "_emit_lambda_logs", lambda *args, **kwargs: None)
+ monkeypatch.setattr(_svc, "_emit_lambda_metrics", lambda *args, **kwargs: None)
+
+ status, headers, payload = asyncio.run(_svc._invoke(name, {}, {"x-amz-log-type": "Tail"}, None))
+
+ assert status == 200
+ assert "X-Amz-Function-Error" not in headers
+ assert json.loads(payload) == {"ok": True}
+ expected_logs = ["invoke-console-message", "invoke-stderr-message"]
+ assert base64.b64decode(headers["X-Amz-Log-Result"]).decode().splitlines() == expected_logs
diff --git a/tests/test_lambda_local_node.py b/tests/test_lambda_local_node.py
deleted file mode 100644
index 1a0dc751..00000000
--- a/tests/test_lambda_local_node.py
+++ /dev/null
@@ -1,126 +0,0 @@
-"""Real subprocess tests of the one-shot local Node executor, bypassing warm workers."""
-
-import asyncio
-import base64
-import io
-import json
-import shutil
-import uuid
-import zipfile
-
-import pytest
-
-from ministack.services import lambda_svc as svc
-
-pytestmark = pytest.mark.skipif(shutil.which("node") is None, reason="Node.js is not installed")
-
-
-def _local_function(source, *, filename="index.js"):
- name = "local-node-logs-" + uuid.uuid4().hex
- archive = io.BytesIO()
- with zipfile.ZipFile(archive, "w") as package:
- package.writestr(filename, source)
- return {
- "config": {
- "FunctionName": name,
- "FunctionArn": svc._func_arn(name),
- "Runtime": "nodejs20.x",
- "Handler": "index.handler",
- "MemorySize": 128,
- "Timeout": 10,
- },
- "code_zip": archive.getvalue(),
- }
-
-
-def _invoke_local(source, event=None, *, filename="index.js"):
- # Dispatch normally prefers a warm worker for Node. Call the one-shot
- # fallback directly so a working warm executor cannot hide this regression.
- return svc._execute_function_local(
- _local_function(source, filename=filename),
- event if event is not None else {},
- request_id=uuid.uuid4().hex,
- )
-
-
[email protected]("filename,export", [("index.js", "exports.handler ="), ("index.mjs", "export const handler =")])
-def test_local_stdout_uses_log_channel(filename, export):
- source = "console.log('module-initialization');\n" + export + """ async (event) => {
- console.log('log-message');
- console.info('info-message');
- console.debug('debug-message');
- console.warn('warn-message');
- console.error('error-message');
- process.stdout.write('stdout-message\\n');
- process.stderr.write('stderr-message\\n');
- await new Promise(resolve => setTimeout(resolve, 10));
- console.log('after-await-message');
- return {ok: true, event};
-};
-"""
- result = _invoke_local(source, {"value": 42}, filename=filename)
-
- assert not result.get("error")
- assert result["body"] == {"ok": True, "event": {"value": 42}}
- assert result["log"].splitlines() == [
- "module-initialization", "log-message", "info-message", "debug-message", "warn-message",
- "error-message", "stdout-message", "stderr-message", "after-await-message",
- ]
-
-
[email protected]("filename,imports,export", [
- ("index.js", "const {writeSync, write} = require('fs');", "exports.handler ="),
- ("index.mjs", "import {writeSync, write} from 'node:fs';", "export const handler ="),
-])
-def test_local_fd_stdout_uses_log_channel(filename, imports, export):
- source = imports + "\n" + export + """ async () => {
- writeSync(1, 'fd-message\\n');
- writeSync(1, JSON.stringify({level: 30, msg: 'pino-message'}) + '\\n');
- await new Promise((resolve, reject) =>
- write(1, 'async-fd-message\\n', err => err ? reject(err) : resolve()));
- const fs = await import('node:fs');
- const fd = fs.openSync('fd-output.txt', 'w');
- try {
- writeSync(fd, 'sync-file');
- await new Promise((resolve, reject) =>
- write(fd, Buffer.from('-async-file'), err => err ? reject(err) : resolve()));
- } finally {
- fs.closeSync(fd);
- }
- return {ok: true, file: fs.readFileSync('fd-output.txt', 'utf8')};
-};
-"""
- result = _invoke_local(source, filename=filename)
-
- assert not result.get("error")
- assert result["body"] == {"ok": True, "file": "sync-file-async-file"}
- messages = result["log"].splitlines()
- assert messages[0] == "fd-message"
- assert json.loads(messages[1]) == {"level": 30, "msg": "pino-message"}
- assert messages[2] == "async-fd-message"
- assert len(messages) == 3
-
-
-def test_local_logs_reach_invoke_tail(monkeypatch):
- function = _local_function("""
-exports.handler = async () => {
- console.log('invoke-console-message');
- console.error('invoke-stderr-message');
- return {ok: true};
-};
-""")
- name = function["config"]["FunctionName"]
- monkeypatch.setitem(svc._functions, name, function)
- monkeypatch.setattr(svc, "LAMBDA_EXECUTOR", "local")
- monkeypatch.setattr(svc, "LAMBDA_STRICT", False)
- monkeypatch.setattr(svc, "_execute_function_warm", svc._execute_function_local)
- monkeypatch.setattr(svc, "_emit_lambda_logs", lambda *args, **kwargs: None)
- monkeypatch.setattr(svc, "_emit_lambda_metrics", lambda *args, **kwargs: None)
-
- status, headers, payload = asyncio.run(svc._invoke(name, {}, {"x-amz-log-type": "Tail"}, None))
-
- assert status == 200
- assert "X-Amz-Function-Error" not in headers
- assert json.loads(payload) == {"ok": True}
- expected_logs = ["invoke-console-message", "invoke-stderr-message"]
- assert base64.b64decode(headers["X-Amz-Log-Result"]).decode().splitlines() == expected_logs
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index f9c13979..74138c0f 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -3915,6 +3915,41 @@ def test_sfn_integration_lambda_invoke_failure_cause_is_json(sfn, lam):
assert cause["errorMessage"] == "widget exploded", cause
+def test_sfn_lambda_task_returning_none_outputs_null(sfn, lam):
+ """A function that returns None yields the JSON text null, which is the
+ Task result: [null, null, null] out of a Map, and Payload null through the
+ optimized lambda:invoke integration."""
+ import uuid as _uuid
+
+ fn = f"sfn-returns-none-{_uuid.uuid4().hex[:8]}"
+ lam.create_function(FunctionName=fn, Runtime="python3.12", Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip("def handler(event, context):\n return None\n")})
+ func_arn = f"arn:aws:lambda:us-east-1:000000000000:function:{fn}"
+ definitions = {
+ "map": ({"StartAt": "Fanout", "States": {"Fanout": {
+ "Type": "Map", "ItemsPath": "$.items", "End": True,
+ "ItemProcessor": {"ProcessorConfig": {"Mode": "INLINE"}, "StartAt": "Call",
+ "States": {"Call": {"Type": "Task", "Resource": func_arn, "End": True}}}}}},
+ [None, None, None]),
+ "invoke": ({"StartAt": "Call", "States": {"Call": {
+ "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke",
+ "Parameters": {"FunctionName": func_arn, "Payload": {}},
+ "OutputPath": "$.Payload", "End": True}}},
+ None),
+ }
+ for label, (definition, expected) in definitions.items():
+ sm = sfn.create_state_machine(name=f"sfn-null-{label}-{_uuid.uuid4().hex[:8]}",
+ definition=json.dumps(definition), roleArn=_LAMBDA_ROLE)
+ ex = sfn.start_execution(stateMachineArn=sm["stateMachineArn"],
+ input=json.dumps({"items": [1, 2, 3]}))
+ desc = _wait_sfn(sfn, ex["executionArn"], timeout=30)
+ assert desc["status"] == "SUCCEEDED", (label, desc)
+ assert json.loads(desc["output"]) == expected, label
+ sfn.delete_state_machine(stateMachineArn=sm["stateMachineArn"])
+ lam.delete_function(FunctionName=fn)
+
+
def test_sfn_integration_ecs_run_task(sfn, ecs):
"""Task state triggers ecs:runTask (fire-and-forget, no Docker needed)."""
ecs.create_cluster(clusterName="sfn-ecs-test")