Skip to content

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

feat: CFN auto-generated names follow AWS {stack}-{logicalId}-{SUFFIX… (#57)

Nahuel Nucera9f0fa47c677a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cba60f24..d0b6ac3a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,22 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.1.15] — 2026-04-01
+
+### Added
+- **Lambda Node.js runtime** — `nodejs14.x` through `nodejs22.x` (and any future `nodejsN.x`) now fully execute via local subprocess (`node`) or Docker; supports `CreateFunction`, `UpdateFunctionCode`, `Invoke` including async handlers; layers resolved to `nodejs/node_modules`; `nodejs24.x` auto-maps via pattern
+
+### Fixed
+- **CloudFormation auto-generated physical names** — resources without explicit names now follow the AWS pattern `{stackName}-{logicalId}-{SUFFIX}` with a 13-char uppercase alphanumeric suffix; service-specific rules applied (S3: lowercase, max 63; SQS: max 80; DynamoDB: max 255; Lambda/IAM/EventBridge: max 64). Fixes CDK stacks that omit explicit resource names producing untraceable `cfn-xxx` names
+- **Import cleanup** — moved lazy stdlib imports (`base64`, `fnmatch`, `re`, `datetime`, `urllib`) to module level across `sqs`, `cloudwatch_logs`, `glue`, `cognito`, `rds`, `apigateway`, `apigateway_v1`; removed duplicate `os`/`re` imports in `s3`
+
+### Tests
+- 3 new Node.js Lambda tests (create+invoke, nodejs22.x, UpdateFunctionCode)
+- 4 new CFN physical name tests (S3/SQS/DynamoDB auto-name pattern, explicit name not overridden)
+- 815 tests total, all passing
+
+---
+
## [1.1.14] — 2026-04-01
### Added
diff --git a/README.md b/README.md
index 81d07f11..66d70311 100644
--- a/README.md
+++ b/README.md
@@ -202,7 +202,7 @@ subnet = ec2.create_subnet(
| **SQS** | CreateQueue, DeleteQueue, ListQueues, GetQueueUrl, GetQueueAttributes, SetQueueAttributes, PurgeQueue, SendMessage, ReceiveMessage, DeleteMessage, ChangeMessageVisibility, ChangeMessageVisibilityBatch, SendMessageBatch, DeleteMessageBatch, TagQueue, UntagQueue, ListQueueTags | Both Query API and JSON protocol; FIFO queues with deduplication; DLQ support |
| **SNS** | CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes, Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, GetSubscriptionAttributes, SetSubscriptionAttributes, ConfirmSubscription, Publish, PublishBatch, TagResource, UntagResource, ListTagsForResource, CreatePlatformApplication, CreatePlatformEndpoint | SNS→SQS fanout delivery; SNS→Lambda fanout (synchronous invocation) |
| **DynamoDB** | CreateTable, UpdateTable, DeleteTable, DescribeTable, ListTables, PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem, TransactWriteItems, TransactGetItems, DescribeTimeToLive, UpdateTimeToLive, DescribeContinuousBackups, UpdateContinuousBackups, DescribeEndpoints, TagResource, UntagResource, ListTagsOfResource | TTL enforced via thread-safe background reaper (60s cadence) |
-| **Lambda** | CreateFunction, DeleteFunction, GetFunction, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration, AddPermission, RemovePermission, ListVersionsByFunction, PublishVersion, TagResource, UntagResource, ListTags, CreateEventSourceMapping, DeleteEventSourceMapping, GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping, CreateFunctionUrlConfig, GetFunctionUrlConfig, UpdateFunctionUrlConfig, DeleteFunctionUrlConfig, ListFunctionUrlConfigs, PublishLayerVersion, GetLayerVersion, ListLayerVersions, DeleteLayerVersion, ListLayers | Python runtimes actually execute with warm worker pool; SQS event source mapping; Function URL CRUD; Lambda Layers CRUD |
+| **Lambda** | CreateFunction, DeleteFunction, GetFunction, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration, AddPermission, RemovePermission, ListVersionsByFunction, PublishVersion, TagResource, UntagResource, ListTags, CreateEventSourceMapping, DeleteEventSourceMapping, GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping, CreateFunctionUrlConfig, GetFunctionUrlConfig, UpdateFunctionUrlConfig, DeleteFunctionUrlConfig, ListFunctionUrlConfigs, PublishLayerVersion, GetLayerVersion, ListLayerVersions, DeleteLayerVersion, ListLayers | Python runtimes execute with warm worker pool; Node.js runtimes (`nodejs14.x`–`nodejs22.x`) execute via local `node` subprocess or Docker; SQS event source mapping; Function URL CRUD; Lambda Layers CRUD |
| **IAM** | CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles, DeleteRole, CreatePolicy, GetPolicy, DeletePolicy, AttachRolePolicy, DetachRolePolicy, PutRolePolicy, GetRolePolicy, DeleteRolePolicy, ListRolePolicies, ListAttachedRolePolicies, CreateAccessKey, ListAccessKeys, DeleteAccessKey, CreateInstanceProfile, GetInstanceProfile, DeleteInstanceProfile, AddRoleToInstanceProfile, RemoveRoleFromInstanceProfile, ListInstanceProfiles, CreateGroup, GetGroup, AddUserToGroup, RemoveUserFromGroup, CreateServiceLinkedRole, CreateOpenIDConnectProvider, TagRole, UntagRole, TagUser, UntagUser, TagPolicy, UntagPolicy | |
| **STS** | GetCallerIdentity, AssumeRole, GetSessionToken, AssumeRoleWithWebIdentity | |
| **SecretsManager** | CreateSecret, GetSecretValue, ListSecrets, DeleteSecret, UpdateSecret, DescribeSecret, PutSecretValue, RestoreSecret, RotateSecret, GetRandomPassword, ListSecretVersionIds, TagResource, UntagResource, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy, ValidateResourcePolicy | |
@@ -453,6 +453,35 @@ docker run -p 4566:4566 \
MiniStack keeps Python Lambda functions warm between invocations. After the first call (cold start), the handler module stays imported in a persistent subprocess. Subsequent calls skip the import step, matching real AWS warm-start behaviour and making test suites significantly faster.
+### Lambda Node.js Runtimes
+
+MiniStack supports Node.js Lambda runtimes (`nodejs14.x`, `nodejs16.x`, `nodejs18.x`, `nodejs20.x`, `nodejs22.x`). Functions execute via a local `node` subprocess (or Docker when `LAMBDA_USE_DOCKER=1`) — no mocking, real JS execution.
+
+```python
+import boto3, json, zipfile, io
+
+lam = boto3.client("lambda", endpoint_url="http://localhost:4566", region_name="us-east-1",
+ aws_access_key_id="test", aws_secret_access_key="test")
+
+code = "exports.handler = async (event) => ({ statusCode: 200, body: JSON.stringify(event) });"
+buf = io.BytesIO()
+with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.js", code)
+
+lam.create_function(
+ FunctionName="my-node-fn",
+ Runtime="nodejs20.x",
+ Role="arn:aws:iam::000000000000:role/r",
+ Handler="index.handler",
+ Code={"ZipFile": buf.getvalue()},
+)
+
+resp = lam.invoke(FunctionName="my-node-fn", Payload=json.dumps({"hello": "world"}))
+print(json.loads(resp["Payload"].read())) # {'statusCode': 200, 'body': '{"hello": "world"}'}
+```
+
+Layers that ship npm packages work too — MiniStack resolves the `nodejs/node_modules` subdirectory inside each layer zip and prepends it to the module search path.
+
---
## Architecture
@@ -505,7 +534,7 @@ pip install boto3 pytest duckdb docker cbor2
# Start MiniStack
docker compose up -d
-# Run the full test suite (808 tests across all 34 services)
+# Run the full test suite (815 tests across all 34 services)
pytest tests/ -v
```
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index 849c6e23..2d5ac5e3 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -45,6 +45,8 @@ import logging
import os
import re
import time
+import urllib.error
+import urllib.request
from ministack.core.responses import error_response_json, new_uuid
@@ -386,9 +388,6 @@ async def _invoke_lambda_proxy(integration, api_id, stage, path, method, headers
async def _invoke_http_proxy(integration, path, method, headers, body, query_params):
"""Forward a request to an HTTP backend."""
- import urllib.error
- import urllib.request
-
uri = integration.get("integrationUri", "")
url = uri.rstrip("/") + path
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 49d528f7..09af12cf 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -70,7 +70,10 @@ Data plane:
import datetime
import json
import logging
+import re
import time
+import urllib.error
+import urllib.request
from ministack.core.responses import new_uuid
@@ -673,9 +676,6 @@ async def _invoke_lambda_proxy_v1(integration, api_id, stage_name, stage, resour
async def _invoke_http_proxy_v1(integration, path, method, headers, body, query_params):
"""Forward a request to an HTTP backend."""
- import urllib.error
- import urllib.request
-
uri = integration.get("uri", "")
url = uri.rstrip("/") + path
@@ -702,7 +702,6 @@ def _invoke_mock_v1(integration):
matching AWS behaviour for MOCK where the input is always treated as
successful (statusCode 200).
"""
- import re
int_responses = integration.get("integrationResponses", {})
if not int_responses:
return 200, {"Content-Type": "application/json"}, b"{}"
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 66b6e11c..ef51e2ef 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -5,6 +5,8 @@ CloudFormation provisioners — resource create/delete handlers for each AWS res
import io
import json
import logging
+import random
+import string
import time
import zipfile
from collections import defaultdict
@@ -28,6 +30,21 @@ ACCOUNT_ID = "000000000000"
REGION = "us-east-1"
+def _physical_name(stack_name: str, logical_id: str, *,
+ lowercase: bool = False, max_len: int = 128) -> str:
+ """Generate an AWS-style physical resource name: {stack}-{logicalId}-{SUFFIX}.
+
+ Matches the pattern AWS CloudFormation uses for auto-named resources so that
+ local testing with CDK (which omits explicit names) produces names that are
+ immediately traceable back to the stack and logical resource.
+ """
+ suffix = "".join(random.choices(string.ascii_uppercase + string.digits, k=13))
+ base = f"{stack_name}-{logical_id}-{suffix}"
+ if lowercase:
+ base = base.lower()
+ return base[:max_len]
+
+
# ===========================================================================
# Resource Provisioner Framework
# ===========================================================================
@@ -63,7 +80,7 @@ def _delete_resource(resource_type: str, physical_id: str, props: dict):
# --- S3 Bucket ---
def _s3_create(logical_id, props, stack_name):
- name = props.get("BucketName") or f"{stack_name}-{logical_id.lower()}-{new_uuid()[:8]}"
+ name = props.get("BucketName") or _physical_name(stack_name, logical_id, lowercase=True, max_len=63)
_s3._buckets[name] = {
"created": now_iso(),
"objects": {},
@@ -96,7 +113,7 @@ def _s3_delete(physical_id, props):
# --- SQS Queue ---
def _sqs_create(logical_id, props, stack_name):
- name = props.get("QueueName") or f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ name = props.get("QueueName") or _physical_name(stack_name, logical_id, max_len=80)
is_fifo = name.endswith(".fifo")
url = f"http://{_sqs.DEFAULT_HOST}:{_sqs.DEFAULT_PORT}/{ACCOUNT_ID}/{name}"
arn = f"arn:aws:sqs:{REGION}:{ACCOUNT_ID}:{name}"
@@ -141,7 +158,7 @@ def _sqs_delete(physical_id, props):
# --- SNS Topic ---
def _sns_create(logical_id, props, stack_name):
- name = props.get("TopicName") or f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ name = props.get("TopicName") or _physical_name(stack_name, logical_id, max_len=256)
arn = f"arn:aws:sns:{REGION}:{ACCOUNT_ID}:{name}"
default_policy = json.dumps({
"Version": "2008-10-17",
@@ -247,7 +264,7 @@ def _sns_sub_delete(physical_id, props):
# --- DynamoDB Table ---
def _ddb_create(logical_id, props, stack_name):
- name = props.get("TableName") or f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ name = props.get("TableName") or _physical_name(stack_name, logical_id, max_len=255)
arn = f"arn:aws:dynamodb:{REGION}:{ACCOUNT_ID}:table/{name}"
key_schema = props.get("KeySchema", [])
@@ -322,7 +339,7 @@ def _zip_inline(source: str | None, handler: str) -> bytes | None:
def _lambda_create(logical_id, props, stack_name):
- name = props.get("FunctionName") or f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ name = props.get("FunctionName") or _physical_name(stack_name, logical_id, max_len=64)
arn = f"arn:aws:lambda:{REGION}:{ACCOUNT_ID}:function:{name}"
runtime = props.get("Runtime", "python3.9")
handler = props.get("Handler", "index.handler")
@@ -379,7 +396,7 @@ def _lambda_delete(physical_id, props):
# --- IAM Role ---
def _iam_role_create(logical_id, props, stack_name):
- name = props.get("RoleName") or f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ name = props.get("RoleName") or _physical_name(stack_name, logical_id, max_len=64)
arn = f"arn:aws:iam::{ACCOUNT_ID}:role/{name}"
role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()
assume_doc = props.get("AssumeRolePolicyDocument", {})
@@ -433,7 +450,7 @@ def _iam_role_delete(physical_id, props):
# --- IAM Policy ---
def _iam_policy_create(logical_id, props, stack_name):
- name = props.get("PolicyName") or f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ name = props.get("PolicyName") or _physical_name(stack_name, logical_id, max_len=128)
path = props.get("Path", "/")
arn = f"arn:aws:iam::{ACCOUNT_ID}:policy{path}{name}"
pol_doc = props.get("PolicyDocument", {})
@@ -482,7 +499,7 @@ def _iam_policy_delete(physical_id, props):
# --- IAM InstanceProfile ---
def _iam_ip_create(logical_id, props, stack_name):
- name = props.get("InstanceProfileName") or f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ name = props.get("InstanceProfileName") or _physical_name(stack_name, logical_id, max_len=128)
path = props.get("Path", "/")
arn = f"arn:aws:iam::{ACCOUNT_ID}:instance-profile{path}{name}"
ip_id = new_uuid().replace("-", "")[:21].upper()
@@ -570,7 +587,7 @@ def _cwlogs_delete(physical_id, props):
# --- EventBridge Rule ---
def _eb_rule_create(logical_id, props, stack_name):
- name = props.get("Name") or f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
+ name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=64)
bus = props.get("EventBusName", "default")
key = f"{name}|{bus}"
arn = f"arn:aws:events:{REGION}:{ACCOUNT_ID}:rule/{bus}/{name}"
diff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.py
index 3d4fb117..1b7c8146 100644
--- a/ministack/services/cloudwatch_logs.py
+++ b/ministack/services/cloudwatch_logs.py
@@ -15,6 +15,7 @@ Supports: CreateLogGroup, DeleteLogGroup, DescribeLogGroups,
"""
import base64
+import fnmatch
import json
import logging
import time
@@ -402,7 +403,6 @@ def _compile_filter_pattern(raw: str):
# JSON-style patterns (starts with {) — treat as match-all for emulation
if raw.startswith("{"):
return lambda msg: True
- import fnmatch
terms = raw.split()
include = []
exclude = []
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 06fecea9..c60a99b8 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -45,6 +45,7 @@ Wire protocol:
import base64
import json
import logging
+import re
import secrets
import string
import time
@@ -1878,7 +1879,6 @@ def _apply_user_filter(users: list, filter_str: str) -> list:
attribute_name ^= "value" (starts with)
attribute_name != "value"
"""
- import re
m = re.match(r'(\w+)\s*(=|\^=|!=)\s*"([^"]*)"', filter_str.strip())
if not m:
return users
diff --git a/ministack/services/glue.py b/ministack/services/glue.py
index 4483e277..dc53f9d5 100644
--- a/ministack/services/glue.py
+++ b/ministack/services/glue.py
@@ -8,6 +8,7 @@ Job execution runs Python scripts via subprocess in background threads.
Crawlers transition through RUNNING state with a configurable timer.
"""
+import fnmatch
import json
import logging
import os
@@ -1070,7 +1071,6 @@ def _get_tags(data):
def _simple_glob_match(pattern, name):
"""Very simple glob matching: * matches anything."""
- import fnmatch
return fnmatch.fnmatch(name, pattern)
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index c3f09b92..f03158d6 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -154,6 +154,49 @@ if _result is not None:
"""
+# Node.js wrapper — written to the code dir and executed with `node`.
+# Reads event from stdin, calls handler, writes JSON result to stdout.
+_NODE_WRAPPER_SCRIPT = """\
+const fs = require('fs');
+const path = require('path');
+
+const codeDir = process.env._LAMBDA_CODE_DIR || '/var/task';
+const modPath = process.env._LAMBDA_HANDLER_MODULE;
+const fnName = process.env._LAMBDA_HANDLER_FUNC;
+
+// Prepend layer dirs to NODE_PATH
+const layerDirs = (process.env._LAMBDA_LAYERS_DIRS || '').split(path.delimiter).filter(Boolean);
+const nodePaths = layerDirs.map(d => path.join(d, 'nodejs', 'node_modules'))
+ .concat(layerDirs)
+ .concat([path.join(codeDir, 'node_modules'), codeDir]);
+module.paths.unshift(...nodePaths);
+
+const context = {
+ functionName: process.env.AWS_LAMBDA_FUNCTION_NAME || '',
+ memoryLimitInMB: process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE || '128',
+ invokedFunctionArn: process.env._LAMBDA_FUNCTION_ARN || '',
+ awsRequestId: process.env.AWS_LAMBDA_LOG_STREAM_NAME || '',
+ logGroupName: '/aws/lambda/' + (process.env.AWS_LAMBDA_FUNCTION_NAME || ''),
+ logStreamName: process.env.AWS_LAMBDA_LOG_STREAM_NAME || '',
+ getRemainingTimeInMillis: () => parseFloat(process.env._LAMBDA_TIMEOUT || '3') * 1000,
+};
+
+let input = '';
+process.stdin.on('data', d => input += d);
+process.stdin.on('end', () => {
+ const event = JSON.parse(input);
+ const mod = require(path.resolve(codeDir, modPath));
+ const handler = mod[fnName];
+ Promise.resolve(handler(event, context)).then(result => {
+ if (result !== undefined) process.stdout.write(JSON.stringify(result));
+ }).catch(err => {
+ process.stderr.write(String(err.stack || err));
+ process.exit(1);
+ });
+});
+"""
+
+
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
@@ -846,11 +889,12 @@ def _execute_function_docker(func: dict, event: dict) -> dict:
},
}
- if not runtime.startswith("python"):
+ is_node = runtime.startswith("nodejs")
+ if not runtime.startswith("python") and not is_node:
return {
"body": {
"statusCode": 200,
- "body": f"Mock response - {runtime} docker wrapper only supports Python runtimes",
+ "body": f"Mock response - {runtime} docker wrapper only supports Python and Node.js runtimes",
},
}
@@ -872,11 +916,6 @@ def _execute_function_docker(func: dict, event: dict) -> dict:
with zipfile.ZipFile(zip_path) as zf:
zf.extractall(code_dir)
- # Write the docker wrapper into the code dir
- wrapper_path = os.path.join(code_dir, "_wrapper.py")
- with open(wrapper_path, "w") as wf:
- wf.write(_DOCKER_WRAPPER_SCRIPT)
-
# Extract layers
layers_dirs: list[str] = []
for layer_ref in config.get("Layers", []):
@@ -937,9 +976,20 @@ def _execute_function_docker(func: dict, event: dict) -> dict:
with open(event_file, "w") as ef:
ef.write(json.dumps(event))
+ if is_node:
+ wrapper_path = os.path.join(code_dir, "_wrapper.js")
+ with open(wrapper_path, "w") as wf:
+ wf.write(_NODE_WRAPPER_SCRIPT)
+ run_cmd = ["sh", "-c", "node /var/task/_wrapper.js < /var/task/_event.json"]
+ else:
+ wrapper_path = os.path.join(code_dir, "_wrapper.py")
+ with open(wrapper_path, "w") as wf:
+ wf.write(_DOCKER_WRAPPER_SCRIPT)
+ run_cmd = ["sh", "-c", "python3 /var/task/_wrapper.py < /var/task/_event.json"]
+
container = client.containers.run(
image,
- command=["sh", "-c", "python3 /var/task/_wrapper.py < /var/task/_event.json"],
+ command=run_cmd,
environment=container_env,
volumes=volumes,
network_mode="host",
@@ -1022,7 +1072,8 @@ def _execute_function_local(func: dict, event: dict) -> dict:
timeout = config.get("Timeout", 3)
env_vars = config.get("Environment", {}).get("Variables", {})
- if not runtime.startswith("python"):
+ is_node = runtime.startswith("nodejs")
+ if not runtime.startswith("python") and not is_node:
return {
"body": {
"statusCode": 200,
@@ -1056,9 +1107,14 @@ def _execute_function_local(func: dict, event: dict) -> dict:
module_name, func_name = handler.rsplit(".", 1)
- wrapper_path = os.path.join(tmpdir, "_wrapper.py")
- with open(wrapper_path, "w") as wf:
- wf.write(_WRAPPER_SCRIPT)
+ if is_node:
+ wrapper_path = os.path.join(tmpdir, "_wrapper.js")
+ with open(wrapper_path, "w") as wf:
+ wf.write(_NODE_WRAPPER_SCRIPT)
+ else:
+ wrapper_path = os.path.join(tmpdir, "_wrapper.py")
+ with open(wrapper_path, "w") as wf:
+ wf.write(_WRAPPER_SCRIPT)
env = dict(os.environ)
env.update(
@@ -1089,8 +1145,9 @@ def _execute_function_local(func: dict, event: dict) -> dict:
env["AWS_ENDPOINT_URL"] = endpoint
env.update(env_vars)
+ cmd = ["node", wrapper_path] if is_node else ["python3", wrapper_path]
proc = subprocess.run(
- ["python3", wrapper_path],
+ cmd,
input=json.dumps(event),
capture_output=True,
text=True,
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index 23a28f5e..60d9c5bf 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -21,6 +21,7 @@ When Docker is available, CreateDBInstance spins up a real Postgres/MySQL contai
and returns the actual host:port as the endpoint.
"""
+import datetime
import logging
import os
import time
@@ -1817,7 +1818,6 @@ def _apply_cluster_filters(clusters, filters):
def _format_time(ts):
- import datetime
dt = datetime.datetime.fromtimestamp(ts, tz=datetime.timezone.utc)
return dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 6575b7b3..68883d5b 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -22,10 +22,8 @@ Supports: CreateBucket, DeleteBucket, ListBuckets, HeadBucket,
Storage: In-memory (optionally backed by S3_DATA_DIR).
"""
-import datetime as _dt
-import os
-import re
import base64
+import datetime as _dt
import hashlib
import json
import logging
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index 3cee3162..0df232db 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -22,6 +22,7 @@ Actions:
"""
import asyncio
+import base64
import hashlib
import json
import logging
@@ -761,7 +762,6 @@ def _md5_msg_attrs(attrs: dict | None) -> str | None:
buf += b"\x02"
val = a.get("BinaryValue", b"")
if isinstance(val, str):
- import base64
val = base64.b64decode(val)
if isinstance(val, bytearray):
val = bytes(val)
diff --git a/pyproject.toml b/pyproject.toml
index 5f0eafda..f323df68 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.1.14"
+version = "1.1.15"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_services.py b/tests/test_services.py
index b1abb4ee..66f8f4e1 100644
--- a/tests/test_services.py
+++ b/tests/test_services.py
@@ -1981,6 +1981,13 @@ def _make_zip(code: str) -> bytes:
return buf.getvalue()
+def _make_zip_js(code: str, filename: str = "index.js") -> bytes:
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr(filename, code)
+ return buf.getvalue()
+
+
def test_ddb_create_table(ddb):
resp = ddb.create_table(
TableName="t_hash_only",
@@ -5988,6 +5995,62 @@ def test_lambda_warm_start(lam, apigw):
lam.delete_function(FunctionName=fname)
+# ========== Lambda — Node.js runtime ==========
+
+_NODE_CODE = (
+ "exports.handler = async (event, context) => {"
+ " return { statusCode: 200, body: JSON.stringify({ hello: event.name || 'world' }) }; };"
+)
+
+
+def test_lambda_nodejs_create_and_invoke(lam):
+ lam.create_function(
+ FunctionName="lam-node-basic",
+ Runtime="nodejs20.x",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip_js(_NODE_CODE, "index.js")},
+ )
+ resp = lam.invoke(
+ FunctionName="lam-node-basic",
+ Payload=json.dumps({"name": "ministack"}),
+ )
+ assert resp["StatusCode"] == 200
+ payload = json.loads(resp["Payload"].read())
+ assert payload["statusCode"] == 200
+ body = json.loads(payload["body"])
+ assert body["hello"] == "ministack"
+
+
+def test_lambda_nodejs22_runtime(lam):
+ lam.create_function(
+ FunctionName="lam-node22",
+ Runtime="nodejs22.x",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip_js(_NODE_CODE, "index.js")},
+ )
+ resp = lam.invoke(FunctionName="lam-node22", Payload=json.dumps({"name": "v22"}))
+ assert resp["StatusCode"] == 200
+ payload = json.loads(resp["Payload"].read())
+ assert payload["statusCode"] == 200
+
+
+def test_lambda_nodejs_update_code(lam):
+ v2 = (
+ "exports.handler = async (event) => {"
+ " return { statusCode: 200, body: 'v2' }; };"
+ )
+ lam.update_function_code(
+ FunctionName="lam-node-basic",
+ ZipFile=_make_zip_js(v2, "index.js"),
+ )
+ resp = lam.invoke(FunctionName="lam-node-basic", Payload=b"{}")
+ assert resp["StatusCode"] == 200
+ payload = json.loads(resp["Payload"].read())
+ assert payload["body"] == "v2"
+
+
# ========== API Gateway execute-api data plane ==========
@@ -15572,3 +15635,111 @@ def test_cfn_e2e_exports_available(cfn_e2e_stack, cfn):
names = {e["Name"]: e["Value"] for e in exports}
assert f"{_E2E_STACK}-bucket" in names
assert names[f"{_E2E_STACK}-bucket"] == cfn_e2e_stack["BucketName"]
+
+
+# ========== CloudFormation — Auto-Generated Physical Names ==========
+
+
+def test_cfn_auto_name_s3_follows_aws_pattern(cfn, s3):
+ """S3 bucket auto-name: lowercase, stackName-logicalId-SUFFIX, max 63 chars."""
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "MyBucket": {"Type": "AWS::S3::Bucket", "Properties": {}},
+ },
+ "Outputs": {
+ "BucketName": {"Value": {"Ref": "MyBucket"}},
+ },
+ }
+ cfn.create_stack(StackName="cfn-autoname-s3", TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, "cfn-autoname-s3")
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+
+ bucket_name = next(o["OutputValue"] for o in stack["Outputs"] if o["OutputKey"] == "BucketName")
+ assert bucket_name == bucket_name.lower(), "S3 auto-name must be lowercase"
+ assert bucket_name.startswith("cfn-autoname-s3-mybucket-"), f"Expected AWS-pattern name, got: {bucket_name}"
+ assert len(bucket_name) <= 63, f"S3 name too long: {len(bucket_name)}"
+ # Verify bucket actually exists
+ s3.head_bucket(Bucket=bucket_name)
+
+ cfn.delete_stack(StackName="cfn-autoname-s3")
+ _wait_stack(cfn, "cfn-autoname-s3")
+
+
+def test_cfn_auto_name_sqs_follows_aws_pattern(cfn, sqs):
+ """SQS queue auto-name: stackName-logicalId-SUFFIX, max 80 chars, case preserved."""
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "MyQueue": {"Type": "AWS::SQS::Queue", "Properties": {}},
+ },
+ "Outputs": {
+ "QueueName": {"Value": {"Fn::GetAtt": ["MyQueue", "QueueName"]}},
+ },
+ }
+ cfn.create_stack(StackName="cfn-autoname-sqs", TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, "cfn-autoname-sqs")
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+
+ queue_name = next(o["OutputValue"] for o in stack["Outputs"] if o["OutputKey"] == "QueueName")
+ assert queue_name.startswith("cfn-autoname-sqs-MyQueue-"), f"Expected AWS-pattern name, got: {queue_name}"
+ assert len(queue_name) <= 80
+
+ cfn.delete_stack(StackName="cfn-autoname-sqs")
+ _wait_stack(cfn, "cfn-autoname-sqs")
+
+
+def test_cfn_auto_name_dynamodb_follows_aws_pattern(cfn, ddb):
+ """DynamoDB table auto-name: stackName-logicalId-SUFFIX, max 255 chars."""
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "MyTable": {
+ "Type": "AWS::DynamoDB::Table",
+ "Properties": {
+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
+ "BillingMode": "PAY_PER_REQUEST",
+ },
+ },
+ },
+ "Outputs": {
+ "TableName": {"Value": {"Ref": "MyTable"}},
+ },
+ }
+ cfn.create_stack(StackName="cfn-autoname-ddb", TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, "cfn-autoname-ddb")
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+
+ table_name = next(o["OutputValue"] for o in stack["Outputs"] if o["OutputKey"] == "TableName")
+ assert table_name.startswith("cfn-autoname-ddb-MyTable-"), f"Expected AWS-pattern name, got: {table_name}"
+ assert len(table_name) <= 255
+ ddb.describe_table(TableName=table_name)
+
+ cfn.delete_stack(StackName="cfn-autoname-ddb")
+ _wait_stack(cfn, "cfn-autoname-ddb")
+
+
+def test_cfn_explicit_name_not_overridden(cfn, s3):
+ """Explicit BucketName must be used as-is, not overridden by auto-name logic."""
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "MyBucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {"BucketName": "cfn-explicit-name-test"},
+ },
+ },
+ "Outputs": {
+ "BucketName": {"Value": {"Ref": "MyBucket"}},
+ },
+ }
+ cfn.create_stack(StackName="cfn-explicit-name", TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, "cfn-explicit-name")
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+
+ bucket_name = next(o["OutputValue"] for o in stack["Outputs"] if o["OutputKey"] == "BucketName")
+ assert bucket_name == "cfn-explicit-name-test"
+
+ cfn.delete_stack(StackName="cfn-explicit-name")
+ _wait_stack(cfn, "cfn-explicit-name")