Skip to content

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

Regionalize EC2 state (#1224)

Ian Oberstaf9546181836
diff --git a/ministack/core/persistence.py b/ministack/core/persistence.py
index 334ea89f..682ba359 100644
--- a/ministack/core/persistence.py
+++ b/ministack/core/persistence.py
@@ -42,6 +42,7 @@ SERVICE_STATE_FORMAT_VERSIONS = {
"ecs": 3,
"resource_groups": 3,
"codebuild": 3,
+ "ec2": 3,
"cloudtrail": 3,
"mq": 3,
"mwaa": 3,
diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.py
index bae7b498..1ea83e55 100644
--- a/ministack/services/cloudformation/changesets.py
+++ b/ministack/services/cloudformation/changesets.py
@@ -2,12 +2,11 @@
CloudFormation change set handlers — Create, Describe, Execute, Delete, List change sets.
"""
-import asyncio
import copy
import json
import logging
-from ministack.core.responses import get_account_id, new_uuid, now_iso
+from ministack.core.responses import get_account_id, get_region, new_uuid, now_iso
from .engine import (
_NO_VALUE,
@@ -18,8 +17,14 @@ from .engine import (
_resolve_refs,
)
from .helpers import CFN_NS, _error, _esc, _extract_members, _p, _resolve_template, _xml
-from .provisioners import REGION
-from .stacks import _add_event, _deploy_stack_async, _diff_resources
+from .stacks import (
+ _add_event,
+ _create_stack_task_in_region,
+ _deploy_stack_async,
+ _diff_resources,
+ _stack_region,
+ _stack_region_context,
+)
logger = logging.getLogger("cloudformation")
@@ -100,7 +105,7 @@ def _create_change_set(params):
# Create a placeholder stack in REVIEW_IN_PROGRESS
stack_id = (
- f"arn:aws:cloudformation:{REGION}:{get_account_id()}:"
+ f"arn:aws:cloudformation:{get_region()}:{get_account_id()}:"
f"stack/{stack_name}/{new_uuid()}"
)
stack = {
@@ -115,6 +120,7 @@ def _create_change_set(params):
"Tags": tags,
"Outputs": [],
"DisableRollback": False,
+ "_region": get_region(),
"_resources": {},
"_template": {},
"_template_body": "",
@@ -152,12 +158,13 @@ def _create_change_set(params):
# detected instead of compared as identical raw nodes (#897).
old_template = stack.get("_template", {}) if cs_type == "UPDATE" else {}
old_params = stack.get("_resolved_params", {}) if cs_type == "UPDATE" else {}
- old_resolved = _resolve_props_for_diff(old_template, old_params, stack_name, stack_id)
- new_resolved = _resolve_props_for_diff(template, param_values, stack_name, stack_id)
+ with _stack_region_context(stack, stack_id):
+ old_resolved = _resolve_props_for_diff(old_template, old_params, stack_name, stack_id)
+ new_resolved = _resolve_props_for_diff(template, param_values, stack_name, stack_id)
changes = _diff_resources(old_resolved, new_resolved)
cs_id = (
- f"arn:aws:cloudformation:{REGION}:{get_account_id()}:"
+ f"arn:aws:cloudformation:{_stack_region(stack, stack_id)}:{get_account_id()}:"
f"changeSet/{cs_name}/{new_uuid()}"
)
@@ -300,18 +307,21 @@ def _execute_change_set(params):
{"ParameterKey": k, "ParameterValue": v["Value"], "NoEcho": v["NoEcho"]}
for k, v in param_values.items()
]
- stack["_conditions"] = _evaluate_conditions(template, param_values)
+ with _stack_region_context(stack, stack_id):
+ stack["_conditions"] = _evaluate_conditions(template, param_values)
- _add_event(stack_id, real_stack_name, real_stack_name,
- "AWS::CloudFormation::Stack", f"{status_prefix}_IN_PROGRESS",
- physical_id=stack_id)
+ _add_event(stack_id, real_stack_name, real_stack_name,
+ "AWS::CloudFormation::Stack", f"{status_prefix}_IN_PROGRESS",
+ physical_id=stack_id)
- asyncio.get_event_loop().create_task(
- _deploy_stack_async(real_stack_name, stack_id, template,
- param_values, False, tags,
- is_update=is_update,
- previous_stack=previous_stack)
- )
+ _create_stack_task_in_region(
+ _deploy_stack_async(real_stack_name, stack_id, template,
+ param_values, False, tags,
+ is_update=is_update,
+ previous_stack=previous_stack),
+ stack,
+ stack_id,
+ )
cs["ExecutionStatus"] = "EXECUTE_COMPLETE"
cs["Status"] = "EXECUTE_COMPLETE"
@@ -366,4 +376,3 @@ def _list_change_sets(params):
# --- GetTemplateSummary ---
-
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index 4e8bb3dd..22ea1d15 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -2,7 +2,6 @@
CloudFormation handlers — API action handlers for all supported CloudFormation actions.
"""
-import asyncio
import copy
import json
import logging
@@ -26,7 +25,14 @@ from .engine import (
)
from .helpers import CFN_NS, _error, _esc, _extract_members, _extract_stack_status_filters, _p, _resolve_template, _xml
from .provisioners import _provision_resource
-from .stacks import _add_event, _delete_stack_async, _deploy_stack_async, _diff_resources
+from .stacks import (
+ _add_event,
+ _create_stack_task_in_region,
+ _delete_stack_async,
+ _deploy_stack_async,
+ _diff_resources,
+ _stack_region_context,
+)
logger = logging.getLogger("cloudformation")
@@ -92,6 +98,7 @@ def _create_stack(params):
"Tags": tags,
"Outputs": [],
"DisableRollback": disable_rollback,
+ "_region": get_region(),
"_resources": {},
"_template": template,
"_template_body": template_body,
@@ -105,9 +112,11 @@ def _create_stack(params):
"AWS::CloudFormation::Stack", "CREATE_IN_PROGRESS",
physical_id=stack_id)
- asyncio.get_event_loop().create_task(
+ _create_stack_task_in_region(
_deploy_stack_async(stack_name, stack_id, template,
- param_values, disable_rollback, tags)
+ param_values, disable_rollback, tags),
+ stack,
+ stack_id,
)
return _xml(200, "CreateStackResponse",
@@ -439,7 +448,11 @@ def _delete_stack(params):
f"Export {export_name} is imported by stack {other_name}")
stack_id = stack["StackId"]
- asyncio.get_event_loop().create_task(_delete_stack_async(stack_name, stack_id))
+ _create_stack_task_in_region(
+ _delete_stack_async(stack_name, stack_id),
+ stack,
+ stack_id,
+ )
return _xml(200, "DeleteStackResponse", "")
@@ -508,17 +521,20 @@ def _update_stack(params):
{"ParameterKey": k, "ParameterValue": v["Value"], "NoEcho": v["NoEcho"]}
for k, v in param_values.items()
]
- stack["_conditions"] = _evaluate_conditions(template, param_values)
-
- _add_event(stack_id, stack_name, stack_name,
- "AWS::CloudFormation::Stack", "UPDATE_IN_PROGRESS",
- physical_id=stack_id)
-
- asyncio.get_event_loop().create_task(
- _deploy_stack_async(stack_name, stack_id, template,
- param_values, disable_rollback, tags,
- is_update=True, previous_stack=previous_stack)
- )
+ with _stack_region_context(stack, stack_id):
+ stack["_conditions"] = _evaluate_conditions(template, param_values)
+
+ _add_event(stack_id, stack_name, stack_name,
+ "AWS::CloudFormation::Stack", "UPDATE_IN_PROGRESS",
+ physical_id=stack_id)
+
+ _create_stack_task_in_region(
+ _deploy_stack_async(stack_name, stack_id, template,
+ param_values, disable_rollback, tags,
+ is_update=True, previous_stack=previous_stack),
+ stack,
+ stack_id,
+ )
return _xml(200, "UpdateStackResponse",
f"<UpdateStackResult><StackId>{stack_id}</StackId></UpdateStackResult>")
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 7da5455b..516ac092 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -3301,6 +3301,7 @@ def _ec2_vpc_endpoint_attributes(endpoint):
def _ec2_vpc_endpoint_create(logical_id, props, stack_name):
+ _ec2._ensure_defaults_initialized()
endpoint_id = "vpce-" + "".join(random.choices(string.hexdigits[:16], k=17))
endpoint = {
"VpcEndpointId": endpoint_id,
@@ -3329,6 +3330,7 @@ def _ec2_vpc_endpoint_create(logical_id, props, stack_name):
def _ec2_vpc_endpoint_update(physical_id, old_props, new_props, stack_name):
+ _ec2._ensure_defaults_initialized()
endpoint = _ec2._vpc_endpoints.get(physical_id)
if not endpoint:
return _ec2_vpc_endpoint_create(physical_id, new_props, stack_name)
@@ -3384,6 +3386,7 @@ def _ec2_subnet_delete(physical_id, props):
def _ec2_sg_create(logical_id, props, stack_name):
+ _ec2._ensure_defaults_initialized()
name = props.get("GroupName", f"{stack_name}-{logical_id}")
desc = props.get("GroupDescription", name)
vpc_id = props.get("VpcId", _ec2._DEFAULT_VPC_ID)
@@ -3460,6 +3463,7 @@ def _ec2_vpc_gw_attach_delete(physical_id, props):
def _ec2_rtb_create(logical_id, props, stack_name):
+ _ec2._ensure_defaults_initialized()
import random
import string
vpc_id = props.get("VpcId", _ec2._DEFAULT_VPC_ID)
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index 87f89de8..202cc156 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -7,8 +7,9 @@ import copy
import json
import logging
import time
+from contextlib import contextmanager
-from ministack.core.responses import get_account_id, new_uuid, now_iso
+from ministack.core.responses import get_account_id, get_region, new_uuid, now_iso, set_request_region
from .engine import (
_NO_VALUE,
@@ -18,11 +19,42 @@ from .engine import (
_resolve_refs,
_topological_sort,
)
-from .provisioners import REGION, _delete_resource, _provision_resource, _update_resource
+from .provisioners import _delete_resource, _provision_resource, _update_resource
logger = logging.getLogger("cloudformation")
+def _region_from_stack_id(stack_id: str | None) -> str | None:
+ if not stack_id:
+ return None
+ parts = stack_id.split(":")
+ if len(parts) > 3 and parts[3]:
+ return parts[3]
+ return None
+
+
+def _stack_region(stack: dict | None, stack_id: str | None = None) -> str:
+ if stack:
+ return stack.get("_region") or _region_from_stack_id(stack.get("StackId")) or get_region()
+ return _region_from_stack_id(stack_id) or get_region()
+
+
+@contextmanager
+def _stack_region_context(stack: dict | None, stack_id: str | None = None):
+ previous_region = get_region()
+ set_request_region(_stack_region(stack, stack_id))
+ try:
+ yield
+ finally:
+ set_request_region(previous_region)
+
+
+def _create_stack_task_in_region(coro, stack: dict | None, stack_id: str | None = None):
+ """Schedule a stack lifecycle coroutine in the stack's owning region."""
+ with _stack_region_context(stack, stack_id):
+ asyncio.get_event_loop().create_task(coro)
+
+
def _is_custom_resource(resource_type: str) -> bool:
return resource_type.startswith("Custom::") or resource_type == "AWS::CloudFormation::CustomResource"
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index a941214d..2b561162 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -72,7 +72,13 @@ from urllib.parse import parse_qs
from xml.sax.saxutils import escape as _esc
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import AccountScopedDict, get_account_id, get_region, new_uuid
+from ministack.core.responses import (
+ AccountRegionScopedDict,
+ AccountScopedDict,
+ get_account_id,
+ get_region,
+ new_uuid,
+)
logger = logging.getLogger("ec2")
@@ -82,33 +88,36 @@ REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# State
# ---------------------------------------------------------------------------
-_instances = AccountScopedDict()
-_security_groups = AccountScopedDict()
-_key_pairs = AccountScopedDict()
-_placement_groups = AccountScopedDict() # group_name -> placement group record
-_vpcs = AccountScopedDict()
-_subnets = AccountScopedDict()
-_internet_gateways = AccountScopedDict()
-_addresses = AccountScopedDict() # allocation_id -> address record
-_tags = AccountScopedDict() # resource_id -> [{"Key": ..., "Value": ...}]
-_route_tables = AccountScopedDict() # rtb_id -> route table record
-_network_interfaces = AccountScopedDict() # eni_id -> ENI record
-_vpc_endpoints = AccountScopedDict() # vpce_id -> endpoint record
-_volumes = AccountScopedDict() # vol_id -> volume record
-_snapshots = AccountScopedDict() # snap_id -> snapshot record
-_nat_gateways = AccountScopedDict() # nat_id -> NAT gateway record
-_network_acls = AccountScopedDict() # acl_id -> network ACL record
-_flow_logs = AccountScopedDict() # flow_log_id -> flow log record
-_vpc_peering = AccountScopedDict() # pcx_id -> peering connection record
-_dhcp_options = AccountScopedDict() # dopt_id -> DHCP options record
-_egress_igws = AccountScopedDict() # eigw_id -> egress-only internet gateway record
-_prefix_lists = AccountScopedDict() # pl_id -> managed prefix list record
-_vpn_gateways = AccountScopedDict() # vgw_id -> VPN gateway record
-_customer_gateways = AccountScopedDict() # cgw_id -> customer gateway record
-_vpn_connections = AccountScopedDict() # vpn_id -> VPN connection record
-_launch_templates = AccountScopedDict() # lt_id -> launch template record (includes versions list)
-_fleets = AccountScopedDict() # fleet_id -> fleet record
-_iam_instance_profile_associations = AccountScopedDict() # assoc_id -> association record
+_instances = AccountRegionScopedDict()
+_security_groups = AccountRegionScopedDict()
+_key_pairs = AccountRegionScopedDict()
+_placement_groups = AccountRegionScopedDict() # group_name -> placement group record
+_vpcs = AccountRegionScopedDict()
+_subnets = AccountRegionScopedDict()
+_internet_gateways = AccountRegionScopedDict()
+_addresses = AccountRegionScopedDict() # allocation_id -> address record
+_tags = AccountRegionScopedDict() # resource_id -> [{"Key": ..., "Value": ...}]
+_route_tables = AccountRegionScopedDict() # rtb_id -> route table record
+_network_interfaces = AccountRegionScopedDict() # eni_id -> ENI record
+_vpc_endpoints = AccountRegionScopedDict() # vpce_id -> endpoint record
+_volumes = AccountRegionScopedDict() # vol_id -> volume record
+_snapshots = AccountRegionScopedDict() # snap_id -> snapshot record
+_nat_gateways = AccountRegionScopedDict() # nat_id -> NAT gateway record
+_network_acls = AccountRegionScopedDict() # acl_id -> network ACL record
+_flow_logs = AccountRegionScopedDict() # flow_log_id -> flow log record
+_vpc_peering = AccountRegionScopedDict() # pcx_id -> peering connection record
+_dhcp_options = AccountRegionScopedDict() # dopt_id -> DHCP options record
+_egress_igws = AccountRegionScopedDict() # eigw_id -> egress-only internet gateway record
+_prefix_lists = AccountRegionScopedDict() # pl_id -> managed prefix list record
+_vpn_gateways = AccountRegionScopedDict() # vgw_id -> VPN gateway record
+_customer_gateways = AccountRegionScopedDict() # cgw_id -> customer gateway record
+_vpn_connections = AccountRegionScopedDict() # vpn_id -> VPN connection record
+_launch_templates = AccountRegionScopedDict() # lt_id -> launch template record (includes versions list)
+_fleets = AccountRegionScopedDict() # fleet_id -> fleet record
+_iam_instance_profile_associations = AccountRegionScopedDict() # assoc_id -> association record
+# Seed defaults once per account/region; do not recreate user-deleted defaults
+# on every later EC2 request in a scope.
+_default_initialized_scopes = set()
@@ -116,6 +125,10 @@ _iam_instance_profile_associations = AccountScopedDict() # assoc_id -> associat
def get_state():
return {
+ "default_initialized_scopes": [
+ {"AccountId": account_id, "Region": region}
+ for account_id, region in sorted(_default_initialized_scopes)
+ ],
"instances": copy.deepcopy(_instances),
"security_groups": copy.deepcopy(_security_groups),
"key_pairs": copy.deepcopy(_key_pairs),
@@ -146,39 +159,160 @@ def get_state():
}
-def restore_state(data):
- if data:
- _instances.update(data.get("instances", {}))
- _security_groups.update(data.get("security_groups", {}))
- _key_pairs.update(data.get("key_pairs", {}))
- _placement_groups.update(data.get("placement_groups", {}))
- _vpcs.update(data.get("vpcs", {}))
- _subnets.update(data.get("subnets", {}))
- _internet_gateways.update(data.get("internet_gateways", {}))
- _addresses.update(data.get("addresses", {}))
- _tags.update(data.get("tags", {}))
- _route_tables.update(data.get("route_tables", {}))
- _network_interfaces.update(data.get("network_interfaces", {}))
- _vpc_endpoints.update(data.get("vpc_endpoints", {}))
- _volumes.update(data.get("volumes", {}))
- _snapshots.update(data.get("snapshots", {}))
- _nat_gateways.update(data.get("nat_gateways", {}))
- _network_acls.update(data.get("network_acls", {}))
- _flow_logs.update(data.get("flow_logs", {}))
- _vpc_peering.update(data.get("vpc_peering", {}))
- _dhcp_options.update(data.get("dhcp_options", {}))
- _egress_igws.update(data.get("egress_igws", {}))
- _prefix_lists.update(data.get("prefix_lists", {}))
- _vpn_gateways.update(data.get("vpn_gateways", {}))
- _customer_gateways.update(data.get("customer_gateways", {}))
- _vpn_connections.update(data.get("vpn_connections", {}))
- _launch_templates.update(data.get("launch_templates", {}))
- _fleets.update(data.get("fleets", {}))
- _iam_instance_profile_associations.update(
- data.get("iam_instance_profile_associations", {})
+def _clear_state():
+ _instances.clear()
+ _security_groups.clear()
+ _key_pairs.clear()
+ _placement_groups.clear()
+ _vpcs.clear()
+ _subnets.clear()
+ _internet_gateways.clear()
+ _addresses.clear()
+ _tags.clear()
+ _route_tables.clear()
+ _network_interfaces.clear()
+ _vpc_endpoints.clear()
+ _volumes.clear()
+ _snapshots.clear()
+ _nat_gateways.clear()
+ _network_acls.clear()
+ _flow_logs.clear()
+ _vpc_peering.clear()
+ _dhcp_options.clear()
+ _egress_igws.clear()
+ _prefix_lists.clear()
+ _vpn_gateways.clear()
+ _customer_gateways.clear()
+ _vpn_connections.clear()
+ _launch_templates.clear()
+ _fleets.clear()
+ _iam_instance_profile_associations.clear()
+ _default_initialized_scopes.clear()
+
+
+def _vpc_peering_scopes(record, default_region=None, account_id=None):
+ default_region = default_region or get_region()
+ scopes = {
+ (
+ record["RequesterVpcInfo"]["OwnerId"],
+ record["RequesterVpcInfo"].get("Region") or default_region,
+ ),
+ (
+ record["AccepterVpcInfo"]["OwnerId"],
+ record["AccepterVpcInfo"].get("Region") or default_region,
+ ),
+ }
+ if account_id is not None:
+ scopes = {scope for scope in scopes if scope[0] == account_id}
+ return scopes
+
+
+def _put_vpc_peering_record(record, default_region=None):
+ pcx_id = record["VpcPeeringConnectionId"]
+ for account_id, region in _vpc_peering_scopes(record, default_region):
+ _vpc_peering.set_scoped(account_id, region, pcx_id, copy.deepcopy(record))
+
+
+def _legacy_vpc_peering_record_for_boot_region(record, region):
+ record = copy.deepcopy(record)
+ record.setdefault("RequesterVpcInfo", {})["Region"] = region
+ record.setdefault("AccepterVpcInfo", {})["Region"] = region
+ return record
+
+
+def _restore_default_initialized_scopes(data):
+ for item in data.get("default_initialized_scopes", []):
+ if isinstance(item, dict):
+ account_id = item.get("AccountId")
+ region = item.get("Region")
+ else:
+ try:
+ account_id, region = item
+ except (TypeError, ValueError):
+ continue
+ if account_id and region:
+ _default_initialized_scopes.add((account_id, region))
+
+
+def _infer_default_initialized_scopes_from_restored_stores():
+ for (account_id, region, _vpc_id), vpc in _vpcs.all_items():
+ if vpc.get("IsDefault"):
+ _default_initialized_scopes.add((account_id, region))
+
+
+def _restore_vpc_peering_store(restored):
+ if isinstance(restored, AccountRegionScopedDict):
+ for (_account_id, region, _key), record in restored.all_items():
+ _put_vpc_peering_record(record, default_region=region)
+ return
+ region = get_region()
+ if isinstance(restored, AccountScopedDict):
+ for (_account_id, _key), record in restored._data.items():
+ _put_vpc_peering_record(
+ _legacy_vpc_peering_record_for_boot_region(record, region),
+ default_region=region,
+ )
+ return
+ for _key, record in restored.items():
+ _put_vpc_peering_record(
+ _legacy_vpc_peering_record_for_boot_region(record, region),
+ default_region=region,
)
+def restore_state(data):
+ if not data:
+ return
+ _clear_state()
+ _restore_default_initialized_scopes(data)
+ _restore_regional_store(_instances, data.get("instances", {}))
+ _restore_regional_store(_security_groups, data.get("security_groups", {}))
+ _restore_regional_store(_key_pairs, data.get("key_pairs", {}))
+ _restore_regional_store(_placement_groups, data.get("placement_groups", {}))
+ _restore_regional_store(_vpcs, data.get("vpcs", {}))
+ _restore_regional_store(_subnets, data.get("subnets", {}))
+ _restore_regional_store(_internet_gateways, data.get("internet_gateways", {}))
+ _restore_regional_store(_addresses, data.get("addresses", {}))
+ _restore_regional_store(_tags, data.get("tags", {}))
+ _restore_regional_store(_route_tables, data.get("route_tables", {}))
+ _restore_regional_store(_network_interfaces, data.get("network_interfaces", {}))
+ _restore_regional_store(_vpc_endpoints, data.get("vpc_endpoints", {}))
+ _restore_regional_store(_volumes, data.get("volumes", {}))
+ _restore_regional_store(_snapshots, data.get("snapshots", {}))
+ _restore_regional_store(_nat_gateways, data.get("nat_gateways", {}))
+ _restore_regional_store(_network_acls, data.get("network_acls", {}))
+ _restore_regional_store(_flow_logs, data.get("flow_logs", {}))
+ _restore_vpc_peering_store(data.get("vpc_peering", {}))
+ _restore_regional_store(_dhcp_options, data.get("dhcp_options", {}))
+ _restore_regional_store(_egress_igws, data.get("egress_igws", {}))
+ _restore_regional_store(_prefix_lists, data.get("prefix_lists", {}))
+ _restore_regional_store(_vpn_gateways, data.get("vpn_gateways", {}))
+ _restore_regional_store(_customer_gateways, data.get("customer_gateways", {}))
+ _restore_regional_store(_vpn_connections, data.get("vpn_connections", {}))
+ _restore_regional_store(_launch_templates, data.get("launch_templates", {}))
+ _restore_regional_store(_fleets, data.get("fleets", {}))
+ _restore_regional_store(
+ _iam_instance_profile_associations,
+ data.get("iam_instance_profile_associations", {})
+ )
+ if "default_initialized_scopes" not in data:
+ _infer_default_initialized_scopes_from_restored_stores()
+
+
+def _restore_regional_store(store, restored):
+ """Map legacy EC2 state to the boot region without mining embedded ARNs."""
+ if isinstance(restored, AccountRegionScopedDict):
+ store.update(restored)
+ return
+ region = get_region()
+ if isinstance(restored, AccountScopedDict):
+ for (account_id, key), value in restored._data.items():
+ store.set_scoped(account_id, region, key, value)
+ return
+ for key, value in restored.items():
+ store.set_scoped(get_account_id(), region, key, value)
+
+
try:
_restored = load_state("ec2")
if _restored:
@@ -206,6 +340,7 @@ _KNOWN_MALFORMED_SECURITY_GROUP_IDS = {
def _init_defaults():
+ _default_initialized_scopes.add((get_account_id(), get_region()))
if _DEFAULT_VPC_ID not in _vpcs:
_vpcs[_DEFAULT_VPC_ID] = {
"VpcId": _DEFAULT_VPC_ID,
@@ -284,8 +419,12 @@ def _init_defaults():
],
}
+def _ensure_defaults_initialized():
+ if (get_account_id(), get_region()) not in _default_initialized_scopes:
+ _init_defaults()
+
-_init_defaults()
+_ensure_defaults_initialized()
# ---------------------------------------------------------------------------
@@ -293,6 +432,7 @@ _init_defaults()
# ---------------------------------------------------------------------------
async def handle_request(method, path, headers, body, query_params):
+ _ensure_defaults_initialized()
params = dict(query_params)
if method in ("POST", "PUT") and body:
raw = body if isinstance(body, str) else body.decode("utf-8", errors="replace")
@@ -2706,7 +2846,8 @@ def _describe_snapshots(p):
def _copy_snapshot(p):
source_snap_id = _p(p, "SourceSnapshotId")
description = _p(p, "Description") or ""
- source = _snapshots.get(source_snap_id)
+ source_region = _p(p, "SourceRegion") or get_region()
+ source = _snapshots.get_scoped(get_account_id(), source_region, source_snap_id)
if not source:
return _error("InvalidSnapshot.NotFound", f"The snapshot '{source_snap_id}' does not exist.", 400)
new_snap_id = _new_snapshot_id()
@@ -3690,6 +3831,15 @@ def _delete_flow_logs(params):
# VPC Peering Connections
# ---------------------------------------------------------------------------
+def _set_vpc_peering_status(record, code, message):
+ status = {"Code": code, "Message": message}
+ pcx_id = record["VpcPeeringConnectionId"]
+ for account_id, region in _vpc_peering_scopes(record):
+ scoped_record = _vpc_peering.get_scoped(account_id, region, pcx_id)
+ if scoped_record is not None:
+ scoped_record["Status"] = status
+
+
def _create_vpc_peering_connection(params):
vpc_id = _p(params, "VpcId")
peer_vpc_id = _p(params, "PeerVpcId")
@@ -3706,7 +3856,7 @@ def _create_vpc_peering_connection(params):
"ExpirationTime": _now_ts(),
"Tags": [],
}
- _vpc_peering[pcx_id] = record
+ _put_vpc_peering_record(record)
# TagSpecifications support for aws_vpc_peering_connection.tags on create.
_parse_tag_specs(params, "vpc-peering-connection", pcx_id)
inner = f"""<vpcPeeringConnection>
@@ -3724,8 +3874,8 @@ def _accept_vpc_peering_connection(params):
if pcx_id not in _vpc_peering:
return _error("InvalidVpcPeeringConnectionID.NotFound",
f"The VPC peering connection '{pcx_id}' does not exist", 400)
- _vpc_peering[pcx_id]["Status"] = {"Code": "active", "Message": "Active"}
pcx = _vpc_peering[pcx_id]
+ _set_vpc_peering_status(pcx, "active", "Active")
inner = f"""<vpcPeeringConnection>
<vpcPeeringConnectionId>{pcx_id}</vpcPeeringConnectionId>
<requesterVpcInfo><vpcId>{pcx['RequesterVpcInfo']['VpcId']}</vpcId><ownerId>{pcx['RequesterVpcInfo']['OwnerId']}</ownerId><region>{pcx['RequesterVpcInfo']['Region']}</region></requesterVpcInfo>
@@ -3763,7 +3913,7 @@ def _delete_vpc_peering_connection(params):
if pcx_id not in _vpc_peering:
return _error("InvalidVpcPeeringConnectionID.NotFound",
f"The VPC peering connection '{pcx_id}' does not exist", 400)
- _vpc_peering[pcx_id]["Status"] = {"Code": "deleted", "Message": "Deleted"}
+ _set_vpc_peering_status(_vpc_peering[pcx_id], "deleted", "Deleted")
return _xml(200, "DeleteVpcPeeringConnectionResponse", "<return>true</return>")
@@ -4535,33 +4685,7 @@ def _delete_vpn_connection_route(p):
# ---------------------------------------------------------------------------
def reset():
- _instances.clear()
- _security_groups.clear()
- _key_pairs.clear()
- _placement_groups.clear()
- _vpcs.clear()
- _subnets.clear()
- _internet_gateways.clear()
- _addresses.clear()
- _tags.clear()
- _route_tables.clear()
- _network_interfaces.clear()
- _vpc_endpoints.clear()
- _volumes.clear()
- _snapshots.clear()
- _nat_gateways.clear()
- _network_acls.clear()
- _flow_logs.clear()
- _vpc_peering.clear()
- _dhcp_options.clear()
- _egress_igws.clear()
- _prefix_lists.clear()
- _vpn_gateways.clear()
- _customer_gateways.clear()
- _vpn_connections.clear()
- _launch_templates.clear()
- _fleets.clear()
- _iam_instance_profile_associations.clear()
+ _clear_state()
_init_defaults()
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 85fcc848..7a113fbb 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -2063,6 +2063,135 @@ def test_cfn_ec2_vpc_endpoint_uses_ec2_state(cfn, ec2):
)["VpcEndpoints"] == []
+def test_cfn_ec2_resources_use_caller_region_context():
+ """EC2 CFN provisioners must write through the caller's region context."""
+ import boto3
+ from botocore.config import Config
+
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+
+ def _client(svc, region):
+ return boto3.client(
+ svc,
+ endpoint_url=endpoint,
+ region_name=region,
+ aws_access_key_id="test",
+ aws_secret_access_key="test",
+ config=Config(region_name=region, retries={"mode": "standard"}),
+ )
+
+ cfn_west = _client("cloudformation", "us-west-2")
+ cfn_east = _client("cloudformation", "us-east-1")
+ ec2_west = _client("ec2", "us-west-2")
+ ec2_east = _client("ec2", "us-east-1")
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-ec2-region-{suffix}"
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Vpc": {
+ "Type": "AWS::EC2::VPC",
+ "Properties": {"CidrBlock": "10.41.0.0/16"},
+ },
+ "Subnet": {
+ "Type": "AWS::EC2::Subnet",
+ "Properties": {
+ "VpcId": {"Ref": "Vpc"},
+ "CidrBlock": "10.41.1.0/24",
+ "AvailabilityZone": "us-west-2a",
+ },
+ },
+ "SecurityGroup": {
+ "Type": "AWS::EC2::SecurityGroup",
+ "Properties": {
+ "GroupDescription": "regional cfn default-vpc fallback proof",
+ },
+ },
+ "Endpoint": {
+ "Type": "AWS::EC2::VPCEndpoint",
+ "Properties": {
+ "VpcEndpointType": "Gateway",
+ "ServiceName": "com.amazonaws.us-west-2.s3",
+ },
+ },
+ "RouteTable": {
+ "Type": "AWS::EC2::RouteTable",
+ "Properties": {},
+ },
+ },
+ "Outputs": {
+ "VpcId": {"Value": {"Ref": "Vpc"}},
+ "SubnetId": {"Value": {"Ref": "Subnet"}},
+ "SecurityGroupId": {"Value": {"Ref": "SecurityGroup"}},
+ "EndpointId": {"Value": {"Ref": "Endpoint"}},
+ "RouteTableId": {"Value": {"Ref": "RouteTable"}},
+ },
+ }
+ outputs = {}
+
+ try:
+ cfn_west.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn_west, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ outputs = {item["OutputKey"]: item["OutputValue"] for item in stack["Outputs"]}
+
+ assert ec2_west.describe_vpcs(VpcIds=[outputs["VpcId"]])["Vpcs"][0]["CidrBlock"] == "10.41.0.0/16"
+ assert ec2_west.describe_subnets(SubnetIds=[outputs["SubnetId"]])["Subnets"][0]["VpcId"] == outputs["VpcId"]
+ assert ec2_west.describe_security_groups(
+ GroupIds=[outputs["SecurityGroupId"]]
+ )["SecurityGroups"][0]["VpcId"] == "vpc-00000001"
+ assert ec2_west.describe_vpc_endpoints(
+ VpcEndpointIds=[outputs["EndpointId"]]
+ )["VpcEndpoints"][0]["VpcId"] == "vpc-00000001"
+ assert ec2_west.describe_route_tables(
+ RouteTableIds=[outputs["RouteTableId"]]
+ )["RouteTables"][0]["VpcId"] == "vpc-00000001"
+
+ with pytest.raises(ClientError):
+ ec2_east.describe_vpcs(VpcIds=[outputs["VpcId"]])
+ with pytest.raises(ClientError):
+ ec2_east.describe_subnets(SubnetIds=[outputs["SubnetId"]])
+ with pytest.raises(ClientError):
+ ec2_east.describe_security_groups(GroupIds=[outputs["SecurityGroupId"]])
+ assert ec2_east.describe_vpc_endpoints(VpcEndpointIds=[outputs["EndpointId"]])["VpcEndpoints"] == []
+
+ updated_template = json.loads(json.dumps(template))
+ updated_template["Resources"]["Endpoint2"] = {
+ "Type": "AWS::EC2::VPCEndpoint",
+ "Properties": {
+ "VpcEndpointType": "Gateway",
+ "ServiceName": "com.amazonaws.us-west-2.dynamodb",
+ },
+ }
+ updated_template["Outputs"]["Endpoint2Id"] = {"Value": {"Ref": "Endpoint2"}}
+
+ cfn_east.update_stack(StackName=stack_name, TemplateBody=json.dumps(updated_template))
+ stack = _wait_stack(cfn_east, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ outputs = {item["OutputKey"]: item["OutputValue"] for item in stack["Outputs"]}
+ assert ec2_west.describe_vpc_endpoints(
+ VpcEndpointIds=[outputs["Endpoint2Id"]]
+ )["VpcEndpoints"][0]["VpcId"] == "vpc-00000001"
+ assert ec2_east.describe_vpc_endpoints(
+ VpcEndpointIds=[outputs["Endpoint2Id"]]
+ )["VpcEndpoints"] == []
+
+ cfn_east.delete_stack(StackName=stack_name)
+ _wait_stack(cfn_east, stack_name)
+ assert ec2_west.describe_vpc_endpoints(
+ VpcEndpointIds=[outputs["EndpointId"], outputs["Endpoint2Id"]]
+ )["VpcEndpoints"] == []
+ finally:
+ try:
+ cfn_west.delete_stack(StackName=stack_name)
+ _wait_stack(cfn_west, stack_name)
+ except ClientError:
+ pass
+
+ if outputs:
+ assert ec2_west.describe_vpc_endpoints(VpcEndpointIds=[outputs["EndpointId"]])["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]
@@ -6392,6 +6521,7 @@ def test_cfn_cdk_opensearch_access_policy_custom_resource(cfn, opensearch):
stack_name = f"cfn-os-access-{suffix}"
domain_name = f"access-{suffix}"
function_name = f"cfn-os-provider-{suffix}"
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
access_policy = json.dumps({
"Version": "2012-10-17",
"Statement": [{
@@ -6483,11 +6613,11 @@ exports.handler = async (event) => {
"Role": "arn:aws:iam::000000000000:role/custom-resource",
"Timeout": 10,
"Code": {"ZipFile": provider_code},
- # CDK local tooling sets this exact hostname. The SDK shim
- # must not turn it into the S3-shaped
- # ``opensearch.localhost`` virtual host.
+ # CDK local tooling sets a root MiniStack gateway endpoint.
+ # The SDK shim must not turn it into the S3-shaped
+ # ``opensearch.<gateway>`` virtual host.
"Environment": {
- "Variables": {"AWS_ENDPOINT_URL": "http://localhost:4566"},
+ "Variables": {"AWS_ENDPOINT_URL": endpoint},
},
},
},
@@ -6629,7 +6759,7 @@ def test_cfn_s3tables_table_schema_from_iceberg_metadata(cfn, s3tables):
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
- resp = _cfn_iceberg_json(f"/iceberg/v1/namespaces/myns/tables/mytable")
+ resp = _cfn_iceberg_json("/iceberg/v1/namespaces/myns/tables/mytable")
fields = resp.get("metadata", {}).get("schemas", [{}])[0].get("fields", [])
field_names = {f["name"] for f in fields}
assert field_names == {"id", "value"}, f"expected columns id/value, got {field_names}"
diff --git a/tests/test_ec2.py b/tests/test_ec2.py
index 4300c629..eacbd072 100644
--- a/tests/test_ec2.py
+++ b/tests/test_ec2.py
@@ -2,13 +2,30 @@ import io
import json
import os
import time
+import urllib.error
+import urllib.request
import uuid as _uuid_mod
import zipfile
-from urllib.parse import urlparse
+from urllib.parse import urlencode, urlparse
+import boto3
import pytest
+from botocore.config import Config
from botocore.exceptions import ClientError
+ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+
+
+def _ec2_client(region, account_id="test"):
+ return boto3.client(
+ "ec2",
+ endpoint_url=ENDPOINT,
+ region_name=region,
+ aws_access_key_id=account_id,
+ aws_secret_access_key="test",
+ config=Config(region_name=region),
+ )
+
def _create_ec2_iam_instance_profile(iam, suffix):
assume = json.dumps(
@@ -93,6 +110,122 @@ def test_ec2_describe_regions_all_regions_includes_opt_in(ec2):
assert base >= 30
+def test_ec2_default_network_resources_are_region_scoped():
+ east = _ec2_client("us-east-1")
+ west = _ec2_client("us-west-2")
+
+ east_vpcs = east.describe_vpcs(
+ Filters=[{"Name": "is-default", "Values": ["true"]}]
+ )["Vpcs"]
+ west_vpcs = west.describe_vpcs(
+ Filters=[{"Name": "is-default", "Values": ["true"]}]
+ )["Vpcs"]
+
+ assert len(east_vpcs) == 1
+ assert len(west_vpcs) == 1
+
+ east_subnets = east.describe_subnets(
+ Filters=[{"Name": "vpc-id", "Values": [east_vpcs[0]["VpcId"]]}]
+ )["Subnets"]
+ west_subnets = west.describe_subnets(
+ Filters=[{"Name": "vpc-id", "Values": [west_vpcs[0]["VpcId"]]}]
+ )["Subnets"]
+ west_default_sgs = west.describe_security_groups(
+ Filters=[
+ {"Name": "vpc-id", "Values": [west_vpcs[0]["VpcId"]]},
+ {"Name": "group-name", "Values": ["default"]},
+ ]
+ )["SecurityGroups"]
+
+ assert {s["AvailabilityZone"] for s in east_subnets} == {
+ "us-east-1a",
+ "us-east-1b",
+ "us-east-1c",
+ }
+ assert {s["AvailabilityZone"] for s in west_subnets} == {
+ "us-west-2a",
+ "us-west-2b",
+ "us-west-2c",
+ }
+ assert len(west_default_sgs) == 1
+ assert west_default_sgs[0]["VpcId"] == west_vpcs[0]["VpcId"]
+
+
+def test_ec2_named_resources_and_tags_are_region_scoped():
+ east = _ec2_client("us-east-1")
+ west = _ec2_client("us-west-2")
+ suffix = _uuid_mod.uuid4().hex[:8]
+ key_name = f"qa-ec2-key-region-{suffix}"
+ pg_name = f"qa-ec2-pg-region-{suffix}"
+ sg_name = f"qa-ec2-sg-region-{suffix}"
+
+ east.create_key_pair(KeyName=key_name)
+ west.create_key_pair(KeyName=key_name)
+ east.create_placement_group(GroupName=pg_name, Strategy="cluster")
+ west.create_placement_group(GroupName=pg_name, Strategy="cluster")
+ east_sg = east.create_security_group(GroupName=sg_name, Description="east")
+ west_sg = west.create_security_group(GroupName=sg_name, Description="west")
+ east.create_tags(Resources=[east_sg["GroupId"]], Tags=[{"Key": "Region", "Value": "east"}])
+ west.create_tags(Resources=[west_sg["GroupId"]], Tags=[{"Key": "Region", "Value": "west"}])
+ east_instance = east.run_instances(
+ ImageId="ami-00000000",
+ MinCount=1,
+ MaxCount=1,
+ InstanceType="t2.micro",
+ )["Instances"][0]
+
+ try:
+ east_key = east.describe_key_pairs(KeyNames=[key_name])["KeyPairs"][0]
+ west_key = west.describe_key_pairs(KeyNames=[key_name])["KeyPairs"][0]
+ east_pg = east.describe_placement_groups(GroupNames=[pg_name])["PlacementGroups"][0]
+ west_pg = west.describe_placement_groups(GroupNames=[pg_name])["PlacementGroups"][0]
+ east_group = east.describe_security_groups(GroupIds=[east_sg["GroupId"]])[
+ "SecurityGroups"
+ ][0]
+ west_group = west.describe_security_groups(GroupIds=[west_sg["GroupId"]])[
+ "SecurityGroups"
+ ][0]
+ east_instances = east.describe_instances(InstanceIds=[east_instance["InstanceId"]])[
+ "Reservations"
+ ][0]["Instances"]
+
+ assert east_key["KeyPairId"] != west_key["KeyPairId"]
+ assert ":us-east-1:" in east_pg["GroupArn"]
+ assert ":us-west-2:" in west_pg["GroupArn"]
+ assert east_group["Description"] == "east"
+ assert west_group["Description"] == "west"
+ assert east_instances[0]["InstanceId"] == east_instance["InstanceId"]
+ assert east.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [east_sg["GroupId"]]}]
+ )["Tags"][0]["Value"] == "east"
+ assert west.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [west_sg["GroupId"]]}]
+ )["Tags"][0]["Value"] == "west"
+ with pytest.raises(ClientError):
+ east.describe_security_groups(GroupIds=[west_sg["GroupId"]])
+ with pytest.raises(ClientError):
+ west.describe_instances(InstanceIds=[east_instance["InstanceId"]])
+ finally:
+ try:
+ east.terminate_instances(InstanceIds=[east_instance["InstanceId"]])
+ except ClientError:
+ pass
+ for client, sg_id in ((east, east_sg["GroupId"]), (west, west_sg["GroupId"])):
+ try:
+ client.delete_security_group(GroupId=sg_id)
+ except ClientError:
+ pass
+ for client in (east, west):
+ try:
+ client.delete_key_pair(KeyName=key_name)
+ except ClientError:
+ pass
+ try:
+ client.delete_placement_group(GroupName=pg_name)
+ except ClientError:
+ pass
+
+
def test_ec2_run_describe_terminate_instances(ec2):
resp = ec2.run_instances(ImageId="ami-00000000", MinCount=1, MaxCount=1, InstanceType="t2.micro")
assert len(resp["Instances"]) == 1
@@ -637,7 +770,7 @@ def test_ec2_placement_group_crud(ec2):
assert created["Strategy"] == "cluster"
assert created["GroupId"].startswith("pg-")
assert created["GroupArn"] == (
- f"arn:aws:ec2:us-east-1:000000000000:placement-group/qa-ec2-pg"
+ "arn:aws:ec2:us-east-1:000000000000:placement-group/qa-ec2-pg"
)
desc = ec2.describe_placement_groups(GroupNames=["qa-ec2-pg"])
@@ -1245,6 +1378,152 @@ def test_ec2_vpc_peering_crud(ec2):
desc2 = ec2.describe_vpc_peering_connections(VpcPeeringConnectionIds=[pcx_id])
assert desc2["VpcPeeringConnections"][0]["Status"]["Code"] == "deleted"
+
+def test_ec2_vpc_peering_accepts_from_peer_region():
+ east = _ec2_client("us-east-1")
+ west = _ec2_client("us-west-2")
+ east_vpc_id = east.create_vpc(CidrBlock="10.107.0.0/16")["Vpc"]["VpcId"]
+ west_vpc_id = west.create_vpc(CidrBlock="10.108.0.0/16")["Vpc"]["VpcId"]
+
+ resp = east.create_vpc_peering_connection(
+ VpcId=east_vpc_id,
+ PeerVpcId=west_vpc_id,
+ PeerRegion="us-west-2",
+ TagSpecifications=[
+ {
+ "ResourceType": "vpc-peering-connection",
+ "Tags": [{"Key": "Scope", "Value": "inter-region"}],
+ }
+ ],
+ )
+ pcx_id = resp["VpcPeeringConnection"]["VpcPeeringConnectionId"]
+
+ assert west.describe_vpc_peering_connections(
+ VpcPeeringConnectionIds=[pcx_id]
+ )["VpcPeeringConnections"][0]["Status"]["Code"] == "pending-acceptance"
+
+ accepted = west.accept_vpc_peering_connection(VpcPeeringConnectionId=pcx_id)
+ assert accepted["VpcPeeringConnection"]["Status"]["Code"] == "active"
+ assert east.describe_vpc_peering_connections(
+ VpcPeeringConnectionIds=[pcx_id]
+ )["VpcPeeringConnections"][0]["Status"]["Code"] == "active"
+ assert east.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [pcx_id]}]
+ )["Tags"][0]["Value"] == "inter-region"
+ assert west.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [pcx_id]}]
+ )["Tags"] == []
+
+ west.delete_vpc_peering_connection(VpcPeeringConnectionId=pcx_id)
+ assert east.describe_vpc_peering_connections(
+ VpcPeeringConnectionIds=[pcx_id]
+ )["VpcPeeringConnections"][0]["Status"]["Code"] == "deleted"
+
+
+def test_ec2_vpc_peering_tags_are_region_local():
+ east = _ec2_client("us-east-1")
+ west = _ec2_client("us-west-2")
+ east_vpc_id = east.create_vpc(CidrBlock="10.109.0.0/16")["Vpc"]["VpcId"]
+ west_vpc_id = west.create_vpc(CidrBlock="10.110.0.0/16")["Vpc"]["VpcId"]
+
+ resp = east.create_vpc_peering_connection(
+ VpcId=east_vpc_id,
+ PeerVpcId=west_vpc_id,
+ PeerRegion="us-west-2",
+ TagSpecifications=[
+ {
+ "ResourceType": "vpc-peering-connection",
+ "Tags": [{"Key": "Scope", "Value": "initial"}],
+ }
+ ],
+ )
+ pcx_id = resp["VpcPeeringConnection"]["VpcPeeringConnectionId"]
+
+ assert east.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [pcx_id]}]
+ )["Tags"][0]["Value"] == "initial"
+ assert west.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [pcx_id]}]
+ )["Tags"] == []
+ assert len(east.describe_vpc_peering_connections(
+ Filters=[{"Name": "tag:Scope", "Values": ["initial"]}]
+ )["VpcPeeringConnections"]) == 1
+ assert west.describe_vpc_peering_connections(
+ Filters=[{"Name": "tag:Scope", "Values": ["initial"]}]
+ )["VpcPeeringConnections"] == []
+
+ west.create_tags(Resources=[pcx_id], Tags=[{"Key": "Scope", "Value": "peer"}])
+ assert east.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [pcx_id]}]
+ )["Tags"][0]["Value"] == "initial"
+ assert west.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [pcx_id]}]
+ )["Tags"][0]["Value"] == "peer"
+ assert east.describe_vpc_peering_connections(
+ Filters=[{"Name": "tag:Scope", "Values": ["peer"]}]
+ )["VpcPeeringConnections"] == []
+ assert len(west.describe_vpc_peering_connections(
+ Filters=[{"Name": "tag:Scope", "Values": ["peer"]}]
+ )["VpcPeeringConnections"]) == 1
+
+ east.delete_tags(Resources=[pcx_id], Tags=[{"Key": "Scope"}])
+ assert east.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [pcx_id]}]
+ )["Tags"] == []
+ assert west.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [pcx_id]}]
+ )["Tags"][0]["Value"] == "peer"
+
+
+def test_ec2_vpc_peering_cross_account_tags_are_account_isolated():
+ requester_account = "111111111111"
+ accepter_account = "222222222222"
+ east = _ec2_client("us-east-1", requester_account)
+ west = _ec2_client("us-west-2", accepter_account)
+ east_vpc_id = east.create_vpc(CidrBlock="10.111.0.0/16")["Vpc"]["VpcId"]
+ west_vpc_id = west.create_vpc(CidrBlock="10.112.0.0/16")["Vpc"]["VpcId"]
+
+ resp = east.create_vpc_peering_connection(
+ VpcId=east_vpc_id,
+ PeerVpcId=west_vpc_id,
+ PeerOwnerId=accepter_account,
+ PeerRegion="us-west-2",
+ TagSpecifications=[
+ {
+ "ResourceType": "vpc-peering-connection",
+ "Tags": [{"Key": "Side", "Value": "requester"}],
+ }
+ ],
+ )
+ pcx_id = resp["VpcPeeringConnection"]["VpcPeeringConnectionId"]
+
+ assert east.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [pcx_id]}]
+ )["Tags"][0]["Value"] == "requester"
+ assert west.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [pcx_id]}]
+ )["Tags"] == []
+
+ west.create_tags(Resources=[pcx_id], Tags=[{"Key": "Side", "Value": "accepter"}])
+ assert west.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [pcx_id]}]
+ )["Tags"][0]["Value"] == "accepter"
+ assert east.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [pcx_id]}]
+ )["Tags"][0]["Value"] == "requester"
+
+ east.create_tags(
+ Resources=[pcx_id],
+ Tags=[{"Key": "Side", "Value": "requester-updated"}],
+ )
+ assert east.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [pcx_id]}]
+ )["Tags"][0]["Value"] == "requester-updated"
+ assert west.describe_tags(
+ Filters=[{"Name": "resource-id", "Values": [pcx_id]}]
+ )["Tags"][0]["Value"] == "accepter"
+
+
def test_ec2_vpc_peering_not_found(ec2):
from botocore.exceptions import ClientError
@@ -2425,6 +2704,52 @@ def test_ebs_copy_snapshot(ec2):
assert new_snap_id != snap_id
assert new_snap_id.startswith("snap-")
+
+def test_ebs_copy_snapshot_respects_source_region():
+ east = _ec2_client("us-east-1")
+ west = _ec2_client("us-west-2")
+
+ vol = east.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")
+ snap = east.create_snapshot(VolumeId=vol["VolumeId"], Description="east source")
+ snap_id = snap["SnapshotId"]
+
+ req = urllib.request.Request(
+ f"{ENDPOINT}/",
+ data=urlencode({
+ "Action": "CopySnapshot",
+ "Version": "2016-11-15",
+ "SourceSnapshotId": snap_id,
+ "Description": "missing source region",
+ }).encode("utf-8"),
+ headers={
+ "Content-Type": "application/x-www-form-urlencoded",
+ "Authorization": (
+ "AWS4-HMAC-SHA256 "
+ "Credential=test/20260729/us-west-2/ec2/aws4_request, "
+ "SignedHeaders=host, Signature=test"
+ ),
+ },
+ method="POST",
+ )
+ with pytest.raises(urllib.error.HTTPError) as exc:
+ urllib.request.urlopen(req, timeout=5)
+ assert exc.value.code == 400
+ assert b"InvalidSnapshot.NotFound" in exc.value.read()
+
+ copied = west.copy_snapshot(
+ SourceRegion="us-east-1",
+ SourceSnapshotId=snap_id,
+ Description="west copy",
+ )
+ copied_id = copied["SnapshotId"]
+
+ assert copied_id != snap_id
+ assert east.describe_snapshots(SnapshotIds=[snap_id])["Snapshots"][0]["SnapshotId"] == snap_id
+ assert west.describe_snapshots(SnapshotIds=[copied_id])["Snapshots"][0]["Description"] == "west copy"
+ with pytest.raises(ClientError):
+ west.describe_snapshots(SnapshotIds=[snap_id])
+
+
def test_ebs_snapshot_attribute(ec2):
vol = ec2.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")
snap = ec2.create_snapshot(VolumeId=vol["VolumeId"], Description="attr test")
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
index 58902f4a..e3bbf5bf 100644
--- a/tests/test_persistence.py
+++ b/tests/test_persistence.py
@@ -3414,6 +3414,323 @@ def test_s3files_region_scoped_state_is_rejected_by_v2_reader(
assert persistence.load_state("s3files") is None
+def test_ec2_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmp_path):
+ """A rollback binary must reject EC2 regional state instead of accepting
+ account-only stores that would collapse same-name resources across regions."""
+ import json as _json
+
+ from ministack.core.responses import AccountRegionScopedDict
+
+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)
+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))
+
+ key_pairs = AccountRegionScopedDict()
+ key_pairs.set_scoped(
+ "000000000000",
+ "us-west-2",
+ "same-key",
+ {"KeyName": "same-key", "KeyPairId": "key-west"},
+ )
+ persistence.save_state("ec2", {"key_pairs": key_pairs})
+
+ raw = _json.loads((tmp_path / "ec2.json").read_text())
+ assert raw["__ministack_format__"] == 3
+ loaded_key_pairs = persistence.load_state("ec2")["key_pairs"]
+ assert loaded_key_pairs.get_scoped(
+ "000000000000", "us-west-2", "same-key"
+ )["KeyPairId"] == "key-west"
+
+ monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})
+ assert persistence.load_state("ec2") is None
+
+
+def test_ec2_legacy_state_restores_to_boot_region_without_arn_mining():
+ """Legacy EC2 state is one coherent graph even when records embed foreign ARNs."""
+ from ministack.core.responses import (
+ AccountScopedDict,
+ get_account_id,
+ get_region,
+ set_request_account_id,
+ set_request_region,
+ )
+ from ministack.services import ec2
+
+ original_account = get_account_id()
+ original_region = get_region()
+ account_id = "123456789012"
+ boot_region = "us-east-1"
+ foreign_region = "us-west-2"
+
+ vpcs = AccountScopedDict()
+ flow_logs = AccountScopedDict()
+
+ try:
+ set_request_account_id(account_id)
+ set_request_region(boot_region)
+ ec2.reset()
+
+ vpcs["vpc-legacy"] = {
+ "VpcId": "vpc-legacy",
+ "CidrBlock": "10.70.0.0/16",
+ "OwnerId": account_id,
+ }
+ flow_logs["fl-legacy"] = {
+ "FlowLogId": "fl-legacy",
+ "ResourceId": "vpc-legacy",
+ "DeliverLogsPermissionArn": (
+ f"arn:aws:logs:{foreign_region}:{account_id}:log-group:foreign"
+ ),
+ "LogDestination": f"arn:aws:logs:{foreign_region}:{account_id}:log-group:foreign",
+ }
+
+ ec2.restore_state({"vpcs": vpcs, "flow_logs": flow_logs})
+
+ assert ec2._vpcs.get_scoped(account_id, boot_region, "vpc-legacy")["VpcId"] == "vpc-legacy"
+ assert ec2._flow_logs.get_scoped(account_id, boot_region, "fl-legacy")["ResourceId"] == "vpc-legacy"
+ assert ec2._flow_logs.get_scoped(account_id, foreign_region, "fl-legacy") is None
+ finally:
+ ec2.reset()
+ set_request_account_id(original_account)
+ set_request_region(original_region)
+
+
+def test_ec2_legacy_vpc_peering_restores_to_boot_region_graph():
+ from ministack.core.responses import (
+ AccountScopedDict,
+ get_account_id,
+ get_region,
+ set_request_account_id,
+ set_request_region,
+ )
+ from ministack.services import ec2
+
+ original_account = get_account_id()
+ original_region = get_region()
+ account_id = "123456789012"
+ boot_region = "us-east-1"
+ peer_region = "us-west-2"
+ pcx_id = "pcx-legacy000000001"
+
+ vpcs = AccountScopedDict()
+ peerings = AccountScopedDict()
+ tags = AccountScopedDict()
+
+ try:
+ set_request_account_id(account_id)
+ set_request_region(boot_region)
+ ec2.reset()
+
+ vpcs["vpc-east"] = {
+ "VpcId": "vpc-east",
+ "CidrBlock": "10.0.0.0/16",
+ "State": "available",
+ "IsDefault": False,
+ "OwnerId": account_id,
+ }
+ vpcs["vpc-west"] = {
+ "VpcId": "vpc-west",
+ "CidrBlock": "10.1.0.0/16",
+ "State": "available",
+ "IsDefault": False,
+ "OwnerId": account_id,
+ }
+ peerings[pcx_id] = {
+ "VpcPeeringConnectionId": pcx_id,
+ "RequesterVpcInfo": {
+ "VpcId": "vpc-east",
+ "OwnerId": account_id,
+ "Region": boot_region,
+ },
+ "AccepterVpcInfo": {
+ "VpcId": "vpc-west",
+ "OwnerId": account_id,
+ "Region": peer_region,
+ },
+ "Status": {
+ "Code": "pending-acceptance",
+ "Message": "Pending Acceptance",
+ },
+ }
+ tags[pcx_id] = [{"Key": "Scope", "Value": "legacy"}]
+
+ ec2.restore_state({"vpcs": vpcs, "vpc_peering": peerings, "tags": tags})
+
+ boot_record = ec2._vpc_peering.get_scoped(account_id, boot_region, pcx_id)
+ peer_record = ec2._vpc_peering.get_scoped(account_id, peer_region, pcx_id)
+ assert boot_record["VpcPeeringConnectionId"] == pcx_id
+ assert boot_record["RequesterVpcInfo"]["Region"] == boot_region
+ assert boot_record["AccepterVpcInfo"]["Region"] == boot_region
+ assert peer_record is None
+ assert ec2._vpcs.get_scoped(account_id, boot_region, "vpc-east") is not None
+ assert ec2._vpcs.get_scoped(account_id, boot_region, "vpc-west") is not None
+ assert ec2._vpcs.get_scoped(account_id, peer_region, "vpc-west") is None
+ assert ec2._tags.get_scoped(account_id, boot_region, pcx_id) == tags[pcx_id]
+ assert ec2._tags.get_scoped(account_id, peer_region, pcx_id) is None
+ assert (account_id, peer_region) not in ec2._default_initialized_scopes
+
+ set_request_region(peer_region)
+ ec2._ensure_defaults_initialized()
+ assert (
+ ec2._vpcs.get_scoped(account_id, peer_region, ec2._DEFAULT_VPC_ID)
+ is not None
+ )
+ ec2._set_vpc_peering_status(boot_record, "active", "Active")
+ assert (
+ ec2._vpc_peering.get_scoped(account_id, boot_region, pcx_id)["Status"]["Code"]
+ == "active"
+ )
+ assert ec2._vpc_peering.get_scoped(account_id, peer_region, pcx_id) is None
+ finally:
+ ec2.reset()
+ set_request_account_id(original_account)
+ set_request_region(original_region)
+
+
+def test_ec2_restore_preserves_deleted_default_resource_scope():
+ from ministack.core.responses import (
+ get_account_id,
+ get_region,
+ set_request_account_id,
+ set_request_region,
+ )
+ from ministack.services import ec2
+
+ original_account = get_account_id()
+ original_region = get_region()
+ account_id = "123456789012"
+ region = "us-west-2"
+
+ try:
+ set_request_account_id(account_id)
+ set_request_region(region)
+ ec2.reset()
+
+ for store in (
+ ec2._vpcs,
+ ec2._subnets,
+ ec2._security_groups,
+ ec2._network_acls,
+ ec2._internet_gateways,
+ ec2._route_tables,
+ ):
+ store.clear()
+
+ state = ec2.get_state()
+ assert {"AccountId": account_id, "Region": region} in state[
+ "default_initialized_scopes"
+ ]
+
+ ec2.restore_state(state)
+ ec2._ensure_defaults_initialized()
+
+ assert ec2._vpcs.get_scoped(account_id, region, ec2._DEFAULT_VPC_ID) is None
+ assert (
+ ec2._subnets.get_scoped(account_id, region, ec2._DEFAULT_SUBNET_ID)
+ is None
+ )
+ assert (
+ ec2._security_groups.get_scoped(account_id, region, ec2._DEFAULT_SG_ID)
+ is None
+ )
+ finally:
+ set_request_account_id(original_account)
+ set_request_region(original_region)
+ ec2.reset()
+
+
+def test_ec2_legacy_generated_default_vpc_marks_scope_initialized():
+ from ministack.core.responses import (
+ AccountScopedDict,
+ get_account_id,
+ get_region,
+ set_request_account_id,
+ set_request_region,
+ )
+ from ministack.services import ec2
+
+ original_account = get_account_id()
+ original_region = get_region()
+ account_id = "123456789012"
+ region = "us-west-2"
+ generated_default_vpc_id = "vpc-0abc1234def567890"
+
+ vpcs = AccountScopedDict()
+
+ try:
+ set_request_account_id(account_id)
+ set_request_region(region)
+ ec2.reset()
+
+ vpcs[generated_default_vpc_id] = {
+ "VpcId": generated_default_vpc_id,
+ "CidrBlock": "172.31.0.0/16",
+ "State": "available",
+ "IsDefault": True,
+ "DhcpOptionsId": "dopt-00000001",
+ "InstanceTenancy": "default",
+ "OwnerId": account_id,
+ "DefaultNetworkAclId": "acl-0abc1234def567890",
+ "DefaultSecurityGroupId": "sg-0abc1234def567890",
+ "MainRouteTableId": "rtb-0abc1234def567890",
+ }
+
+ ec2.restore_state({"vpcs": vpcs})
+ ec2._ensure_defaults_initialized()
+
+ assert (
+ ec2._vpcs.get_scoped(account_id, region, generated_default_vpc_id)
+ is not None
+ )
+ assert ec2._vpcs.get_scoped(account_id, region, ec2._DEFAULT_VPC_ID) is None
+ finally:
+ set_request_account_id(original_account)
+ set_request_region(original_region)
+ ec2.reset()
+
+
+def test_ec2_region_scoped_v3_state_is_idempotent(monkeypatch, tmp_path):
+ import json as _json
+
+ from ministack.core.responses import AccountRegionScopedDict
+
+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)
+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))
+
+ account_id = "123456789012"
+ region = "us-west-2"
+
+ key_pairs = AccountRegionScopedDict()
+ key_pairs.set_scoped(
+ account_id,
+ region,
+ "regional-key",
+ {"KeyName": "regional-key", "KeyPairId": "key-west"},
+ )
+ flow_logs = AccountRegionScopedDict()
+ flow_logs.set_scoped(
+ account_id,
+ region,
+ "fl-regional",
+ {
+ "FlowLogId": "fl-regional",
+ "ResourceId": "vpc-regional",
+ "LogDestination": f"arn:aws:logs:{region}:{account_id}:log-group:regional",
+ },
+ )
+
+ persistence.save_state("ec2", {"key_pairs": key_pairs, "flow_logs": flow_logs})
+ first_snapshot = _json.loads((tmp_path / "ec2.json").read_text())
+ assert first_snapshot["__ministack_format__"] == 3
+ assert f"{account_id}\x00{region}\x00'regional-key'" in first_snapshot["payload"]["key_pairs"]["data"]
+
+ loaded = persistence.load_state("ec2")
+ assert loaded["key_pairs"].get_scoped(account_id, region, "regional-key")["KeyPairId"] == "key-west"
+ persistence.save_state("ec2", loaded)
+ second_snapshot = _json.loads((tmp_path / "ec2.json").read_text())
+
+ assert second_snapshot == first_snapshot
+
+
def test_servicediscovery_region_scoped_state_is_rejected_by_v2_reader(
monkeypatch, tmp_path
):