Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix: re add tests due merge conflicts (#1196)
Nahuel Nucera1c1770285cab
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 45456a39..e005b65e 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -2439,6 +2439,27 @@ def _apigw_request_validator_delete(physical_id, props):pass+# --- API Gateway DocumentationVersion ---++def _apigw_documentation_version_identity(props):+ return f"{props.get('RestApiId', '')}/{props.get('DocumentationVersion', '')}"+++def _apigw_documentation_version_create(logical_id, props, stack_name):+ # Documentation snapshots do not affect MiniStack's permissive local API+ # request handling. A native CFN identity is sufficient for templates and+ # dependent resources to complete their lifecycle.+ return _apigw_documentation_version_identity(props), {}+++def _apigw_documentation_version_update(physical_id, old_props, new_props, stack_name):+ return _apigw_documentation_version_identity(new_props), {}+++def _apigw_documentation_version_delete(physical_id, props):+ pass++# --- Lambda EventSourceMapping ---def _lambda_esm_create(logical_id, props, stack_name):@@ -5317,6 +5338,7 @@ _RESOURCE_HANDLERS = {"create": _apigw_request_validator_create,"update": _apigw_request_validator_update,"delete": _apigw_request_validator_delete,+ },"AWS::ApiGateway::DocumentationVersion": {"create": _apigw_documentation_version_create,"update": _apigw_documentation_version_update,diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex fbe734bc..35f63750 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -995,6 +995,18 @@ def _normalize_endpoint_url(value: str) -> str:return f"http://{host}"+def _rewrite_host_for_container(url: str) -> str:+ """Rewrite a ``localhost``/``127.0.0.1`` URL to ``host.docker.internal`` so a+ Docker Lambda container can reach ministack on the host. Explicitly+ configured hosts (e.g. a Docker-network name) are left untouched."""+ if not url:+ return url+ for host in ("localhost", "127.0.0.1"):+ url = url.replace(f"://{host}:", "://host.docker.internal:")+ url = url.replace(f"://{host}/", "://host.docker.internal/")+ return url++def _fetch_code_from_s3(bucket: str, key: str, version_id: str | None = None) -> bytes | None:"""Fetch Lambda code zip from the in-memory S3 service.@@ -3085,6 +3097,13 @@ def _docker_cp_dir(container, src_dir: str, dest_dir: str, arcname: str = "."):def _invoke_rie(container, event: dict, timeout: int) -> dict:"""POST event to a running RIE container's HTTP endpoint."""import urllib.request+ # A CloudFormation custom-resource ResponseURL points at ministack on the+ # host; rewrite localhost/127.0.0.1 to host.docker.internal so the callback+ # is reachable from inside the container (issue #1149), consistent with the+ # AWS_ENDPOINT_URL rewrite. Without this the PUT fails with ConnectionRefused+ # and the stack hangs on the custom resource until ServiceTimeout.+ if isinstance(event, dict) and event.get("ResponseURL"):+ event = {**event, "ResponseURL": _rewrite_host_for_container(event["ResponseURL"])}max_attempts = int(timeout * 10) + 20for _attempt in range(max_attempts):container.reload()@@ -3346,10 +3365,7 @@ def _spawn_lambda_container(config: dict, code_zip: bytes | None):endpoint = f"http://host.docker.internal:{port}"else:# Rewrite localhost/127.0.0.1 → host.docker.internal for container access- endpoint = endpoint.replace("://localhost:", "://host.docker.internal:")- endpoint = endpoint.replace("://localhost/", "://host.docker.internal/")- endpoint = endpoint.replace("://127.0.0.1:", "://host.docker.internal:")- endpoint = endpoint.replace("://127.0.0.1/", "://host.docker.internal/")+ endpoint = _rewrite_host_for_container(endpoint)container_env["AWS_ENDPOINT_URL"] = endpoint# Mounts (Zip only — Image bakes code in). Layers are NEVER bind-mounted:diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 786eac21..65106859 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -1994,6 +1994,56 @@ def test_cfn_appsync_function_configuration_attributes(cfn, appsync):passappsync.delete_graphql_api(apiId=api_id)++def test_cfn_ec2_vpc_endpoint_uses_ec2_state(cfn, ec2):+ """CloudFormation VPC endpoints share the EC2 API state and expose their ID."""+ suffix = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-vpce-{suffix}"+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Vpc": {+ "Type": "AWS::EC2::VPC",+ "Properties": {"CidrBlock": "10.40.0.0/16"},+ },+ "Endpoint": {+ "Type": "AWS::EC2::VPCEndpoint",+ "Properties": {+ "VpcEndpointType": "Gateway",+ "VpcId": {"Ref": "Vpc"},+ "ServiceName": "com.amazonaws.us-east-1.s3",+ "Tags": [{"Key": "source", "Value": "cloudformation"}],+ },+ },+ },+ "Outputs": {+ "RefId": {"Value": {"Ref": "Endpoint"}},+ "GetAttId": {"Value": {"Fn::GetAtt": ["Endpoint", "Id"]}},+ },+ }++ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ outputs = {item["OutputKey"]: item["OutputValue"] for item in stack["Outputs"]}+ assert outputs["RefId"] == outputs["GetAttId"]+ assert outputs["RefId"].startswith("vpce-")++ endpoints = ec2.describe_vpc_endpoints(+ VpcEndpointIds=[outputs["RefId"]]+ )["VpcEndpoints"]+ assert len(endpoints) == 1+ assert endpoints[0]["VpcEndpointId"] == outputs["RefId"]+ assert endpoints[0]["ServiceName"] == "com.amazonaws.us-east-1.s3"+ assert endpoints[0]["Tags"] == [{"Key": "source", "Value": "cloudformation"}]++ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+ assert ec2.describe_vpc_endpoints(+ VpcEndpointIds=[outputs["RefId"]]+ )["VpcEndpoints"] == []++def test_cfn_elbv2_load_balancer_and_listener(cfn, elbv2):"""CloudFormation provisions ELBv2 LoadBalancer + Listener and cleans both on delete."""uid = _uuid_mod.uuid4().hex[:8]@@ -5222,6 +5272,67 @@ def test_cfn_apigateway_request_validator_identity(cfn, apigw_v1):apigw_v1.delete_rest_api(restApiId=api_id)+def test_cfn_apigateway_documentation_version_lifecycle(cfn, apigw_v1):+ """DocumentationVersion has a stable CFN identity and supports replacement."""+ suffix = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-documentation-version-{suffix}"+ api_id = apigw_v1.create_rest_api(name=f"documentation-version-{suffix}")["id"]++ def template(version, description):+ return {+ "Resources": {+ "DocumentationVersion": {+ "Type": "AWS::ApiGateway::DocumentationVersion",+ "Properties": {+ "RestApiId": api_id,+ "DocumentationVersion": version,+ "Description": description,+ },+ },+ },+ }++ def physical_id():+ detail = cfn.describe_stack_resource(+ StackName=stack_name,+ LogicalResourceId="DocumentationVersion",+ )["StackResourceDetail"]+ return detail["PhysicalResourceId"]++ try:+ cfn.create_stack(+ StackName=stack_name,+ TemplateBody=json.dumps(template("v1", "Created")),+ )+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ created_id = physical_id()+ assert created_id == f"{api_id}/v1"++ cfn.update_stack(+ StackName=stack_name,+ TemplateBody=json.dumps(template("v1", "Updated")),+ )+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ assert physical_id() == created_id++ cfn.update_stack(+ StackName=stack_name,+ TemplateBody=json.dumps(template("v2", "Replacement")),+ )+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ assert physical_id() == f"{api_id}/v2"+ finally:+ try:+ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+ except ClientError:+ pass+ apigw_v1.delete_rest_api(restApiId=api_id)++# ---------------------------------------------------------------------------# ApiGatewayV1 Integration with OpenAPI spec parsing# ---------------------------------------------------------------------------diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex dee49c72..003c5662 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -8420,3 +8420,58 @@ def test_lambda_durable_resume_captures_region_and_account():d._executions._data.pop(("111111111111", arn), None)_request_account_id.reset(tok_a)_request_region.reset(tok_r)+++def test_rewrite_host_for_container_rewrites_localhost():+ from ministack.services.lambda_svc import _rewrite_host_for_container as rw+ assert rw("http://localhost:4566/_ministack/cfn-response/tok") == \+ "http://host.docker.internal:4566/_ministack/cfn-response/tok"+ assert rw("http://127.0.0.1:4566/x") == "http://host.docker.internal:4566/x"+ # Explicit Docker-network hostnames and empty values are left untouched.+ assert rw("http://ministack:4566/x") == "http://ministack:4566/x"+ assert rw("http://host.docker.internal:4566/x") == "http://host.docker.internal:4566/x"+ assert rw("") == ""+++def test_invoke_rie_rewrites_custom_resource_response_url():+ """Regression for #1149: a docker-executed custom resource's ResponseURL+ (default localhost) must be rewritten to host.docker.internal before the+ event is POSTed to the RIE, or the callback hits the container itself and+ the stack hangs to ServiceTimeout."""+ from ministack.services.lambda_svc import _invoke_rie++ class _FakeContainer:+ status = "running"+ attrs = {"NetworkSettings": {"Networks": {}}}+ ports = {"8080/tcp": [{"HostPort": "12345"}]}++ def reload(self):+ pass++ def logs(self, **_kw):+ return b""++ class _FakeResp:+ headers = {}++ def read(self):+ return json.dumps({"Status": "SUCCESS"}).encode()++ captured = {}++ def _fake_urlopen(req, timeout=None):+ captured["body"] = json.loads(req.data.decode())+ return _FakeResp()++ event = {+ "RequestType": "Create",+ "ResponseURL": "http://localhost:4566/_ministack/cfn-response/tok",+ "ResourceProperties": {},+ }+ with patch("urllib.request.urlopen", _fake_urlopen):+ _invoke_rie(_FakeContainer(), event, timeout=5)++ assert captured["body"]["ResponseURL"] == \+ "http://host.docker.internal:4566/_ministack/cfn-response/tok"+ # The caller's event dict must not be mutated in place.+ assert event["ResponseURL"] == "http://localhost:4566/_ministack/cfn-response/tok"diff --git a/tests/test_persistence.py b/tests/test_persistence.pyindex 70152aeb..1532d93b 100644--- a/tests/test_persistence.py+++ b/tests/test_persistence.py@@ -2078,6 +2078,219 @@ def test_batch_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmp_patassert persistence.load_state("batch") is None+def test_autoscaling_region_scoped_state_is_rejected_by_v2_reader(+ monkeypatch, tmp_path+):+ """A rollback binary must reject Auto Scaling's regional schema instead+ of accepting it as v2 and silently dropping every regional store."""+ import json as _json++ from ministack.core.responses import AccountRegionScopedDict++ monkeypatch.setattr(persistence, "PERSIST_STATE", True)+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))++ asgs = AccountRegionScopedDict()+ asgs.set_scoped(+ "000000000000",+ "us-west-2",+ "regional-asg",+ {+ "AutoScalingGroupARN": (+ "arn:aws:autoscaling:us-west-2:000000000000:"+ "autoScalingGroup:regional:autoScalingGroupName/regional-asg"+ )+ },+ )+ persistence.save_state("autoscaling", {"asgs": asgs})++ raw = _json.loads((tmp_path / "autoscaling.json").read_text())+ assert raw["__ministack_format__"] == 3+ loaded_asgs = persistence.load_state("autoscaling")["asgs"]+ assert loaded_asgs.get_scoped(+ "000000000000", "us-west-2", "regional-asg"+ )["AutoScalingGroupARN"].endswith("autoScalingGroupName/regional-asg")++ # Simulate the previous binary, whose highest understood format is v2.+ monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})+ assert persistence.load_state("autoscaling") is None+++def test_athena_region_scoped_state_is_rejected_by_v2_reader(+ monkeypatch, tmp_path+):+ """A rollback binary must reject Athena's regional schema instead of+ accepting it as v2 and silently dropping every regional store."""+ import json as _json++ from ministack.core.responses import AccountRegionScopedDict++ monkeypatch.setattr(persistence, "PERSIST_STATE", True)+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))++ workgroups = AccountRegionScopedDict()+ workgroups.set_scoped(+ "000000000000",+ "us-west-2",+ "regional-workgroup",+ {"Name": "regional-workgroup", "Description": "west"},+ )+ persistence.save_state("athena", {"_workgroups": workgroups})++ raw = _json.loads((tmp_path / "athena.json").read_text())+ assert raw["__ministack_format__"] == 3+ loaded_workgroups = persistence.load_state("athena")["_workgroups"]+ assert loaded_workgroups.get_scoped(+ "000000000000", "us-west-2", "regional-workgroup"+ )["Description"] == "west"++ # Simulate the previous binary, whose highest understood format is v2.+ monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})+ assert persistence.load_state("athena") is None+++def test_inspector2_region_scoped_state_is_rejected_by_v2_reader(+ monkeypatch, tmp_path+):+ """A rollback binary must reject Inspector2 regional account buckets."""+ import json as _json++ from ministack.core.responses import AccountRegionScopedDict++ monkeypatch.setattr(persistence, "PERSIST_STATE", True)+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))++ configs = AccountRegionScopedDict()+ configs.set_scoped(+ "000000000000",+ "us-west-2",+ "000000000000",+ {"ecr": {"status": "ENABLED"}},+ )+ persistence.save_state("inspector2", {"account_config": configs})++ raw = _json.loads((tmp_path / "inspector2.json").read_text())+ assert raw["__ministack_format__"] == 3+ loaded = persistence.load_state("inspector2")["account_config"]+ assert loaded.get_scoped(+ "000000000000", "us-west-2", "000000000000"+ ) == {"ecr": {"status": "ENABLED"}}++ monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})+ assert persistence.load_state("inspector2") is None+++def test_efs_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmp_path):+ """A rollback binary must reject EFS regional state instead of dropping it."""+ import json as _json++ from ministack.core.responses import AccountRegionScopedDict++ monkeypatch.setattr(persistence, "PERSIST_STATE", True)+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))++ file_systems = AccountRegionScopedDict()+ file_systems.set_scoped(+ "000000000000",+ "us-west-2",+ "fs-11111111111111111",+ {+ "FileSystemId": "fs-11111111111111111",+ "FileSystemArn": (+ "arn:aws:elasticfilesystem:us-west-2:000000000000:"+ "file-system/fs-11111111111111111"+ ),+ },+ )+ persistence.save_state("efs", {"file_systems": file_systems})++ raw = _json.loads((tmp_path / "efs.json").read_text())+ assert raw["__ministack_format__"] == 3+ loaded = persistence.load_state("efs")["file_systems"]+ assert loaded.get_scoped(+ "000000000000", "us-west-2", "fs-11111111111111111"+ )["FileSystemId"] == "fs-11111111111111111"++ monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})+ assert persistence.load_state("efs") is None+++def test_s3files_region_scoped_state_is_rejected_by_v2_reader(+ monkeypatch, tmp_path+):+ """A rollback binary must reject S3 Files' regional schema instead of+ accepting it as v2 and silently dropping every regional store."""+ import json as _json++ from ministack.core.responses import AccountRegionScopedDict++ monkeypatch.setattr(persistence, "PERSIST_STATE", True)+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))++ file_systems = AccountRegionScopedDict()+ file_systems.set_scoped(+ "000000000000",+ "us-west-2",+ "fs-11111111111111111",+ {+ "fileSystemId": "fs-11111111111111111",+ "fileSystemArn": (+ "arn:aws:s3files:us-west-2:000000000000:"+ "file-system/fs-11111111111111111"+ ),+ },+ )+ persistence.save_state("s3files", {"file_systems": file_systems})++ raw = _json.loads((tmp_path / "s3files.json").read_text())+ assert raw["__ministack_format__"] == 3+ loaded_file_systems = persistence.load_state("s3files")["file_systems"]+ assert loaded_file_systems.get_scoped(+ "000000000000", "us-west-2", "fs-11111111111111111"+ )["fileSystemId"] == "fs-11111111111111111"++ # Simulate the previous binary, whose highest understood format is v2.+ monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})+ assert persistence.load_state("s3files") is None+++def test_servicediscovery_region_scoped_state_is_rejected_by_v2_reader(+ monkeypatch, tmp_path+):+ """A rollback binary must reject Cloud Map's regional schema instead of+ accepting it as v2 and silently dropping every regional store."""+ import json as _json++ from ministack.core.responses import AccountRegionScopedDict++ monkeypatch.setattr(persistence, "PERSIST_STATE", True)+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))++ namespaces = AccountRegionScopedDict()+ namespaces.set_scoped(+ "000000000000",+ "us-west-2",+ "ns-regional",+ {+ "Arn": (+ "arn:aws:servicediscovery:us-west-2:000000000000:"+ "namespace/ns-regional"+ )+ },+ )+ persistence.save_state("servicediscovery", {"namespaces": namespaces})++ raw = _json.loads((tmp_path / "servicediscovery.json").read_text())+ assert raw["__ministack_format__"] == 3+ loaded_namespaces = persistence.load_state("servicediscovery")["namespaces"]+ assert loaded_namespaces.get_scoped(+ "000000000000", "us-west-2", "ns-regional"+ )["Arn"].endswith("namespace/ns-regional")++ monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})+ assert persistence.load_state("servicediscovery") is None++def test_batch_persistence_lifecycle_restores_regional_state(monkeypatch, tmp_path):"""The gateway save map and Batch import-time restore must preserve stateoutside the ambient boot region across a process-shaped reload."""