Skip to content

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

release v1.5.13 (#1760)

Nahuel Nucera551c42860ce4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 017b2b4f..1852e761 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,14 +7,22 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
-### Fixed
-- **IAM — three calls are authorized against the action and resource AWS uses** — a Lambda Function URL invoke is checked against its function ARN, alias qualifier included, and supplies `lambda:FunctionUrlAuthType`, so the policy `grantInvokeUrl` writes matches. The WebSocket `@connections` API asks for `execute-api:ManageConnections` instead of `execute-api:Invoke`. `iot-jobs-data` operations are authorized under `iotjobsdata:`, except `StartCommandExecution`, which stays on `iot:`. A policy written for the old action names stops matching, as on AWS. Contributed by @iot-rocket.
+## [1.5.13] — 2026-09-17
+
### Added
-- **CloudFormation: the `AWS::LanguageExtensions` transform**: a template declaring it was provisioned unexpanded, so an `Fn::ForEach` left the stack in `CREATE_IN_PROGRESS` for good and an `Fn::ToJsonString` reached SSM as a Python dict. The transform now runs between `AWS::Include` and SAM: `Fn::ForEach` over literal, `CommaDelimitedList` and intrinsic collections, nested and inside `Properties`, plus `Fn::Length` and `Fn::ToJsonString`. Where the identifier is substituted, the error sentences and the unexpanded `GetTemplateSummary` follow measurements on a real account. Contributed by @iot-rocket.
+- **CloudFormation — the `AWS::LanguageExtensions` transform** — a template declaring it was provisioned unexpanded, so an `Fn::ForEach` left the stack in `CREATE_IN_PROGRESS` for good and an `Fn::ToJsonString` reached SSM as a Python dict. The transform now runs between `AWS::Include` and SAM: `Fn::ForEach` over literal, `CommaDelimitedList` and intrinsic collections, nested and inside `Properties`, plus `Fn::Length` and `Fn::ToJsonString`. Where the identifier is substituted, the error sentences and the unexpanded `GetTemplateSummary` follow measurements on a real account. Contributed by @iot-rocket.
+- **RDS — IAM database authentication tokens are verified** — a helper validates an SDK-generated token against the endpoint, port, database username, signing scope, lifetime and signature. Nothing calls it yet; database login itself is a later stage. Contributed by @Areson.
+
+### Changed
+- **Persistence — every saved snapshot is restored through the registry** — a service restored its own state as a side effect of being imported, so the boot path carried a hand-maintained list of eager imports to cover the modules the router never reached. The registry now drives one restore loop, and the runtime work a restore implies runs from each module's `load_persisted_state` instead of its import. No user-visible change. Contributed by @jgrumboe.
+
### Fixed
-- **IAM — a group policy document is validated, and an `AWS::IAM::Policy` naming a missing entity fails** — `PutGroupPolicy` stored a malformed document; all three inline handlers now answer `NoSuchEntity` before `MalformedPolicyDocument`, the order measured on AWS. An `AWS::IAM::Policy` skipped a Role, User or Group that was not there and reported `CREATE_COMPLETE`; the resource now fails with `The role with name <name> cannot be found.`, and an update checks names and document before it takes the old policy off. Contributed by @iot-rocket.
+- **Router — the first request to any service no longer loads CloudFormation** — the WaitCondition signal handler imported `cloudformation.wait_conditions` above the path check, so every first request pulled in the whole package and, through its provisioners, AppSync and graphql; the first `/_ministack/reset` ran `appsync.reset()` with it. The import now sits behind the path match, and a guard keeps it there. Reported by @ThailerL.
+- **DynamoDB — `ImportTable` reads the S3 source** — the import created the table, reported `COMPLETED` and imported nothing: the source objects were never opened. CSV and `DYNAMODB_JSON`, GZIP or uncompressed, are now read from the prefix and written into the table, with the counters reported as it runs and per-item errors in the `/aws-dynamodb/imports` log group. A missing bucket or prefix fails the import and leaves no table behind; `ION` and `ZSTD` are refused with a stated reason. Contributed by @gakuto-cw21.
- **IAM — a Secrets Manager request is authorized against the stored secret ARN** — the resource was built from the name in the request, `secret:<name>`, while AWS evaluates the stored ARN with the six random characters minted at `CreateSecret`. The grant shape the CDK writes for a secret looked up by name, `secret:<name>-??????` or `secret:<name>-*`, matched nothing under `AUTH=true`. The resource now comes from the store through the handlers' own lookup; a secret that does not exist keeps the name-derived ARN. Contributed by @iot-rocket.
-- **Lambda — a layer shared through `AddLayerVersionPermission` attaches** — every layer ARN from another account was refused before the stored policy was read. Attachment, from the API and from a CloudFormation function, and `GetLayerVersionByArn` now evaluate it for account, root, public and organization grants, and an attached function keeps the content after the grant is revoked or the version is deleted. Contributed by @iot-rocket.
+- **IAM — a group policy document is validated, and an `AWS::IAM::Policy` naming a missing entity fails** — `PutGroupPolicy` stored a malformed document; all three inline handlers now answer `NoSuchEntity` before `MalformedPolicyDocument`. An `AWS::IAM::Policy` skipped a Role, User or Group that was not there and reported `CREATE_COMPLETE`; the resource now fails with `The role with name <name> cannot be found.`, and an update checks names and document before it takes the old policy off. Contributed by @iot-rocket.
+- **IAM — three calls are authorized against the action and resource AWS uses** — a Lambda Function URL invoke is checked against its function ARN, alias qualifier included, and supplies `lambda:FunctionUrlAuthType`, so the policy `grantInvokeUrl` writes matches. The WebSocket `@connections` API asks for `execute-api:ManageConnections` instead of `execute-api:Invoke`. `iot-jobs-data` operations are authorized under `iotjobsdata:`, except `StartCommandExecution`, which stays on `iot:`. A policy written for the old action names stops matching, as on AWS. Contributed by @iot-rocket.
+- **Lambda — a layer shared through `AddLayerVersionPermission` attaches** — every layer ARN from another account was refused before the stored policy was read. Attachment, from the API and from a CloudFormation function, and `GetLayerVersionByArn` now evaluate it for account, root, public and organization grants, and an attached function keeps the content after the grant is revoked or the version is deleted. A foreign layer version that no grant covers stays refused. Contributed by @iot-rocket.
## [1.5.12] — 2026-09-15
diff --git a/ministack/app.py b/ministack/app.py
index 14482dc6..18ce9611 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -1265,10 +1265,12 @@ async def _handle_post_body_shortcuts(
logging.getLogger("cloudformation").warning("CFN ResponseURL PUT for unknown token %r — ignoring", token)
return 200, {}, b""
- # CloudFormation WaitConditionHandle signal URL (the presigned S3 URL on AWS)
- from ministack.services.cloudformation import wait_conditions as _cfn_wc
+ # CloudFormation WaitConditionHandle signal URL (the presigned S3 URL on AWS).
+ # The literal keeps the import behind the check; above it, the first request
+ # to any service pulled in the whole CloudFormation package.
+ if method == "PUT" and path.startswith("/_ministack/cfn-signal/"):
+ from ministack.services.cloudformation import wait_conditions as _cfn_wc
- if method == "PUT" and path.startswith(_cfn_wc.SIGNAL_PATH):
token = path[len(_cfn_wc.SIGNAL_PATH) :]
if not _cfn_wc.has_handle(token):
logging.getLogger("cloudformation").warning("CFN wait condition signal for unknown token %r", token)
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 8298704e..17d89810 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -67,6 +67,7 @@ from ministack.core.responses import (
set_request_account_id,
set_request_region,
)
+from ministack.core.router import extract_access_key_id
from ministack.core.sigv4 import (
build_canonical_request,
build_string_to_sign,
@@ -761,6 +762,156 @@ def _get_object_data(bucket_name: str, key: str, version_id: str | None = None)
return _read_body(bucket_name, key, obj)
+_ACL_GROUP_AUTHENTICATED = "http://acs.amazonaws.com/groups/global/AuthenticatedUsers"
+# The permissions that answer a read and a write, FULL_CONTROL covering both.
+_ACL_READ_PERMS = ("READ", "FULL_CONTROL")
+_ACL_WRITE_PERMS = ("WRITE", "FULL_CONTROL")
+
+
+def _acl_group_grants(stored_xml: str | None) -> list[tuple[str, str]]:
+ """``(group URI, permission)`` for every Group grant in a stored ACL."""
+ if not stored_xml:
+ return []
+ try:
+ root = fromstring(stored_xml.encode() if isinstance(stored_xml, str) else stored_xml)
+ except Exception:
+ return []
+ grants = []
+ for grant in root.iter():
+ if not grant.tag.endswith("Grant"):
+ continue
+ uri = permission = ""
+ for child in grant.iter():
+ if child.tag.endswith("URI") and child.text:
+ uri = child.text.strip()
+ elif child.tag.endswith("Permission") and child.text:
+ permission = child.text.strip()
+ if uri and permission:
+ grants.append((uri, permission))
+ return grants
+
+
+def _public_access_blocked(owner_account: str, bucket_name: str) -> bool:
+ """Whether the bucket's Public Access Block shuts public grants off."""
+ record = _buckets.get_scoped(owner_account, None, bucket_name) or {}
+ stored = record.get("_public_access_block")
+ if not stored:
+ return False
+ try:
+ root = fromstring(stored.encode() if isinstance(stored, str) else stored)
+ except Exception:
+ return False
+ for child in root.iter():
+ if child.tag.endswith(("BlockPublicAcls", "RestrictPublicBuckets",
+ "BlockPublicPolicy", "IgnorePublicAcls")):
+ if (child.text or "").strip().lower() == "true":
+ return True
+ return False
+
+
+def _account_from_access_key(access_key: str) -> str:
+ """The tenant an access key selects, the way the router scopes a request."""
+ try:
+ return find_iam_access_key_account(access_key) or access_key
+ except AmbiguousAccessKeyError:
+ return ""
+
+
+def _bucket_owner_account(name: str) -> str | None:
+ """The account that owns *name*, or None.
+
+ "General purpose buckets exist in a global namespace, which means that each
+ bucket name must be unique across all AWS accounts in all the AWS Regions
+ within a partition" — so a name identifies one bucket, whoever asks. The
+ store stays account-scoped; this is the index over it.
+ """
+ for account_id, bucket_name in _buckets._data:
+ if bucket_name == name:
+ return account_id
+ return None
+
+
+def _foreign_bucket_allows(owner_account: str, bucket_name: str, key: str,
+ method: str, query_params: dict, caller: str) -> bool:
+ """Whether a caller who does not own the bucket may have this request.
+
+ The owner's grants decide it: a Group grant on the bucket or the object
+ ACL, or an allow in the bucket policy. Nothing granted means the request
+ is denied, which is S3's default for a bucket nobody has opened up.
+ """
+ if _public_access_blocked(owner_account, bucket_name):
+ return False
+ wants = _ACL_READ_PERMS if method in ("GET", "HEAD") else _ACL_WRITE_PERMS
+ groups = [_ACL_GROUP_ALL_USERS] if not caller else [
+ _ACL_GROUP_ALL_USERS, _ACL_GROUP_AUTHENTICATED]
+
+ acls = [_bucket_acl.get_scoped(owner_account, None, bucket_name)]
+ if key:
+ acls.append(_object_acl.get_scoped(owner_account, None, (bucket_name, key, "")))
+ for stored in acls:
+ for uri, permission in _acl_group_grants(stored):
+ if uri in groups and permission in wants:
+ return True
+
+ policy = _bucket_policies.get_scoped(owner_account, None, bucket_name)
+ if policy:
+ from ministack.core.iam_evaluator import EvalContext, evaluate_resource_policy
+
+ action = "s3:GetObject" if method in ("GET", "HEAD") else "s3:PutObject"
+ resource = f"arn:aws:s3:::{bucket_name}"
+ ctx = EvalContext(
+ principal_arn=f"arn:aws:iam::{caller}:root" if caller else "*",
+ principal_type="Root" if caller else "Anonymous",
+ principal_account=caller or "",
+ action=action,
+ resource_arn=f"{resource}/{key}" if key else resource,
+ region=get_region(),
+ )
+ if evaluate_resource_policy(policy, ctx).decision == "Allow":
+ return True
+ return False
+
+
+def _request_access_key(method: str, key: str, headers: dict, query_params: dict,
+ body: bytes) -> str:
+ """The caller's access key, including the one a browser POST signs into its
+ form rather than a header or the query string."""
+ access_key = extract_access_key_id(headers, query_params)
+ if not access_key and method == "POST" and not key:
+ access_key = _post_form_access_key_id(
+ _parse_multipart_form(headers.get("content-type", ""), body))
+ return access_key
+
+
+def _apply_bucket_scope(method: str, bucket: str, key: str, headers: dict,
+ query_params: dict, body: bytes = b""):
+ """Resolve the request's bucket in the global namespace and gate it.
+
+ A bucket name identifies one bucket whoever asks, so a request for a name
+ another account owns is answered by that bucket — if its owner granted the
+ access. The scope is pinned to the owner for the rest of the request, so
+ every account-scoped lookup behind this reads the right tenant's state.
+ """
+ if not bucket:
+ return None
+ owner = _bucket_owner_account(bucket)
+ caller = get_account_id()
+ if owner is None or owner == caller:
+ return None
+ if method == "PUT" and not key and not query_params:
+ # CreateBucket answers BucketAlreadyExists for a taken name.
+ return None
+ access_key = _request_access_key(method, key, headers, query_params, body)
+ if access_key and _account_from_access_key(access_key) == owner:
+ # The caller is the owner; the credential just was not in a header.
+ set_request_account_id(owner)
+ return None
+ if not _foreign_bucket_allows(owner, bucket, key, method, query_params, access_key and caller):
+ return _error("AccessDenied", "Access Denied", 403, f"/{bucket}/{key}" if key else f"/{bucket}")
+ set_request_account_id(owner)
+ return None
+
+
def _ensure_bucket(name: str):
return _buckets.get(name)
@@ -1705,6 +1856,13 @@ async def handle_request(
# reach the handlers exactly as a header-signed request delivers them.
headers = _merge_hoisted_amz_headers(headers, query_params)
+ denied = _apply_bucket_scope(method, bucket, key, headers, query_params, body)
+ if denied is not None:
+ status, resp_headers, resp_body = denied
+ resp_headers.setdefault("x-amz-request-id", new_uuid())
+ resp_headers.setdefault("x-amz-id-2", base64.b64encode(os.urandom(48)).decode())
+ return status, resp_headers, resp_body
+
result = _dispatch(method, bucket, key, headers, body, query_params)
status, resp_headers, resp_body = result
@@ -1979,6 +2137,18 @@ def _create_bucket(name: str, body: bytes, headers: dict = None):
if name in _buckets:
# Idempotent: same account already owns it — return 200 like real AWS
return 200, {"Location": f"/{name}"}, b""
+ if _bucket_owner_account(name) is not None:
+ # "After creating a general purpose bucket in the shared global
+ # namespace, that bucket name is unavailable for anyone else to create
+ # within a partition."
+ return _error(
+ "BucketAlreadyExists",
+ "The requested bucket name is not available. The bucket namespace "
+ "is shared by all users of the system. Please select a different "
+ "name and try again.",
+ 409,
+ f"/{name}",
+ )
region = None
tags = {}
diff --git a/pyproject.toml b/pyproject.toml
index d0039475..3bcc69b7 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.5.12"
+version = "1.5.13"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_router.py b/tests/test_router.py
index 45916101..3571ee5a 100644
--- a/tests/test_router.py
+++ b/tests/test_router.py
@@ -4,6 +4,11 @@ Pure routing-layer tests — no boto3, no live server. Covers the path-based
fallback (i.e. when neither X-Amz-Target nor a SigV4 credential scope is
available to disambiguate the service).
"""
+import os
+import subprocess
+import sys
+import textwrap
+
import pytest
from ministack.core.router import detect_service
@@ -474,3 +479,54 @@ def test_location_host_routes(host):
assert detect_service(
"POST", "/tracking/v0/trackers", {"host": host}, {}
) == "location"
+
+
+# ---------------------------------------------------------------------------
+# What a request pulls in
+# ---------------------------------------------------------------------------
+
+
+def test_first_request_does_not_import_cloudformation():
+ """A request to any service must not load the CloudFormation package.
+
+ In a subprocess: the rest of the suite has imported everything already.
+ """
+ src = textwrap.dedent(
+ """
+ import asyncio, sys
+ from ministack.app import app
+
+ async def receive():
+ return {"type": "http.request", "body": b""}
+
+ async def send(message):
+ pass
+
+ for method in ("GET", "PUT", "POST"):
+ asyncio.run(app(
+ {"type": "http", "method": method, "path": "/",
+ "query_string": b"", "headers": []},
+ receive, send,
+ ))
+ print(",".join(
+ m for m in ("ministack.services.cloudformation", "ministack.services.appsync", "graphql")
+ if m in sys.modules
+ ))
+ """
+ )
+ proc = subprocess.run(
+ [sys.executable, "-c", src],
+ capture_output=True,
+ text=True,
+ cwd=os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
+ env={**os.environ, "IOT_MTLS_ENABLED": "0"},
+ )
+ assert proc.returncode == 0, proc.stderr
+ assert proc.stdout.strip() == "", f"request imported {proc.stdout.strip()}"
+
+
+def test_cfn_signal_prefix_matches_wait_conditions():
+ """Guards the literal in app.py against drifting from the module."""
+ from ministack.services.cloudformation import wait_conditions
+
+ assert wait_conditions.SIGNAL_PATH == "/_ministack/cfn-signal/"