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
Regionalize API Gateway v2 state (#1279)
Ian Oberst1e0c835a3786
diff --git a/ministack/app.py b/ministack/app.pyindex 03ab8f43..84da6b53 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -1264,7 +1264,7 @@ def _resolve_stage_and_path(api_id: str, tentative_stage: str, execute_path: strif apigw_v1.find_api_scope(api_id) is not None:stages_map = apigw_v1.stages_for_api(api_id)else:- stages_map = _get_module("apigateway")._stages.get(api_id, {})+ stages_map = _get_module("apigateway").stages_for_api(api_id)if tentative_stage in stages_map:return tentative_stage, execute_path@@ -1300,7 +1300,10 @@ async def _handle_execute_api_request(return await apigw_v1.handle_execute(api_id, stage, method, execute_path, headers, body, query_params)- return await _get_module("apigateway").handle_execute(+ apigw_v2 = _get_module("apigateway")+ if apigw_v2.find_api_scope(api_id) is None:+ return 404, {"Content-Type": "application/json"}, json.dumps({"message": "Not Found"}).encode()+ return await apigw_v2.handle_execute(api_id, stage, execute_path, method, headers, body, query_params)except Exception as e:diff --git a/ministack/core/persistence.py b/ministack/core/persistence.pyindex 28b341db..5b589805 100644--- a/ministack/core/persistence.py+++ b/ministack/core/persistence.py@@ -30,6 +30,7 @@ STATE_FORMAT_VERSION = 2# alongside the version machinery itself (98fdacc), so the v2 default already# covers it; stamping v3 would only add needless rollback refusal.SERVICE_STATE_FORMAT_VERSIONS = {+ "apigateway": 3,"apigateway_v1": 3,"appsync": 3,"appsync_events": 3,diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.pyindex 884e695d..b1e9add9 100644--- a/ministack/services/apigateway.py+++ b/ministack/services/apigateway.py@@ -52,7 +52,14 @@ import urllib.parseimport urllib.requestfrom ministack.core.arn import ArnParseError, parse_arn-from ministack.core.responses import AccountScopedDict, error_response_json, get_account_id, get_region, new_uuid+from ministack.core.responses import (+ AccountRegionScopedDict,+ AccountScopedDict,+ error_response_json,+ get_account_id,+ get_region,+ new_uuid,+)_HOST = os.environ.get("MINISTACK_HOST", "localhost")_PORT = os.environ.get("GATEWAY_PORT", "4566")@@ -85,21 +92,19 @@ async def _urlopen_async(request_or_url, timeout_seconds: float):return await asyncio.to_thread(_urlopen_sync, request_or_url, timeout_seconds)-REGION = os.environ.get("MINISTACK_REGION", "us-east-1")_PROXY_TIMEOUT_SECONDS = _timeout_from_env("MINISTACK_APIGW_PROXY_TIMEOUT_SECONDS", 30.0)_JWKS_TIMEOUT_SECONDS = _timeout_from_env("MINISTACK_APIGW_JWKS_TIMEOUT_SECONDS", 5.0)# ---- Module-level state -----_apis = AccountScopedDict() # api_id -> api object-_api_regions = AccountScopedDict() # api_id -> owning region-_routes = AccountScopedDict() # api_id -> {route_id -> route object}-_integrations = AccountScopedDict() # api_id -> {integration_id -> integration object}-_stages = AccountScopedDict() # api_id -> {stage_name -> stage object}-_deployments = AccountScopedDict() # api_id -> {deployment_id -> deployment object}-_authorizers = AccountScopedDict() # api_id -> {authorizer_id -> authorizer object}-_api_tags = AccountScopedDict() # resource_arn -> {key -> value}-_route_responses = AccountScopedDict() # api_id -> {route_id -> {rr_id -> route_response}}-_integration_responses = AccountScopedDict() # api_id -> {integration_id -> {ir_id -> int_response}}+_apis = AccountRegionScopedDict() # api_id -> api object+_routes = AccountRegionScopedDict() # api_id -> {route_id -> route object}+_integrations = AccountRegionScopedDict() # api_id -> {integration_id -> integration object}+_stages = AccountRegionScopedDict() # api_id -> {stage_name -> stage object}+_deployments = AccountRegionScopedDict() # api_id -> {deployment_id -> deployment object}+_authorizers = AccountRegionScopedDict() # api_id -> {authorizer_id -> authorizer object}+_api_tags = AccountRegionScopedDict() # resource_arn -> {key -> value}+_route_responses = AccountRegionScopedDict() # api_id -> {route_id -> {rr_id -> route_response}}+_integration_responses = AccountRegionScopedDict() # api_id -> {integration_id -> {ir_id -> int_response}}# JWKS cache is account-scoped because issuer URLs in MiniStack can resolve# to per-account local Cognito user pools — the same URL string may legitimately# serve different keys in different accounts.@@ -214,7 +219,6 @@ def get_state() -> dict:import copyreturn {"apis": copy.deepcopy(_apis),- "api_regions": copy.deepcopy(_api_regions),"routes": copy.deepcopy(_routes),"integrations": copy.deepcopy(_integrations),"stages": copy.deepcopy(_stages),@@ -226,18 +230,86 @@ def get_state() -> dict:}+def _legacy_account_items(restored):+ if isinstance(restored, AccountScopedDict):+ return restored._data.items()+ if isinstance(restored, dict):+ account_id = get_account_id()+ return [((account_id, key), value) for key, value in restored.items()]+ return ()+++def _legacy_region(region_store, account_id, key):+ if isinstance(region_store, AccountScopedDict):+ return region_store.get_scoped(account_id, None, key)+ if isinstance(region_store, dict):+ return region_store.get(key)+ return None+++def _restore_api_store(restored, region_store):+ if isinstance(restored, AccountRegionScopedDict):+ _apis.update(restored)+ return {+ (account_id, api_id): region+ for (account_id, region, api_id), _api in _apis.all_items()+ }++ regions = {}+ boot_region = get_region()+ for (account_id, api_id), api in _legacy_account_items(restored):+ region = _legacy_region(region_store, account_id, api_id) or boot_region+ _apis.set_scoped(account_id, region, api_id, api)+ regions[(account_id, api_id)] = region+ return regions+++def _restore_child_store(store, restored, api_regions):+ if isinstance(restored, AccountRegionScopedDict):+ store.update(restored)+ return++ boot_region = get_region()+ for (account_id, api_id), value in _legacy_account_items(restored):+ region = api_regions.get((account_id, api_id), boot_region)+ store.set_scoped(account_id, region, api_id, value)+++def _region_from_apigateway_arn(resource_arn: str) -> str | None:+ try:+ parsed = parse_arn(resource_arn)+ except (ArnParseError, TypeError):+ return None+ if parsed.service != "apigateway":+ return None+ return parsed.region or None+++def _restore_api_tags(restored):+ if isinstance(restored, AccountRegionScopedDict):+ _api_tags.update(restored)+ return++ boot_region = get_region()+ for (account_id, resource_arn), tags in _legacy_account_items(restored):+ region = _region_from_apigateway_arn(resource_arn) or boot_region+ _api_tags.set_scoped(account_id, region, resource_arn, tags)++def load_persisted_state(data: dict) -> None:"""Restore module state from a previously persisted snapshot."""- _apis.update(data.get("apis", {}))- _api_regions.update(data.get("api_regions", {}))- _routes.update(data.get("routes", {}))- _integrations.update(data.get("integrations", {}))- _stages.update(data.get("stages", {}))- _deployments.update(data.get("deployments", {}))- _authorizers.update(data.get("authorizers", {}))- _api_tags.update(data.get("api_tags", {}))- _route_responses.update(data.get("route_responses", {}))- _integration_responses.update(data.get("integration_responses", {}))+ if not data:+ return++ api_regions = _restore_api_store(data.get("apis", {}), data.get("api_regions", {}))+ _restore_child_store(_routes, data.get("routes", {}), api_regions)+ _restore_child_store(_integrations, data.get("integrations", {}), api_regions)+ _restore_child_store(_stages, data.get("stages", {}), api_regions)+ _restore_child_store(_deployments, data.get("deployments", {}), api_regions)+ _restore_child_store(_authorizers, data.get("authorizers", {}), api_regions)+ _restore_api_tags(data.get("api_tags", {}))+ _restore_child_store(_route_responses, data.get("route_responses", {}), api_regions)+ _restore_child_store(_integration_responses, data.get("integration_responses", {}), api_regions)# ---- Control plane router ----@@ -803,6 +875,29 @@ def _apply_request_parameter_mappings(async def handle_execute(api_id, stage, path, method, headers, body, query_params):"""Execute an API request through a deployed API (data plane)."""+ scope = find_api_scope(api_id)+ if scope is None:+ return 404, {"Content-Type": "application/json"}, json.dumps({"message": "Not Found"}).encode()+ owner_account_id, owner_region = scope++ from ministack.core.responses import _request_account_id, _request_region++ account_token = _request_account_id.set(owner_account_id)+ region_token = _request_region.set(owner_region)+ try:+ return await _handle_execute_in_scope(+ api_id, stage, path, method, headers, body, query_params,+ owner_account_id, owner_region,+ )+ finally:+ _request_account_id.reset(account_token)+ _request_region.reset(region_token)+++async def _handle_execute_in_scope(+ api_id, stage, path, method, headers, body, query_params,+ owner_account_id, owner_region,+):api = _apis.get(api_id)if not api:return 404, {"Content-Type": "application/json"}, json.dumps({"message": "Not Found"}).encode()@@ -881,8 +976,8 @@ async def handle_execute(api_id, stage, path, method, headers, body, query_param(path_params or None),authorizer_claims=authorizer_claims,authorizer_scopes=authorizer_scopes,- owner_account_id=get_account_id(),- owner_region=_api_regions.get(api_id, get_region()),+ owner_account_id=owner_account_id,+ owner_region=owner_region,)elif integration_type == "HTTP_PROXY":mapped_headers, mapped_query, mapped_path = _apply_request_parameter_mappings(@@ -1204,7 +1299,25 @@ async def _invoke_http_proxy(integration, path, method, headers, body, query_par# ---- Control plane: APIs -----def _resolve_custom_api_id(tags: dict, existing: "AccountScopedDict") -> str | None:+def find_api_scope(api_id):+ """Return (account_id, region) owning api_id within the ambient account."""+ account_id = get_account_id()+ for (stored_account, region, stored_api_id), _api in _apis.all_items():+ if stored_account == account_id and stored_api_id == api_id:+ return stored_account, region+ return None+++def stages_for_api(api_id):+ """Return stages for api_id after resolving the v2 data-plane owner scope."""+ scope = find_api_scope(api_id)+ if scope is None:+ return {}+ account_id, region = scope+ return _stages.get_scoped(account_id, region, api_id, {})+++def _resolve_custom_api_id(tags: dict, existing: "AccountRegionScopedDict") -> str | None:"""Return a caller-pinned API id from the ``ms-custom-id`` tag, or Noneif no tag is set (issue #400).@@ -1224,7 +1337,11 @@ def _resolve_custom_api_id(tags: dict, existing: "AccountScopedDict") -> str | Ncustom = tags.get("ms-custom-id")if not custom:return None- if custom in existing:+ if existing is _apis and find_api_scope(str(custom)) is not None:+ raise ValueError(+ f"API id '{custom}' (from ms-custom-id tag) is already in use"+ )+ if existing is not _apis and custom in existing:raise ValueError(f"API id '{custom}' (from ms-custom-id tag) is already in use")@@ -1260,7 +1377,6 @@ def _create_api(data):if data.get("corsConfiguration"):api["corsConfiguration"] = data["corsConfiguration"]_apis[api_id] = api- _api_regions[api_id] = get_region()_routes[api_id] = {}_integrations[api_id] = {}_stages[api_id] = {}@@ -1271,26 +1387,30 @@ def _create_api(data):def _get_api(api_id):api = _apis.get(api_id)- # APIs are region-specific; an API owned by another region must not be- # visible from this one (the execute path already enforces this — keep the- # control plane consistent).- if not api or _api_regions.get(api_id, get_region()) != get_region():+ if not api:return _apigw_error("NotFoundException", f"API {api_id} not found", 404)return _apigw_response(api)def _get_apis():- items = [- api for api_id, api in _apis.items()- if _api_regions.get(api_id, get_region()) == get_region()- ]- return _apigw_response({"items": items})+ return _apigw_response({"items": list(_apis.values())})+++def _api_not_found(api_id):+ return _apigw_error("NotFoundException", f"API {api_id} not found", 404)+++def _require_api(api_id):+ if api_id not in _apis:+ return _api_not_found(api_id)+ return Nonedef _delete_api(api_id):+ if api_id not in _apis:+ return _api_not_found(api_id)_delete_api_tag_resources(api_id)_apis.pop(api_id, None)- _api_regions.pop(api_id, None)_routes.pop(api_id, None)_integrations.pop(api_id, None)_stages.pop(api_id, None)@@ -1313,7 +1433,7 @@ def _update_api(api_id, data):def _create_route(api_id, data):if api_id not in _apis:- return _apigw_error("NotFoundException", f"API {api_id} not found", 404)+ return _api_not_found(api_id)route_id = new_uuid()[:8]route = {"routeId": route_id,@@ -1336,10 +1456,14 @@ def _create_route(api_id, data):def _get_routes(api_id):+ if err := _require_api(api_id):+ return errreturn _apigw_response({"items": list(_routes.get(api_id, {}).values())})def _get_route(api_id, route_id):+ if err := _require_api(api_id):+ return errroute = _routes.get(api_id, {}).get(route_id)if not route:return _apigw_error("NotFoundException", f"Route {route_id} not found", 404)@@ -1347,6 +1471,8 @@ def _get_route(api_id, route_id):def _update_route(api_id, route_id, data):+ if err := _require_api(api_id):+ return errroute = _routes.get(api_id, {}).get(route_id)if not route:return _apigw_error("NotFoundException", f"Route {route_id} not found", 404)@@ -1386,6 +1512,8 @@ def _update_route(api_id, route_id, data):def _delete_route(api_id, route_id):+ if err := _require_api(api_id):+ return err_routes.get(api_id, {}).pop(route_id, None)_api_tags.pop(_api_resource_arn(api_id, "routes", route_id), None)return 204, {}, b""@@ -1395,7 +1523,7 @@ def _delete_route(api_id, route_id):def _create_integration(api_id, data):if api_id not in _apis:- return _apigw_error("NotFoundException", f"API {api_id} not found", 404)+ return _api_not_found(api_id)int_id = new_uuid()[:8]integration = {"integrationId": int_id,@@ -1423,10 +1551,14 @@ def _create_integration(api_id, data):def _get_integrations(api_id):+ if err := _require_api(api_id):+ return errreturn _apigw_response({"items": list(_integrations.get(api_id, {}).values())})def _get_integration(api_id, int_id):+ if err := _require_api(api_id):+ return errintegration = _integrations.get(api_id, {}).get(int_id)if not integration:return _apigw_error("NotFoundException", f"Integration {int_id} not found", 404)@@ -1434,6 +1566,8 @@ def _get_integration(api_id, int_id):def _update_integration(api_id, int_id, data):+ if err := _require_api(api_id):+ return errintegration = _integrations.get(api_id, {}).get(int_id)if not integration:return _apigw_error("NotFoundException", f"Integration {int_id} not found", 404)@@ -1460,6 +1594,8 @@ def _update_integration(api_id, int_id, data):def _delete_integration(api_id, int_id):+ if err := _require_api(api_id):+ return err_integrations.get(api_id, {}).pop(int_id, None)_api_tags.pop(_api_resource_arn(api_id, "integrations", int_id), None)return 204, {}, b""@@ -1469,7 +1605,7 @@ def _delete_integration(api_id, int_id):def _create_stage(api_id, data):if api_id not in _apis:- return _apigw_error("NotFoundException", f"API {api_id} not found", 404)+ return _api_not_found(api_id)stage_name = data.get("stageName", "$default")stage = {"stageName": stage_name,@@ -1489,10 +1625,14 @@ def _create_stage(api_id, data):def _get_stages(api_id):+ if err := _require_api(api_id):+ return errreturn _apigw_response({"items": list(_stages.get(api_id, {}).values())})def _get_stage(api_id, stage_name):+ if err := _require_api(api_id):+ return errstage = _stages.get(api_id, {}).get(stage_name)if not stage:return _apigw_error("NotFoundException", f"Stage '{stage_name}' not found", 404)@@ -1500,6 +1640,8 @@ def _get_stage(api_id, stage_name):def _update_stage(api_id, stage_name, data):+ if err := _require_api(api_id):+ return errstage = _stages.get(api_id, {}).get(stage_name)if not stage:return _apigw_error("NotFoundException", f"Stage '{stage_name}' not found", 404)@@ -1512,6 +1654,8 @@ def _update_stage(api_id, stage_name, data):def _delete_stage(api_id, stage_name):+ if err := _require_api(api_id):+ return err_stages.get(api_id, {}).pop(stage_name, None)_api_tags.pop(_api_resource_arn(api_id, "stages", stage_name), None)return 204, {}, b""@@ -1521,7 +1665,7 @@ def _delete_stage(api_id, stage_name):def _create_deployment(api_id, data):if api_id not in _apis:- return _apigw_error("NotFoundException", f"API {api_id} not found", 404)+ return _api_not_found(api_id)deployment_id = new_uuid()[:8]deployment = {"deploymentId": deployment_id,@@ -1534,10 +1678,14 @@ def _create_deployment(api_id, data):def _get_deployments(api_id):+ if err := _require_api(api_id):+ return errreturn _apigw_response({"items": list(_deployments.get(api_id, {}).values())})def _get_deployment(api_id, deployment_id):+ if err := _require_api(api_id):+ return errdeployment = _deployments.get(api_id, {}).get(deployment_id)if not deployment:return _apigw_error("NotFoundException", f"Deployment {deployment_id} not found", 404)@@ -1545,6 +1693,8 @@ def _get_deployment(api_id, deployment_id):def _delete_deployment(api_id, deployment_id):+ if err := _require_api(api_id):+ return err_deployments.get(api_id, {}).pop(deployment_id, None)_api_tags.pop(_api_resource_arn(api_id, "deployments", deployment_id), None)return 204, {}, b""@@ -1569,7 +1719,7 @@ def _tag_resource_not_found(resource_arn: str):def _api_exists_in_request_region(api_id: str) -> bool:- return api_id in _apis and _api_regions.get(api_id, get_region()) == get_region()+ return api_id in _apisdef _validate_tag_resource_arn(resource_arn: str) -> tuple[str | None, tuple | None]:@@ -1647,7 +1797,7 @@ def _untag_resource(resource_arn: str, tag_keys: list):def _create_authorizer(api_id, data):if api_id not in _apis:- return _apigw_error("NotFoundException", f"API {api_id} not found", 404)+ return _api_not_found(api_id)auth_id = new_uuid()[:8]authorizer = {"authorizerId": auth_id,@@ -1666,10 +1816,14 @@ def _create_authorizer(api_id, data):def _get_authorizers(api_id):+ if err := _require_api(api_id):+ return errreturn _apigw_response({"items": list(_authorizers.get(api_id, {}).values())})def _get_authorizer(api_id, auth_id):+ if err := _require_api(api_id):+ return errauthorizer = _authorizers.get(api_id, {}).get(auth_id)if not authorizer:return _apigw_error("NotFoundException", f"Authorizer {auth_id} not found", 404)@@ -1677,6 +1831,8 @@ def _get_authorizer(api_id, auth_id):def _update_authorizer(api_id, auth_id, data):+ if err := _require_api(api_id):+ return errauthorizer = _authorizers.get(api_id, {}).get(auth_id)if not authorizer:return _apigw_error("NotFoundException", f"Authorizer {auth_id} not found", 404)@@ -1689,6 +1845,8 @@ def _update_authorizer(api_id, auth_id, data):def _delete_authorizer(api_id, auth_id):+ if err := _require_api(api_id):+ return err_authorizers.get(api_id, {}).pop(auth_id, None)_api_tags.pop(_api_resource_arn(api_id, "authorizers", auth_id), None)return 204, {}, b""@@ -1696,7 +1854,6 @@ def _delete_authorizer(api_id, auth_id):def reset():_apis.clear()- _api_regions.clear()_routes.clear()_integrations.clear()_stages.clear()@@ -1721,6 +1878,8 @@ def reset():# ==========================================================================def _create_route_response(api_id, route_id, data):+ if err := _require_api(api_id):+ return errroutes = _routes.get(api_id, {})if route_id not in routes:return _apigw_error("NotFoundException", f"Route {route_id} not found", 404)@@ -1738,11 +1897,19 @@ def _create_route_response(api_id, route_id, data):def _get_route_responses(api_id, route_id):+ if err := _require_api(api_id):+ return err+ if route_id not in _routes.get(api_id, {}):+ return _apigw_error("NotFoundException", f"Route {route_id} not found", 404)items = list(_route_responses.get(api_id, {}).get(route_id, {}).values())return _apigw_response({"items": items})def _get_route_response(api_id, route_id, rr_id):+ if err := _require_api(api_id):+ return err+ if route_id not in _routes.get(api_id, {}):+ return _apigw_error("NotFoundException", f"Route {route_id} not found", 404)rr = _route_responses.get(api_id, {}).get(route_id, {}).get(rr_id)if not rr:return _apigw_error("NotFoundException", f"RouteResponse {rr_id} not found", 404)@@ -1750,6 +1917,10 @@ def _get_route_response(api_id, route_id, rr_id):def _update_route_response(api_id, route_id, rr_id, data):+ if err := _require_api(api_id):+ return err+ if route_id not in _routes.get(api_id, {}):+ return _apigw_error("NotFoundException", f"Route {route_id} not found", 404)rr = _route_responses.get(api_id, {}).get(route_id, {}).get(rr_id)if not rr:return _apigw_error("NotFoundException", f"RouteResponse {rr_id} not found", 404)@@ -1760,6 +1931,10 @@ def _update_route_response(api_id, route_id, rr_id, data):def _delete_route_response(api_id, route_id, rr_id):+ if err := _require_api(api_id):+ return err+ if route_id not in _routes.get(api_id, {}):+ return _apigw_error("NotFoundException", f"Route {route_id} not found", 404)_route_responses.get(api_id, {}).get(route_id, {}).pop(rr_id, None)return 204, {}, b""@@ -1769,6 +1944,8 @@ def _delete_route_response(api_id, route_id, rr_id):# ==========================================================================def _create_integration_response(api_id, integration_id, data):+ if err := _require_api(api_id):+ return errintegs = _integrations.get(api_id, {})if integration_id not in integs:return _apigw_error("NotFoundException", f"Integration {integration_id} not found", 404)@@ -1787,11 +1964,19 @@ def _create_integration_response(api_id, integration_id, data):def _get_integration_responses(api_id, integration_id):+ if err := _require_api(api_id):+ return err+ if integration_id not in _integrations.get(api_id, {}):+ return _apigw_error("NotFoundException", f"Integration {integration_id} not found", 404)items = list(_integration_responses.get(api_id, {}).get(integration_id, {}).values())return _apigw_response({"items": items})def _get_integration_response(api_id, integration_id, ir_id):+ if err := _require_api(api_id):+ return err+ if integration_id not in _integrations.get(api_id, {}):+ return _apigw_error("NotFoundException", f"Integration {integration_id} not found", 404)ir = _integration_responses.get(api_id, {}).get(integration_id, {}).get(ir_id)if not ir:return _apigw_error("NotFoundException", f"IntegrationResponse {ir_id} not found", 404)@@ -1799,6 +1984,10 @@ def _get_integration_response(api_id, integration_id, ir_id):def _update_integration_response(api_id, integration_id, ir_id, data):+ if err := _require_api(api_id):+ return err+ if integration_id not in _integrations.get(api_id, {}):+ return _apigw_error("NotFoundException", f"Integration {integration_id} not found", 404)ir = _integration_responses.get(api_id, {}).get(integration_id, {}).get(ir_id)if not ir:return _apigw_error("NotFoundException", f"IntegrationResponse {ir_id} not found", 404)@@ -1810,6 +1999,10 @@ def _update_integration_response(api_id, integration_id, ir_id, data):def _delete_integration_response(api_id, integration_id, ir_id):+ if err := _require_api(api_id):+ return err+ if integration_id not in _integrations.get(api_id, {}):+ return _apigw_error("NotFoundException", f"Integration {integration_id} not found", 404)_integration_responses.get(api_id, {}).get(integration_id, {}).pop(ir_id, None)return 204, {}, b""@@ -1831,14 +2024,14 @@ def _api_protocol(api_id: str) -> str | None:def _api_owner(api_id: str):"""Return (protocolType, owner_account_id, owner_region) for an API or None."""- # AccountScopedDict stores keys as (account_id, original_key). Walk internals- # so we can find the owning account without knowing it up front.- for (acct, key), api in _apis._data.items():+ # WebSocket dispatch arrives before we know the owning account or region, so+ # scan every account+region slot directly.+ for (acct, region, key), api in _apis.all_items():if key == api_id:return (api.get("protocolType", "HTTP"),acct,- _api_regions.get_scoped(acct, None, api_id, get_region()),+ region,)return None@@ -2061,7 +2254,7 @@ async def handle_websocket(scope, receive, send, api_id: str, path_override: strpath = path_override if path_override is not None else scope.get("path", "")path_parts = path.lstrip("/").split("/", 1)tentative = path_parts[0] if path_parts and path_parts[0] else "$default"- configured_stages = _stages.get(api_id, {})+ configured_stages = _stages.get_scoped(account_id, owner_region, api_id, {})if tentative in configured_stages:stage = tentativeelif "$default" in configured_stages:diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 44e14d36..112df7b1 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -4473,7 +4473,6 @@ def _apigw_v2_api_create(logical_id, props, stack_name):if props.get("CorsConfiguration"):api["corsConfiguration"] = props["CorsConfiguration"]_apigw_v2._apis[api_id] = api- _apigw_v2._api_regions[api_id] = get_region()_apigw_v2._routes[api_id] = {}_apigw_v2._integrations[api_id] = {}_apigw_v2._stages[api_id] = {}@@ -4483,7 +4482,6 @@ def _apigw_v2_api_create(logical_id, props, stack_name):def _apigw_v2_api_delete(physical_id, props):_apigw_v2._apis.pop(physical_id, None)- _apigw_v2._api_regions.pop(physical_id, None)_apigw_v2._routes.pop(physical_id, None)_apigw_v2._integrations.pop(physical_id, None)_apigw_v2._stages.pop(physical_id, None)diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.pyindex 0736de3e..ee115313 100644--- a/tests/test_apigatewayv2.py+++ b/tests/test_apigatewayv2.py@@ -18,6 +18,19 @@ _endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")_EXECUTE_PORT = urlparse(_endpoint).port or 4566+def _regional_client(service: str, region: str):+ import boto3+ from botocore.config import Config++ return boto3.client(+ service,+ endpoint_url=_endpoint,+ aws_access_key_id="test",+ aws_secret_access_key="test",+ region_name=region,+ config=Config(region_name=region),+ )+def _make_zip(code: str) -> bytes:buf = io.BytesIO()with zipfile.ZipFile(buf, "w") as zf:@@ -122,6 +135,166 @@ def test_apigw_apis_are_region_isolated():assert e.value.response["Error"]["Code"] == "NotFoundException"+def test_apigw_control_plane_child_crud_is_region_isolated():+ import boto3+ from botocore.config import Config++ def cli(r):+ return boto3.client(+ "apigatewayv2", endpoint_url=_endpoint,+ aws_access_key_id="test", aws_secret_access_key="test",+ region_name=r, config=Config(region_name=r),+ )++ east, west = cli("us-east-1"), cli("us-west-2")++ http_api_id = east.create_api(+ Name=f"child-iso-http-{_uuid_mod.uuid4().hex[:8]}",+ ProtocolType="HTTP",+ )["ApiId"]+ route_id = east.create_route(ApiId=http_api_id, RouteKey="GET /items")["RouteId"]+ integration_id = east.create_integration(+ ApiId=http_api_id,+ IntegrationType="HTTP_PROXY",+ IntegrationUri="https://example.com",+ IntegrationMethod="GET",+ )["IntegrationId"]+ east.create_stage(ApiId=http_api_id, StageName="prod")+ deployment_id = east.create_deployment(ApiId=http_api_id)["DeploymentId"]+ authorizer_id = east.create_authorizer(+ ApiId=http_api_id,+ AuthorizerType="JWT",+ Name="jwt",+ IdentitySource=["$request.header.Authorization"],+ JwtConfiguration={+ "Audience": ["client"],+ "Issuer": "https://issuer.example.test",+ },+ )["AuthorizerId"]++ ws_api_id = east.create_api(+ Name=f"child-iso-ws-{_uuid_mod.uuid4().hex[:8]}",+ ProtocolType="WEBSOCKET",+ )["ApiId"]+ ws_integration_id = east.create_integration(+ ApiId=ws_api_id,+ IntegrationType="MOCK",+ )["IntegrationId"]+ ws_route_id = east.create_route(+ ApiId=ws_api_id,+ RouteKey="sendMessage",+ Target=f"integrations/{ws_integration_id}",+ )["RouteId"]+ route_response_id = east.create_route_response(+ ApiId=ws_api_id,+ RouteId=ws_route_id,+ RouteResponseKey="$default",+ )["RouteResponseId"]+ integration_response_id = east.create_integration_response(+ ApiId=ws_api_id,+ IntegrationId=ws_integration_id,+ IntegrationResponseKey="/200/",+ )["IntegrationResponseId"]++ calls = [+ lambda: west.update_api(ApiId=http_api_id, Name="wrong-region"),+ lambda: west.delete_api(ApiId=http_api_id),+ lambda: west.get_routes(ApiId=http_api_id),+ lambda: west.create_route(ApiId=http_api_id, RouteKey="GET /wrong"),+ lambda: west.get_route(ApiId=http_api_id, RouteId=route_id),+ lambda: west.update_route(ApiId=http_api_id, RouteId=route_id, RouteKey="GET /wrong"),+ lambda: west.delete_route(ApiId=http_api_id, RouteId=route_id),+ lambda: west.get_integrations(ApiId=http_api_id),+ lambda: west.create_integration(+ ApiId=http_api_id,+ IntegrationType="HTTP_PROXY",+ IntegrationUri="https://wrong.example",+ ),+ lambda: west.get_integration(ApiId=http_api_id, IntegrationId=integration_id),+ lambda: west.update_integration(+ ApiId=http_api_id,+ IntegrationId=integration_id,+ Description="wrong-region",+ ),+ lambda: west.delete_integration(ApiId=http_api_id, IntegrationId=integration_id),+ lambda: west.get_stages(ApiId=http_api_id),+ lambda: west.create_stage(ApiId=http_api_id, StageName="wrong"),+ lambda: west.get_stage(ApiId=http_api_id, StageName="prod"),+ lambda: west.update_stage(ApiId=http_api_id, StageName="prod", Description="wrong"),+ lambda: west.delete_stage(ApiId=http_api_id, StageName="prod"),+ lambda: west.get_deployments(ApiId=http_api_id),+ lambda: west.create_deployment(ApiId=http_api_id),+ lambda: west.get_deployment(ApiId=http_api_id, DeploymentId=deployment_id),+ lambda: west.delete_deployment(ApiId=http_api_id, DeploymentId=deployment_id),+ lambda: west.get_authorizers(ApiId=http_api_id),+ lambda: west.create_authorizer(+ ApiId=http_api_id,+ AuthorizerType="JWT",+ Name="wrong",+ IdentitySource=["$request.header.Authorization"],+ ),+ lambda: west.get_authorizer(ApiId=http_api_id, AuthorizerId=authorizer_id),+ lambda: west.update_authorizer(+ ApiId=http_api_id,+ AuthorizerId=authorizer_id,+ Name="wrong",+ ),+ lambda: west.delete_authorizer(ApiId=http_api_id, AuthorizerId=authorizer_id),+ lambda: west.get_route_responses(ApiId=ws_api_id, RouteId=ws_route_id),+ lambda: west.create_route_response(+ ApiId=ws_api_id,+ RouteId=ws_route_id,+ RouteResponseKey="$default",+ ),+ lambda: west.get_route_response(+ ApiId=ws_api_id,+ RouteId=ws_route_id,+ RouteResponseId=route_response_id,+ ),+ lambda: west.update_route_response(+ ApiId=ws_api_id,+ RouteId=ws_route_id,+ RouteResponseId=route_response_id,+ RouteResponseKey="$default",+ ),+ lambda: west.delete_route_response(+ ApiId=ws_api_id,+ RouteId=ws_route_id,+ RouteResponseId=route_response_id,+ ),+ lambda: west.get_integration_responses(+ ApiId=ws_api_id,+ IntegrationId=ws_integration_id,+ ),+ lambda: west.create_integration_response(+ ApiId=ws_api_id,+ IntegrationId=ws_integration_id,+ IntegrationResponseKey="/200/",+ ),+ lambda: west.get_integration_response(+ ApiId=ws_api_id,+ IntegrationId=ws_integration_id,+ IntegrationResponseId=integration_response_id,+ ),+ lambda: west.update_integration_response(+ ApiId=ws_api_id,+ IntegrationId=ws_integration_id,+ IntegrationResponseId=integration_response_id,+ IntegrationResponseKey="/200/",+ ),+ lambda: west.delete_integration_response(+ ApiId=ws_api_id,+ IntegrationId=ws_integration_id,+ IntegrationResponseId=integration_response_id,+ ),+ ]++ for call in calls:+ with pytest.raises(ClientError) as exc_info:+ call()+ assert exc_info.value.response["Error"]["Code"] == "NotFoundException"++def test_apigw_update_api(apigw):api_id = apigw.create_api(Name="update-api-before", ProtocolType="HTTP")["ApiId"]apigw.update_api(ApiId=api_id, Name="update-api-after")@@ -138,10 +311,11 @@ def test_apigw_delete_api(apigw):assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404def test_apigw_cfn_api_tracks_owner_region():- from ministack.core.responses import get_region, set_request_region+ from ministack.core.responses import get_account_id, get_region, set_request_regionfrom ministack.services import apigateway as _apigwfrom ministack.services.cloudformation import provisioners as _provisioners+ account_id = get_account_id()original_region = get_region()api_id = Nonetry:@@ -152,10 +326,10 @@ def test_apigw_cfn_api_tracks_owner_region():"cfn-apigwv2-region",)- assert _apigw._api_regions[api_id] == "us-west-2"+ assert _apigw._apis.get_scoped(account_id, "us-west-2", api_id)["apiId"] == api_id_provisioners._apigw_v2_api_delete(api_id, {})- assert api_id not in _apigw._api_regions+ assert _apigw._apis.get_scoped(account_id, "us-west-2", api_id) is Noneapi_id = Nonefinally:if api_id is not None:@@ -2065,7 +2239,7 @@ def handler(event, context):"""-def _make_fn(lam, name: str, code: str) -> str:+def _make_fn(lam, name: str, code: str, *, region: str = "us-east-1") -> str:try:lam.delete_function(FunctionName=name)except Exception:@@ -2093,13 +2267,14 @@ def _make_fn(lam, name: str, code: str) -> str:)except Exception:pass- return f"arn:aws:lambda:us-east-1:000000000000:function:{name}"+ return f"arn:aws:lambda:{region}:000000000000:function:{name}"def _wire_ws_api(apigw, lam, *, name_suffix: str,connect_code: str | None = None,default_code: str = _ECHO_CODE,- disconnect_code: str | None = None) -> tuple[str, dict]:+ disconnect_code: str | None = None,+ function_region: str = "us-east-1") -> tuple[str, dict]:"""Create a WS API + routes + integrations and return (apiId, metadata)."""api = apigw.create_api(Name=f"ws-{name_suffix}", ProtocolType="WEBSOCKET")api_id = api["ApiId"]@@ -2108,7 +2283,7 @@ def _wire_ws_api(apigw, lam, *, name_suffix: str,def _route(route_key: str, code: str):fn_name = f"ws-{name_suffix}-{route_key.lstrip('$')}-{uuid.uuid4().hex[:6]}"- arn = _make_fn(lam, fn_name, code)+ arn = _make_fn(lam, fn_name, code, region=function_region)meta["created_functions"].append(fn_name)integ = apigw.create_integration(ApiId=api_id,@@ -2254,6 +2429,50 @@ def test_ws_post_to_connection_from_management_api(apigw, lam):ws.close()+def test_ws_non_boot_region_routes_and_management_api():+ """A WebSocket API owned by a non-boot region routes frames and @connections+ operations through the API owner's region, not the server boot region."""+ import urllib.request++ apigw_west = _regional_client("apigatewayv2", "us-west-2")+ apigw_east = _regional_client("apigatewayv2", "us-east-1")+ lam_west = _regional_client("lambda", "us-west-2")+ api_id, _ = _wire_ws_api(+ apigw_west,+ lam_west,+ name_suffix=f"west-{_uuid_mod.uuid4().hex[:6]}",+ function_region="us-west-2",+ )+ with pytest.raises(ClientError) as exc_info:+ apigw_east.get_stages(ApiId=api_id)+ assert exc_info.value.response["Error"]["Code"] == "NotFoundException"+ ws = _WSClient(+ "localhost",+ _EXECUTE_PORT,+ "/prod",+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"},+ )+ try:+ ws.send(json.dumps({"action": "sendMessage", "payload": "west"}))+ reply = ws.recv()+ parsed = json.loads(reply)+ conn_id = parsed["connectionId"]+ assert parsed["eventType"] == "MESSAGE"+ assert parsed["body"]["payload"] == "west"++ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/prod/@connections/{conn_id}"+ req = urllib.request.Request(+ url,+ data=b"west-push",+ method="POST",+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"},+ )+ assert urllib.request.urlopen(req, timeout=30).status == 200+ assert ws.recv(timeout=3) == "west-push"+ finally:+ ws.close()++def test_ws_get_connection_returns_metadata(apigw, lam):"""@connections GetConnection returns connected-at / identity."""import urllib.request@@ -2614,6 +2833,40 @@ def test_apigwv2_custom_id_duplicate_rejected(apigw):assert exc_info.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409+def test_apigwv2_custom_id_duplicate_rejected_across_regions():+ """ms-custom-id values are account-wide unique, not region-local."""+ from ministack.core.responses import get_region, set_request_region+ from ministack.services import apigateway as apigw_mod++ original_region = get_region()+ api_id = f"v2regionaldup{_uuid_mod.uuid4().hex[:6]}"+ try:+ set_request_region("us-west-2")+ status, _headers, body = apigw_mod._create_api(+ {+ "name": "dup-west",+ "protocolType": "HTTP",+ "tags": {"ms-custom-id": api_id},+ }+ )+ assert status == 201+ assert json.loads(body)["apiId"] == api_id++ set_request_region("us-east-1")+ status, _headers, body = apigw_mod._create_api(+ {+ "name": "dup-east",+ "protocolType": "HTTP",+ "tags": {"ms-custom-id": api_id},+ }+ )+ assert status == 409+ assert json.loads(body)["__type"] == "ConflictException"+ assert apigw_mod.find_api_scope(api_id) == ("000000000000", "us-west-2")+ finally:+ set_request_region(original_region)++def test_apigwv2_custom_id_absent_uses_random(apigw):"""CreateApi without the tag continues to produce a random apiId."""resp = apigw.create_api(Name="random-id", ProtocolType="HTTP")@@ -2867,6 +3120,70 @@ def test_apigwv2_lambda_integration_uses_function_arn_region(apigw, lam):assert ":us-west-2:" in body+def test_apigwv2_unsigned_execute_resolves_non_boot_region_api():+ import urllib.error+ import urllib.request++ import boto3+ from botocore.config import Config++ west_apigw = boto3.client(+ "apigatewayv2",+ endpoint_url=_endpoint,+ aws_access_key_id="test",+ aws_secret_access_key="test",+ region_name="us-west-2",+ config=Config(region_name="us-west-2"),+ )+ west_lam = _lambda_client("us-west-2")+ fn_name = f"apigw-west-owner-{uuid.uuid4().hex[:6]}"+ west_arn = _make_regional_fn(west_lam, fn_name, "west-owner")++ api_id = west_apigw.create_api(+ Name=f"west-owner-api-{uuid.uuid4().hex[:6]}",+ ProtocolType="HTTP",+ )["ApiId"]+ integ = west_apigw.create_integration(+ ApiId=api_id,+ IntegrationType="AWS_PROXY",+ IntegrationUri=_wrapped_uri(west_arn),+ IntegrationMethod="POST",+ )+ west_apigw.create_route(+ ApiId=api_id,+ RouteKey="GET /hello",+ Target=f"integrations/{integ['IntegrationId']}",+ )+ west_apigw.create_stage(ApiId=api_id, StageName="prod", AutoDeploy=True)++ requests = [+ (+ f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/prod/hello",+ f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}",+ ),+ (+ f"http://localhost:{_EXECUTE_PORT}/_aws/execute-api/{api_id}/prod/hello",+ f"localhost:{_EXECUTE_PORT}",+ ),+ ]+ for url, host in requests:+ req = urllib.request.Request(url)+ req.add_header("Host", host)+ resp = urllib.request.urlopen(req, timeout=30)+ assert resp.status == 200+ body = resp.read().decode()+ assert body.startswith("west-owner:")+ assert ":us-west-2:" in body++ missing = urllib.request.Request(+ f"http://missing-api.execute-api.localhost:{_EXECUTE_PORT}/prod/hello"+ )+ missing.add_header("Host", f"missing-api.execute-api.localhost:{_EXECUTE_PORT}")+ with pytest.raises(urllib.error.HTTPError) as exc_info:+ urllib.request.urlopen(missing, timeout=30)+ assert exc_info.value.code == 404++def test_apigwv1_lambda_integration_uses_function_arn_region(apigw_v1, lam):import urllib.requestdiff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 5831a23b..4dd327c2 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -48,6 +48,12 @@ def _wait_stack(cfn, name, timeout=30):raise TimeoutError(f"Stack {name} stuck at {status}")+def _assert_apigwv2_api_not_found(call):+ with pytest.raises(ClientError) as exc_info:+ call()+ assert exc_info.value.response["Error"]["Code"] == "NotFoundException"++def _regional_cfn_test_client(service, region):import boto3from botocore.config import Config@@ -4299,7 +4305,7 @@ def test_cfn_apigwv2_integration_basic(cfn, apigw):# Delete and verify cleanupcfn.delete_stack(StackName=stack_name)_wait_stack(cfn, stack_name)- assert apigw.get_integrations(ApiId=api_id)["Items"] == []+ _assert_apigwv2_api_not_found(lambda: apigw.get_integrations(ApiId=api_id))def test_cfn_apigwv2_ms_custom_id(cfn, apigw):@@ -4383,7 +4389,7 @@ def test_cfn_apigwv2_route_basic(cfn, apigw):# Delete and verify cleanupcfn.delete_stack(StackName=stack_name)_wait_stack(cfn, stack_name)- assert apigw.get_routes(ApiId=api_id)["Items"] == []+ _assert_apigwv2_api_not_found(lambda: apigw.get_routes(ApiId=api_id))def test_cfn_apigwv2_authorizer_jwt(cfn, apigw):@@ -4464,7 +4470,7 @@ def test_cfn_apigwv2_authorizer_jwt(cfn, apigw):cfn.delete_stack(StackName=stack_name)_wait_stack(cfn, stack_name)- assert apigw.get_authorizers(ApiId=api_id)["Items"] == []+ _assert_apigwv2_api_not_found(lambda: apigw.get_authorizers(ApiId=api_id))def test_cfn_apigwv2_integration_getatt(cfn, apigw):@@ -4637,8 +4643,73 @@ def test_cfn_apigwv2_full_http_api_stack(cfn, apigw):cfn.delete_stack(StackName=stack_name)_wait_stack(cfn, stack_name)- assert apigw.get_integrations(ApiId=api_id)["Items"] == []- assert apigw.get_routes(ApiId=api_id)["Items"] == []+ _assert_apigwv2_api_not_found(lambda: apigw.get_integrations(ApiId=api_id))+ _assert_apigwv2_api_not_found(lambda: apigw.get_routes(ApiId=api_id))+++def test_cfn_apigwv2_full_http_api_stack_in_non_boot_region():+ """A region-B CloudFormation stack creates ApiGatewayV2 children in region B."""+ suffix = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-apigwv2-west-{suffix}"+ west_cfn = _regional_cfn_test_client("cloudformation", "us-west-2")+ west_apigw = _regional_cfn_test_client("apigatewayv2", "us-west-2")+ east_apigw = _regional_cfn_test_client("apigatewayv2", "us-east-1")+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "HttpApi": {+ "Type": "AWS::ApiGatewayV2::Api",+ "Properties": {+ "Name": f"{stack_name}-api",+ "ProtocolType": "HTTP",+ },+ },+ "Stage": {+ "Type": "AWS::ApiGatewayV2::Stage",+ "Properties": {+ "ApiId": {"Ref": "HttpApi"},+ "StageName": "$default",+ "AutoDeploy": True,+ },+ },+ "Integration": {+ "Type": "AWS::ApiGatewayV2::Integration",+ "Properties": {+ "ApiId": {"Ref": "HttpApi"},+ "IntegrationType": "AWS_PROXY",+ "IntegrationUri": "arn:aws:lambda:us-west-2:000000000000:function:my-handler",+ "PayloadFormatVersion": "2.0",+ },+ },+ "ProxyRoute": {+ "Type": "AWS::ApiGatewayV2::Route",+ "Properties": {+ "ApiId": {"Ref": "HttpApi"},+ "RouteKey": "ANY /{proxy+}",+ "Target": {"Fn::Join": ["/", ["integrations", {"Ref": "Integration"}]]},+ },+ },+ },+ }+ api_id = None+ try:+ west_cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))+ stack = _wait_stack(west_cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE"++ resources = west_cfn.describe_stack_resources(StackName=stack_name)["StackResources"]+ api_res = [r for r in resources if r["ResourceType"] == "AWS::ApiGatewayV2::Api"][0]+ api_id = api_res["PhysicalResourceId"]++ assert len(west_apigw.get_integrations(ApiId=api_id)["Items"]) == 1+ assert len(west_apigw.get_routes(ApiId=api_id)["Items"]) == 1+ assert len(west_apigw.get_stages(ApiId=api_id)["Items"]) == 1+ _assert_apigwv2_api_not_found(lambda: east_apigw.get_routes(ApiId=api_id))+ finally:+ _delete_cfn_test_stack(west_cfn, stack_name)++ if api_id is not None:+ _assert_apigwv2_api_not_found(lambda: west_apigw.get_routes(ApiId=api_id))def test_cfn_apigwv2_integration_ref_returns_integration_id_alone(cfn, apigw):diff --git a/tests/test_persistence.py b/tests/test_persistence.pyindex 920a1242..385c25f2 100644--- a/tests/test_persistence.py+++ b/tests/test_persistence.py@@ -4581,6 +4581,175 @@ def test_opensearch_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmassert persistence.load_state("opensearch") is None+def test_apigateway_v2_legacy_state_uses_api_region_sidecar_and_tag_arns(+ monkeypatch, tmp_path+):+ import json as _json++ from ministack.core.responses import (+ AccountScopedDict,+ get_account_id,+ get_region,+ set_request_account_id,+ set_request_region,+ )+ from ministack.services import apigateway as service++ original_account = get_account_id()+ original_region = get_region()+ account_id = "000000000000"+ boot_region = "us-east-1"+ api_region = "us-west-2"+ api_id = "legacy-http-api"+ fallback_api_id = "legacy-fallback-api"++ def scoped(value_by_api):+ store = AccountScopedDict()+ for key, value in value_by_api.items():+ store.set_scoped(account_id, None, key, value)+ return store++ payload = {+ "apis": scoped(+ {+ api_id: {"apiId": api_id, "name": "west-api"},+ fallback_api_id: {+ "apiId": fallback_api_id,+ "name": "fallback-api",+ },+ }+ ),+ "api_regions": scoped({api_id: api_region}),+ "routes": scoped({api_id: {"route-1": {"routeId": "route-1"}}}),+ "integrations": scoped(+ {api_id: {"int-1": {"integrationId": "int-1"}}}+ ),+ "stages": scoped({api_id: {"prod": {"stageName": "prod"}}}),+ "deployments": scoped({api_id: {"dep-1": {"deploymentId": "dep-1"}}}),+ "authorizers": scoped(+ {api_id: {"auth-1": {"authorizerId": "auth-1"}}}+ ),+ "route_responses": scoped(+ {api_id: {"route-1": {"rr-1": {"routeResponseId": "rr-1"}}}}+ ),+ "integration_responses": scoped(+ {+ api_id: {+ "int-1": {+ "ir-1": {"integrationResponseId": "ir-1"}+ }+ }+ }+ ),+ "api_tags": scoped(+ {+ f"arn:aws:apigateway:{api_region}::/apis/{api_id}": {+ "env": "west"+ }+ }+ ),+ }++ monkeypatch.setattr(persistence, "PERSIST_STATE", True)+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))+ (tmp_path / "apigateway.json").write_text(+ _json.dumps(+ {"__ministack_format__": 2, "payload": payload},+ default=persistence._json_default,+ )+ )++ loaded = persistence.load_state("apigateway")+ service.reset()+ try:+ set_request_account_id(account_id)+ set_request_region(boot_region)+ service.load_persisted_state(loaded)++ assert service._apis.get_scoped(account_id, api_region, api_id)[+ "name"+ ] == "west-api"+ assert service._routes.get_scoped(account_id, api_region, api_id) == {+ "route-1": {"routeId": "route-1"}+ }+ assert service._integrations.get_scoped(+ account_id, api_region, api_id+ ) == {"int-1": {"integrationId": "int-1"}}+ assert service._stages.get_scoped(account_id, api_region, api_id) == {+ "prod": {"stageName": "prod"}+ }+ assert service._deployments.get_scoped(+ account_id, api_region, api_id+ ) == {"dep-1": {"deploymentId": "dep-1"}}+ assert service._authorizers.get_scoped(+ account_id, api_region, api_id+ ) == {"auth-1": {"authorizerId": "auth-1"}}+ assert service._route_responses.get_scoped(+ account_id, api_region, api_id+ ) == {"route-1": {"rr-1": {"routeResponseId": "rr-1"}}}+ assert service._integration_responses.get_scoped(+ account_id, api_region, api_id+ ) == {+ "int-1": {"ir-1": {"integrationResponseId": "ir-1"}}+ }+ assert service._api_tags.get_scoped(+ account_id,+ api_region,+ f"arn:aws:apigateway:{api_region}::/apis/{api_id}",+ ) == {"env": "west"}+ assert (+ service._apis.get_scoped(account_id, boot_region, fallback_api_id)[+ "name"+ ]+ == "fallback-api"+ )+ assert service._apis.get_scoped(account_id, boot_region, api_id) is None+ finally:+ service.reset()+ set_request_account_id(original_account)+ set_request_region(original_region)+++def test_apigateway_v2_region_scoped_state_round_trips_and_rejects_v2_reader(+ monkeypatch, tmp_path+):+ import json as _json++ from ministack.core.responses import AccountRegionScopedDict+ from ministack.services import apigateway as service++ account_id = "000000000000"+ api_id = "regional-http-api"+ api_region = "us-west-2"+ apis = AccountRegionScopedDict()+ apis.set_scoped(+ account_id,+ api_region,+ api_id,+ {"apiId": api_id, "name": "regional API"},+ )++ monkeypatch.setattr(persistence, "PERSIST_STATE", True)+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))++ persistence.save_state("apigateway", {"apis": apis})+ raw = _json.loads((tmp_path / "apigateway.json").read_text())+ assert raw["__ministack_format__"] == 3++ loaded = persistence.load_state("apigateway")+ service.reset()+ try:+ service.load_persisted_state(loaded)+ assert service._apis.get_scoped(account_id, api_region, api_id)[+ "name"+ ] == "regional API"+ finally:+ service.reset()++ monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})+ assert persistence.load_state("apigateway") is None++def test_apigateway_v1_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmp_path):