Skip to content

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

Release 1.3.5 (#399)

Nahuel Nucera71555a7fc599
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6e8cedda..611f4f1e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,10 +7,24 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
-## [Unreleased] — 2026-04-20
+## [1.3.5] — 2026-04-20
### Added
-- **API Gateway v2 WebSocket APIs** — full WebSocket data plane and control plane on the execute-api host (`ws://{apiId}.execute-api.{host}:{port}/{stage}`). `CreateApi(ProtocolType=WEBSOCKET)` defaults `RouteSelectionExpression` to `$request.body.action`; adds full `RouteResponse` and `IntegrationResponse` CRUD (`Create/Get/Update/Delete` under `/v2/apis/{apiId}/routes/{routeId}/routeresponses` and `/integrations/{integrationId}/integrationresponses`). ASGI `websocket` scope is handled end-to-end: on connect, the `$connect` Lambda runs with the handshake's `queryStringParameters` / `multiValueQueryStringParameters` on the event so token-gated connect hooks work like AWS — 2xx accepts, non-2xx rejects. Incoming frames evaluate the API's `RouteSelectionExpression` and dispatch to `$connect` / `$disconnect` / `$default` / custom-action routes; Lambda event matches AWS WebSocket v2 proxy (`requestContext.connectionId` / `routeKey` / `eventType` / `messageId` / `identity.sourceIp`, real `disconnectStatusCode` + `disconnectReason` from the close frame). `AWS`, `AWS_PROXY`, and `MOCK` integration types supported (MOCK returns the first matching `IntegrationResponse.responseTemplates` entry). `@connections` management API served on the execute-api host: `PostToConnection` pushes to a per-connection outbox that the WS session drains (enables server-side push), `GetConnection`, `DeleteConnection`; unknown or closed connections return `410 GoneException`. Connections carry their owning account; cross-API `@connections` lookups are rejected and Lambda invocations run in the owner's context. No new dependencies — upgrade is served by hypercorn; tests use a stdlib-only WS client. Reported by @whittin3
+- **API Gateway v2 WebSocket APIs** — full WebSocket support on the execute-api host: `CreateApi(ProtocolType=WEBSOCKET)`, `RouteResponse` + `IntegrationResponse` CRUD, `$connect`/`$disconnect`/`$default`/custom-action route dispatch via `$request.body.*`, `AWS_PROXY`/`AWS`/`MOCK` integrations, and the `@connections` management API (`PostToConnection`/`GetConnection`/`DeleteConnection`) with per-connection outbox for server-side push. `$connect` receives `queryStringParameters`/`multiValueQueryStringParameters` so token-gated hooks work like AWS. Multi-tenant: connections carry their owning account. Reported by @whittin3. Fixes #383
+- **Resource Groups Tagging API — Phase 3** — `TagResources` and `UntagResources` across S3, Lambda, SQS, SNS, DynamoDB, EventBridge, KMS, ECR, ECS, Glue, Cognito (IdP + Identity), AppSync, Scheduler, CloudFront, EFS. Contributed by @AdigaAkhil (#384). Fixes #382
+
+### Changed
+- **Centralised service registry** — `SERVICE_HANDLERS`, `SERVICE_NAME_ALIASES`, and `_reset_all_state`'s module list are now derived from one `SERVICE_REGISTRY` in `app.py`. Adding a service is one dict entry. Contributed by @jgrumboe (#391)
+- **ASGI dispatcher refactor** — the monolithic `app()` is split into tiered helpers (pre-body / post-body / special data-plane / generic). Adds an `_is_potential_alb_request()` gate that skips the ALB module load for non-ALB traffic. Contributed by @jgrumboe (#394)
+
+### Fixed
+- **CloudFormation `AWS::Region` and provisioner ARNs ignored the caller's region** — CFN used a module-level `REGION` everywhere, so CDK bootstrap with `AWS_REGION=us-east-2` got `us-east-1` baked into every `${AWS::Region}` substitution and ~15 provisioner ARNs. Region is now a per-request contextvar (`get_region()`); CFN engine, handlers, and every provisioner use it. Reported by @youngkwangk. Fixes #398
+- **S3 `CompleteMultipartUpload` did not version the final object** — when versioning was enabled, the response lacked `x-amz-version-id` and the object never appeared in `list_object_versions`. Multipart now follows the same versioning path as `PutObject`. Reported by @adzcodemi. (#397) Fixes #392
+- **EC2 `CreateSecurityGroup` description parameter** — contributed by @AdigaAkhil (#396)
+- **Tagging `TagResources`/`UntagResources` error shape** — unsupported resource types and missing resources now return `InvalidParameterException` (400) in `FailedResourcesMap`, matching AWS. Previously returned `InternalServiceException` (501/500) or silently no-op'd on Lambda/SNS/SQS/Cognito-IDP. Writers/removers now raise a typed `_ResourceNotFound` that the entry point surfaces per-ARN. Docstrings added across every writer/remover.
+
+---
+
## [1.3.4] — 2026-04-20
### Fixed
diff --git a/ministack/app.py b/ministack/app.py
index 46713723..7cb61ac9 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -59,7 +59,7 @@ _NON_S3_VHOST_NAMES = frozenset({
from ministack.core.hypercorn_compat import install as _install_hypercorn_compat
from ministack.core.persistence import PERSIST_STATE, load_state, save_all
-from ministack.core.responses import set_request_account_id
+from ministack.core.responses import set_request_account_id, set_request_region
from ministack.core.router import detect_service, extract_access_key_id, extract_region
# Must run before hypercorn emits its first Expect: 100-continue reply.
@@ -603,6 +603,15 @@ async def _handle_execute_api_request(host: str, path: str, method: str, headers
stage = path_parts[0] if path_parts else "$default"
execute_path = "/" + path_parts[1] if len(path_parts) > 1 else "/"
try:
+ # WebSocket @connections management API — lives on the execute-api host
+ # at /{stage}/@connections/{connectionId}. Detect and dispatch before
+ # normal REST/HTTP routing.
+ conn_prefix = f"/{stage}/@connections/"
+ if path.startswith(conn_prefix):
+ connection_id = path[len(conn_prefix):].split("/", 1)[0]
+ return await _get_module("apigateway").handle_connections_api(
+ method, api_id, stage, connection_id, body, headers
+ )
if api_id in _get_module("apigateway_v1")._rest_apis:
return await _get_module("apigateway_v1").handle_execute(
api_id, stage, method, execute_path, headers, body, query_params
@@ -772,6 +781,33 @@ async def app(scope, receive, send):
await _handle_lifespan(scope, receive, send)
return
+ if scope["type"] == "websocket":
+ # WebSocket APIs only reach us via the execute-api host pattern:
+ # ws://{apiId}.execute-api.{host}[:port]/{stage}[/...]
+ ws_headers = {}
+ for name, value in scope.get("headers", []):
+ try:
+ ws_headers[name.decode("latin-1").lower()] = value.decode("utf-8")
+ except UnicodeDecodeError:
+ ws_headers[name.decode("latin-1").lower()] = value.decode("latin-1")
+ ws_host = ws_headers.get("host", "")
+ m = _EXECUTE_API_RE.match(ws_host)
+ if not m:
+ msg = await receive()
+ if msg.get("type") == "websocket.connect":
+ await send({"type": "websocket.close", "code": 1008})
+ return
+ ws_api_id = m.group(1)
+ try:
+ await _get_module("apigateway").handle_websocket(scope, receive, send, ws_api_id)
+ except Exception:
+ logger.exception("Error in WebSocket dispatch")
+ try:
+ await send({"type": "websocket.close", "code": 1011})
+ except Exception:
+ pass
+ return
+
if scope["type"] != "http":
return
@@ -803,6 +839,11 @@ async def app(scope, receive, send):
if _access_key:
set_request_account_id(_access_key)
+ # Set per-request region from SigV4 Credential scope so CFN's AWS::Region
+ # pseudo-param and ARN-building use the caller's region, not MINISTACK_REGION
+ # (issue #398). Falls back to MINISTACK_REGION env.
+ set_request_region(extract_region(headers))
+
if await _send_if_handled(send, await _handle_pre_body_request(method, path, headers, query_params, request_id)):
return
@@ -1017,8 +1058,16 @@ def _reset_all_state():
from ministack.core.persistence import PERSIST_STATE, STATE_DIR
- for service_config in SERVICE_REGISTRY.values():
- mod_name = service_config["module"]
+ # Stateful modules that don't have a routing entry in SERVICE_REGISTRY but
+ # still need reset() — REST API v1 (served via the apigateway module),
+ # SES v2 (served via the ses module), and EventBridge Pipes (CFN-only
+ # provisioner with a background poller thread that reset() must stop).
+ _extra_reset_modules = ("apigateway_v1", "ses_v2", "pipes")
+
+ module_names = {cfg["module"] for cfg in SERVICE_REGISTRY.values()}
+ module_names.update(_extra_reset_modules)
+
+ for mod_name in module_names:
if mod_name in _loaded_modules:
mod = _loaded_modules[mod_name]
try:
diff --git a/ministack/core/responses.py b/ministack/core/responses.py
index 6b687d73..ec636f39 100644
--- a/ministack/core/responses.py
+++ b/ministack/core/responses.py
@@ -40,6 +40,29 @@ def get_account_id() -> str:
return _request_account_id.get()
+# Request-scoped region. Set per-request in app.py from the SigV4 Authorization
+# header's Credential scope. Fixes #398 (CDK bootstrap resources inheriting the
+# wrong region when MINISTACK_REGION differs from the caller's AWS_REGION).
+_request_region: contextvars.ContextVar[str] = contextvars.ContextVar(
+ "_request_region",
+ default=os.environ.get("MINISTACK_REGION", "us-east-1"),
+)
+
+
+def set_request_region(region: str | None) -> None:
+ """Set the region for the current request. Falls back to MINISTACK_REGION /
+ ``us-east-1`` when the caller supplies nothing."""
+ if region:
+ _request_region.set(region)
+ else:
+ _request_region.set(os.environ.get("MINISTACK_REGION", "us-east-1"))
+
+
+def get_region() -> str:
+ """Return the region for the current request."""
+ return _request_region.get()
+
+
class AccountScopedDict:
"""A dict-like container that namespaces keys by the current request's account ID.
diff --git a/ministack/services/acm.py b/ministack/services/acm.py
index a7448075..749de884 100644
--- a/ministack/services/acm.py
+++ b/ministack/services/acm.py
@@ -15,7 +15,7 @@ import time
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, now_iso
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, now_iso, get_region
logger = logging.getLogger("acm")
@@ -52,7 +52,7 @@ def _epoch(iso_or_epoch):
def _cert_arn():
- return f"arn:aws:acm:{REGION}:{get_account_id()}:certificate/{new_uuid()}"
+ return f"arn:aws:acm:{get_region()}:{get_account_id()}:certificate/{new_uuid()}"
def _validation_options(domain, method):
diff --git a/ministack/services/alb.py b/ministack/services/alb.py
index da2e0528..3293cff0 100644
--- a/ministack/services/alb.py
+++ b/ministack/services/alb.py
@@ -28,7 +28,7 @@ import time
from urllib.parse import parse_qs
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid, get_region
logger = logging.getLogger("alb")
@@ -230,7 +230,7 @@ def _attrs_xml(attrs):
def _lb_xml(lb):
azs = "".join(
- f"<member><ZoneName>{REGION}a</ZoneName><SubnetId>{s}</SubnetId>"
+ f"<member><ZoneName>{get_region()}a</ZoneName><SubnetId>{s}</SubnetId>"
f"<LoadBalancerAddresses/></member>"
for s in lb.get("Subnets", [])
)
@@ -348,11 +348,11 @@ def _create_lb(params):
return _error("DuplicateLoadBalancerName",
f"A load balancer with name '{name}' already exists.")
lid = _short_id()
- arn = f"arn:aws:elasticloadbalancing:{REGION}:{get_account_id()}:loadbalancer/app/{name}/{lid}"
+ arn = f"arn:aws:elasticloadbalancing:{get_region()}:{get_account_id()}:loadbalancer/app/{name}/{lid}"
lb = {
"LoadBalancerArn": arn,
"LoadBalancerName": name,
- "DNSName": f"{name}-{lid[:8]}.{REGION}.elb.amazonaws.com",
+ "DNSName": f"{name}-{lid[:8]}.{get_region()}.elb.amazonaws.com",
"Scheme": _p(params, "Scheme", "internet-facing"),
"VpcId": _p(params, "VpcId", "vpc-00000001"),
"State": "active",
@@ -440,7 +440,7 @@ def _create_tg(params):
return _error("DuplicateTargetGroupName",
f"A target group with name '{name}' already exists.")
tid = _short_id()
- arn = f"arn:aws:elasticloadbalancing:{REGION}:{get_account_id()}:targetgroup/{name}/{tid}"
+ arn = f"arn:aws:elasticloadbalancing:{get_region()}:{get_account_id()}:targetgroup/{name}/{tid}"
tg = {
"TargetGroupArn": arn,
"TargetGroupName": name,
@@ -567,7 +567,7 @@ def _create_listener(params):
lb = _lbs[lb_arn]
lb_name = lb["LoadBalancerName"]
lb_id = lb_arn.split("/")[-1]
- l_arn = (f"arn:aws:elasticloadbalancing:{REGION}:{get_account_id()}"
+ l_arn = (f"arn:aws:elasticloadbalancing:{get_region()}:{get_account_id()}"
f":listener/app/{lb_name}/{lb_id}/{lid}")
actions = _parse_actions(params, "DefaultActions")
for action in actions:
@@ -588,7 +588,7 @@ def _create_listener(params):
_tags[l_arn] = _parse_tags(params)
# auto-create default rule
rule_id = _short_id()
- rule_arn = (f"arn:aws:elasticloadbalancing:{REGION}:{get_account_id()}"
+ rule_arn = (f"arn:aws:elasticloadbalancing:{get_region()}:{get_account_id()}"
f":listener-rule/app/{lb_name}/{lb_id}/{lid}/{rule_id}")
_rules[rule_arn] = {
"RuleArn": rule_arn, "ListenerArn": l_arn,
@@ -684,7 +684,7 @@ def _create_rule(params):
lb_id = lb_arn.split("/")[-1]
l_id = l_arn.split("/")[-1]
rule_id = _short_id()
- rule_arn = (f"arn:aws:elasticloadbalancing:{REGION}:{get_account_id()}"
+ rule_arn = (f"arn:aws:elasticloadbalancing:{get_region()}:{get_account_id()}"
f":listener-rule/app/{lb_name}/{lb_id}/{l_id}/{rule_id}")
rule = {
"RuleArn": rule_arn, "ListenerArn": l_arn,
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index 96764b42..b8bb90a5 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -49,7 +49,7 @@ import time
import urllib.error
import urllib.request
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, new_uuid, get_region
_HOST = os.environ.get("MINISTACK_HOST", "localhost")
_PORT = os.environ.get("GATEWAY_PORT", "4566")
@@ -89,7 +89,7 @@ def _apigw_error(code: str, message: str, status: int) -> tuple:
def _api_arn(api_id: str) -> str:
- return f"arn:aws:apigateway:{REGION}::/apis/{api_id}"
+ return f"arn:aws:apigateway:{get_region()}::/apis/{api_id}"
# ---- Persistence hooks ----
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 57deb81d..20246641 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -77,7 +77,7 @@ import time
import urllib.error
import urllib.request
-from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid, get_region
def _now_unix():
@@ -124,7 +124,7 @@ def _v1_error(code, message, status):
def _rest_api_arn(api_id):
- return f"arn:aws:apigateway:{REGION}::/restapis/{api_id}"
+ return f"arn:aws:apigateway:{get_region()}::/restapis/{api_id}"
def _compute_path(api_id, resource_id):
@@ -1448,7 +1448,7 @@ def _create_domain_name(data):
"certificateName": data.get("certificateName", ""),
"certificateArn": data.get("certificateArn", ""),
"distributionDomainName": f"{domain_name}.cloudfront.net",
- "regionalDomainName": f"{domain_name}.execute-api.{REGION}.amazonaws.com",
+ "regionalDomainName": f"{domain_name}.execute-api.{get_region()}.amazonaws.com",
"regionalHostedZoneId": "Z1UJRXOUMOOFQ8",
"endpointConfiguration": data.get("endpointConfiguration", {"types": ["REGIONAL"]}),
"tags": data.get("tags", {}),
diff --git a/ministack/services/appconfig.py b/ministack/services/appconfig.py
index 9e0a294b..29123ac7 100644
--- a/ministack/services/appconfig.py
+++ b/ministack/services/appconfig.py
@@ -34,7 +34,7 @@ import time
import uuid
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import AccountScopedDict, get_account_id
+from ministack.core.responses import AccountScopedDict, get_account_id, get_region
logger = logging.getLogger("appconfig")
@@ -98,24 +98,24 @@ def _now_iso():
def _app_arn(app_id):
- return f"arn:aws:appconfig:{REGION}:{get_account_id()}:application/{app_id}"
+ return f"arn:aws:appconfig:{get_region()}:{get_account_id()}:application/{app_id}"
def _env_arn(app_id, env_id):
- return f"arn:aws:appconfig:{REGION}:{get_account_id()}:application/{app_id}/environment/{env_id}"
+ return f"arn:aws:appconfig:{get_region()}:{get_account_id()}:application/{app_id}/environment/{env_id}"
def _profile_arn(app_id, profile_id):
- return f"arn:aws:appconfig:{REGION}:{get_account_id()}:application/{app_id}/configurationprofile/{profile_id}"
+ return f"arn:aws:appconfig:{get_region()}:{get_account_id()}:application/{app_id}/configurationprofile/{profile_id}"
def _strategy_arn(strategy_id):
- return f"arn:aws:appconfig:{REGION}:{get_account_id()}:deploymentstrategy/{strategy_id}"
+ return f"arn:aws:appconfig:{get_region()}:{get_account_id()}:deploymentstrategy/{strategy_id}"
def _deployment_arn(app_id, env_id, deploy_num):
return (
- f"arn:aws:appconfig:{REGION}:{get_account_id()}:"
+ f"arn:aws:appconfig:{get_region()}:{get_account_id()}:"
f"application/{app_id}/environment/{env_id}/deployment/{deploy_num}"
)
diff --git a/ministack/services/appsync.py b/ministack/services/appsync.py
index 68893f64..86be0270 100644
--- a/ministack/services/appsync.py
+++ b/ministack/services/appsync.py
@@ -25,7 +25,7 @@ import re
import time
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, get_region
logger = logging.getLogger("appsync")
@@ -64,7 +64,7 @@ def _now():
def _api_arn(api_id):
- return f"arn:aws:appsync:{REGION}:{get_account_id()}:apis/{api_id}"
+ return f"arn:aws:appsync:{get_region()}:{get_account_id()}:apis/{api_id}"
def _json(status, body):
@@ -96,8 +96,8 @@ def _create_graphql_api(body):
"authenticationType": auth_type,
"arn": arn,
"uris": {
- "GRAPHQL": f"https://{api_id}.appsync-api.{REGION}.amazonaws.com/graphql",
- "REALTIME": f"wss://{api_id}.appsync-realtime-api.{REGION}.amazonaws.com/graphql",
+ "GRAPHQL": f"https://{api_id}.appsync-api.{get_region()}.amazonaws.com/graphql",
+ "REALTIME": f"wss://{api_id}.appsync-realtime-api.{get_region()}.amazonaws.com/graphql",
},
"additionalAuthenticationProviders": additional_auth,
"xrayEnabled": xray,
diff --git a/ministack/services/athena.py b/ministack/services/athena.py
index b3e2f54c..75c9d828 100644
--- a/ministack/services/athena.py
+++ b/ministack/services/athena.py
@@ -22,7 +22,7 @@ import threading
import time
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, get_region
logger = logging.getLogger("athena")
@@ -144,11 +144,11 @@ _DUCKDB_TYPE_MAP = {
def _arn_workgroup(name):
- return f"arn:aws:athena:{REGION}:{get_account_id()}:workgroup/{name}"
+ return f"arn:aws:athena:{get_region()}:{get_account_id()}:workgroup/{name}"
def _arn_datacatalog(name):
- return f"arn:aws:athena:{REGION}:{get_account_id()}:datacatalog/{name}"
+ return f"arn:aws:athena:{get_region()}:{get_account_id()}:datacatalog/{name}"
async def handle_request(method, path, headers, body, query_params):
diff --git a/ministack/services/autoscaling.py b/ministack/services/autoscaling.py
index bbf04ca8..d0e3458f 100644
--- a/ministack/services/autoscaling.py
+++ b/ministack/services/autoscaling.py
@@ -19,7 +19,7 @@ import os
import time
from collections import defaultdict
-from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid, now_iso
+from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid, now_iso, get_region
logger = logging.getLogger("autoscaling")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
@@ -98,7 +98,7 @@ def _error(code, message, status=400):
def _asg_arn(name):
- return f"arn:aws:autoscaling:{REGION}:{get_account_id()}:autoScalingGroup:{new_uuid()}:autoScalingGroupName/{name}"
+ return f"arn:aws:autoscaling:{get_region()}:{get_account_id()}:autoScalingGroup:{new_uuid()}:autoScalingGroupName/{name}"
# ---------------------------------------------------------------------------
@@ -122,7 +122,7 @@ def _create_asg(p):
"MaxSize": int(_p(p, "MaxSize") or 0),
"DesiredCapacity": int(_p(p, "DesiredCapacity") or _p(p, "MinSize") or 0),
"DefaultCooldown": int(_p(p, "DefaultCooldown") or 300),
- "AvailabilityZones": _parse_member_list(p, "AvailabilityZones") or [f"{REGION}a"],
+ "AvailabilityZones": _parse_member_list(p, "AvailabilityZones") or [f"{get_region()}a"],
"HealthCheckType": _p(p, "HealthCheckType") or "EC2",
"HealthCheckGracePeriod": int(_p(p, "HealthCheckGracePeriod") or 300),
"Instances": [],
@@ -256,7 +256,7 @@ def _create_lc(p):
return _error("ValidationError", "LaunchConfigurationName is required")
if name in _launch_configs:
return _error("AlreadyExistsFault", f"LaunchConfiguration {name} already exists")
- arn = f"arn:aws:autoscaling:{REGION}:{get_account_id()}:launchConfiguration:{new_uuid()}:launchConfigurationName/{name}"
+ arn = f"arn:aws:autoscaling:{get_region()}:{get_account_id()}:launchConfiguration:{new_uuid()}:launchConfigurationName/{name}"
_launch_configs[name] = {
"LaunchConfigurationName": name,
"LaunchConfigurationARN": arn,
@@ -304,7 +304,7 @@ def _put_scaling_policy(p):
policy_name = _p(p, "PolicyName")
if not policy_name:
return _error("ValidationError", "PolicyName is required")
- arn = f"arn:aws:autoscaling:{REGION}:{get_account_id()}:scalingPolicy:{new_uuid()}:autoScalingGroupName/{asg_name}:policyName/{policy_name}"
+ arn = f"arn:aws:autoscaling:{get_region()}:{get_account_id()}:scalingPolicy:{new_uuid()}:autoScalingGroupName/{asg_name}:policyName/{policy_name}"
key = f"{asg_name}/{policy_name}"
_policies[key] = {
"PolicyARN": arn,
@@ -406,7 +406,7 @@ def _put_scheduled_action(p):
asg_name = _p(p, "AutoScalingGroupName")
action_name = _p(p, "ScheduledActionName")
key = f"{asg_name}/{action_name}"
- arn = f"arn:aws:autoscaling:{REGION}:{get_account_id()}:scheduledUpdateGroupAction:{new_uuid()}:autoScalingGroupName/{asg_name}:scheduledActionName/{action_name}"
+ arn = f"arn:aws:autoscaling:{get_region()}:{get_account_id()}:scheduledUpdateGroupAction:{new_uuid()}:autoScalingGroupName/{asg_name}:scheduledActionName/{action_name}"
_scheduled_actions[key] = {
"ScheduledActionARN": arn,
"ScheduledActionName": action_name,
diff --git a/ministack/services/cloudformation/engine.py b/ministack/services/cloudformation/engine.py
index 087de5a0..395e07da 100644
--- a/ministack/services/cloudformation/engine.py
+++ b/ministack/services/cloudformation/engine.py
@@ -12,13 +12,14 @@ from collections import defaultdict
import yaml
-from ministack.core.responses import get_account_id, new_uuid
+from ministack.core.responses import get_account_id, get_region, new_uuid
# Sentinel for AWS::NoValue
_NO_VALUE = object()
+# REGION kept for backwards compat with old imports; new code must prefer
+# get_region() so AWS::Region reflects the caller's request region (#398).
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
-# Note: get_account_id()/REGION duplicated here to keep engine.py free of __init__ imports (avoids circular deps)
# ===========================================================================
@@ -252,7 +253,7 @@ def _resolve_refs(value, resources, params, conditions, mappings,
pseudo = {
"AWS::StackName": stack_name,
"AWS::StackId": stack_id,
- "AWS::Region": REGION,
+ "AWS::Region": get_region(),
"AWS::AccountId": get_account_id(),
"AWS::NoValue": _NO_VALUE,
"AWS::URLSuffix": "amazonaws.com",
@@ -318,7 +319,7 @@ def _resolve_refs(value, resources, params, conditions, mappings,
pseudo = {
"AWS::StackName": stack_name,
"AWS::StackId": stack_id,
- "AWS::Region": REGION,
+ "AWS::Region": get_region(),
"AWS::AccountId": get_account_id(),
"AWS::URLSuffix": "amazonaws.com",
"AWS::Partition": "aws",
@@ -407,7 +408,7 @@ def _resolve_refs(value, resources, params, conditions, mappings,
region = _resolve_refs(value["Fn::GetAZs"], resources, params,
conditions, mappings, stack_name, stack_id)
if not region:
- region = REGION
+ region = get_region()
return [f"{region}a", f"{region}b", f"{region}c"]
# --- Fn::Cidr ---
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index 6919b603..52f37e5b 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -14,7 +14,8 @@ from .engine import (
_resolve_refs, _NO_VALUE,
)
from .stacks import _add_event, _deploy_stack_async, _delete_stack_async, _diff_resources
-from .provisioners import _provision_resource, REGION
+from .provisioners import _provision_resource
+from ministack.core.responses import get_region
from .helpers import _xml, _error, _p, _esc, _extract_members, _extract_stack_status_filters, _resolve_template, CFN_NS
from .changesets import (
_create_change_set, _describe_change_set, _execute_change_set,
@@ -61,7 +62,7 @@ def _create_stack(params):
return _error("ValidationError", str(exc))
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()}"
)
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index cd79d73f..f9b27745 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -12,7 +12,7 @@ import time
import zipfile
from collections import defaultdict
-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
import ministack.services.s3 as _s3
import ministack.services.sqs as _sqs
@@ -48,6 +48,8 @@ import ministack.services.codebuild as _codebuild
logger = logging.getLogger("cloudformation")
+# Module-level REGION kept for legacy imports; new code must use get_region()
+# so AWS::Region / ARNs reflect the caller's request region (#398).
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
@@ -105,7 +107,7 @@ def _s3_create(logical_id, props, stack_name):
_s3._buckets[name] = {
"created": now_iso(),
"objects": {},
- "region": REGION,
+ "region": get_region(),
}
versioning = props.get("VersioningConfiguration", {})
if versioning.get("Status") == "Enabled":
@@ -113,8 +115,8 @@ def _s3_create(logical_id, props, stack_name):
attrs = {
"Arn": f"arn:aws:s3:::{name}",
"DomainName": f"{name}.s3.amazonaws.com",
- "RegionalDomainName": f"{name}.s3.{REGION}.amazonaws.com",
- "WebsiteURL": f"http://{name}.s3-website-{REGION}.amazonaws.com",
+ "RegionalDomainName": f"{name}.s3.{get_region()}.amazonaws.com",
+ "WebsiteURL": f"http://{name}.s3-website-{get_region()}.amazonaws.com",
}
return name, attrs
@@ -151,7 +153,7 @@ def _sqs_create(logical_id, props, stack_name):
name = props.get("QueueName") or _physical_name(stack_name, logical_id, max_len=80)
is_fifo = name.endswith(".fifo")
url = f"http://{_sqs.DEFAULT_HOST}:{_sqs.DEFAULT_PORT}/{get_account_id()}/{name}"
- arn = f"arn:aws:sqs:{REGION}:{get_account_id()}:{name}"
+ arn = f"arn:aws:sqs:{get_region()}:{get_account_id()}:{name}"
now_ts = str(int(time.time()))
attributes = {
@@ -194,7 +196,7 @@ def _sqs_delete(physical_id, props):
def _sns_create(logical_id, props, stack_name):
name = props.get("TopicName") or _physical_name(stack_name, logical_id, max_len=256)
- arn = f"arn:aws:sns:{REGION}:{get_account_id()}:{name}"
+ arn = f"arn:aws:sns:{get_region()}:{get_account_id()}:{name}"
default_policy = json.dumps({
"Version": "2008-10-17",
"Id": "__default_policy_ID",
@@ -307,7 +309,7 @@ def _sns_sub_delete(physical_id, props):
def _ddb_create(logical_id, props, stack_name):
name = props.get("TableName") or _physical_name(stack_name, logical_id, max_len=255)
- arn = f"arn:aws:dynamodb:{REGION}:{get_account_id()}:table/{name}"
+ arn = f"arn:aws:dynamodb:{get_region()}:{get_account_id()}:table/{name}"
key_schema = props.get("KeySchema", [])
pk_name = None
@@ -385,7 +387,7 @@ def _zip_inline(source: str | None, handler: str, runtime: str = "python3.12") -
def _lambda_create(logical_id, props, stack_name):
name = props.get("FunctionName") or _physical_name(stack_name, logical_id, max_len=64)
- arn = f"arn:aws:lambda:{REGION}:{get_account_id()}:function:{name}"
+ arn = f"arn:aws:lambda:{get_region()}:{get_account_id()}:function:{name}"
runtime = props.get("Runtime", "python3.12")
handler = props.get("Handler", "index.handler")
role = props.get("Role", f"arn:aws:iam::{get_account_id()}:role/dummy-role")
@@ -584,7 +586,7 @@ def _ssm_create(logical_id, props, stack_name):
value = props.get("Value", "")
description = props.get("Description", "")
# ARN: no extra slash if name starts with /
- param_arn = f"arn:aws:ssm:{REGION}:{get_account_id()}:parameter{name}"
+ param_arn = f"arn:aws:ssm:{get_region()}:{get_account_id()}:parameter{name}"
_ssm._parameters[name] = {
"Name": name,
@@ -610,7 +612,7 @@ def _ssm_delete(physical_id, props):
def _cwlogs_create(logical_id, props, stack_name):
name = props.get("LogGroupName") or f"/aws/cloudformation/{stack_name}/{logical_id}"
- arn = f"arn:aws:logs:{REGION}:{get_account_id()}:log-group:{name}:*"
+ arn = f"arn:aws:logs:{get_region()}:{get_account_id()}:log-group:{name}:*"
retention = props.get("RetentionInDays")
_cw_logs._log_groups[name] = {
@@ -634,7 +636,7 @@ def _eb_rule_create(logical_id, props, stack_name):
name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=64)
bus = props.get("EventBusName", "default")
key = _eb._rule_key(name, bus)
- arn = f"arn:aws:events:{REGION}:{get_account_id()}:rule/{bus}/{name}"
+ arn = f"arn:aws:events:{get_region()}:{get_account_id()}:rule/{bus}/{name}"
_eb._rules[key] = {
"Name": name,
@@ -782,7 +784,7 @@ def _eb_event_bus_create(logical_id, props, stack_name):
"Tags": props.get("Tags", []),
}
_eb._create_event_bus(data)
- arn = f"arn:aws:events:{REGION}:{get_account_id()}:event-bus/{name}"
+ arn = f"arn:aws:events:{get_region()}:{get_account_id()}:event-bus/{name}"
return name, {"Arn": arn, "Name": name}
@@ -812,7 +814,7 @@ def _kinesis_stream_create(logical_id, props, stack_name):
if retention > 8760:
retention = 8760
- arn = f"arn:aws:kinesis:{REGION}:{get_account_id()}:stream/{name}"
+ arn = f"arn:aws:kinesis:{get_region()}:{get_account_id()}:stream/{name}"
stream_id = new_uuid()
_kinesis._streams[name] = {
@@ -895,7 +897,7 @@ def _lambda_version_create(logical_id, props, stack_name):
"code_zip": func.get("code_zip"),
}
return ver_arn, {"Version": ver_str}
- ver_arn = f"arn:aws:lambda:{REGION}:{get_account_id()}:function:{func_name}:1"
+ ver_arn = f"arn:aws:lambda:{get_region()}:{get_account_id()}:function:{func_name}:1"
return ver_arn, {"Version": "1"}
@@ -910,7 +912,7 @@ def _cfn_wait_condition_create(logical_id, props, stack_name):
def _cfn_wait_condition_handle_create(logical_id, props, stack_name):
"""WaitConditionHandle — no-op, return a presigned-style URL."""
pid = f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
- url = f"https://cloudformation-waitcondition-{REGION}.s3.amazonaws.com/{pid}"
+ url = f"https://cloudformation-waitcondition-{get_region()}.s3.amazonaws.com/{pid}"
return pid, {"Ref": url}
@@ -938,7 +940,7 @@ def _apigw_rest_api_create(logical_id, props, stack_name):
break
return api_id, {
"RootResourceId": root_id,
- "Arn": f"arn:aws:apigateway:{REGION}::/restapis/{api_id}",
+ "Arn": f"arn:aws:apigateway:{get_region()}::/restapis/{api_id}",
}
@@ -1061,7 +1063,7 @@ def _lambda_esm_create(logical_id, props, stack_name):
func_name = func_name.rsplit(":", 1)[-1]
esm_id = new_uuid()
func = _lambda_svc._functions.get(func_name)
- func_arn = func["config"]["FunctionArn"] if func else f"arn:aws:lambda:{REGION}:{get_account_id()}:function:{func_name}"
+ func_arn = func["config"]["FunctionArn"] if func else f"arn:aws:lambda:{get_region()}:{get_account_id()}:function:{func_name}"
esm = {
"UUID": esm_id,
@@ -1127,7 +1129,7 @@ def _lambda_alias_create(logical_id, props, stack_name):
func = _lambda_svc._functions.get(func_name)
if func:
alias = {
- "AliasArn": f"arn:aws:lambda:{REGION}:{get_account_id()}:function:{func_name}:{alias_name}",
+ "AliasArn": f"arn:aws:lambda:{get_region()}:{get_account_id()}:function:{func_name}:{alias_name}",
"Name": alias_name,
"FunctionVersion": func_version,
"Description": props.get("Description", ""),
@@ -1139,7 +1141,7 @@ def _lambda_alias_create(logical_id, props, stack_name):
func["aliases"][alias_name] = alias
return alias["AliasArn"], {"AliasArn": alias["AliasArn"]}
- alias_arn = f"arn:aws:lambda:{REGION}:{get_account_id()}:function:{func_name}:{alias_name}"
+ alias_arn = f"arn:aws:lambda:{get_region()}:{get_account_id()}:function:{func_name}:{alias_name}"
return alias_arn, {"AliasArn": alias_arn}
@@ -1207,12 +1209,12 @@ def _appsync_api_create(logical_id, props, stack_name):
name = props.get("Name") or _physical_name(stack_name, logical_id)
auth_type = props.get("AuthenticationType", "API_KEY")
api_id = new_uuid()[:8]
- arn = f"arn:aws:appsync:{REGION}:{get_account_id()}:apis/{api_id}"
+ arn = f"arn:aws:appsync:{get_region()}:{get_account_id()}:apis/{api_id}"
now = _time.time()
_appsync._apis[api_id] = {
"apiId": api_id, "name": name, "authenticationType": auth_type,
"arn": arn,
- "uris": {"GRAPHQL": f"https://{api_id}.appsync-api.{REGION}.amazonaws.com/graphql"},
+ "uris": {"GRAPHQL": f"https://{api_id}.appsync-api.{get_region()}.amazonaws.com/graphql"},
"createdAt": now, "lastUpdatedAt": now,
"additionalAuthenticationProviders": props.get("AdditionalAuthenticationProviders", []),
"xrayEnabled": False,
@@ -1221,7 +1223,7 @@ def _appsync_api_create(logical_id, props, stack_name):
_appsync._data_sources[api_id] = {}
_appsync._resolvers[api_id] = {}
_appsync._types[api_id] = {}
- return api_id, {"ApiId": api_id, "Arn": arn, "GraphQLUrl": f"https://{api_id}.appsync-api.{REGION}.amazonaws.com/graphql"}
+ return api_id, {"ApiId": api_id, "Arn": arn, "GraphQLUrl": f"https://{api_id}.appsync-api.{get_region()}.amazonaws.com/graphql"}
def _appsync_api_delete(physical_id, props):
@@ -1245,9 +1247,9 @@ def _appsync_ds_create(logical_id, props, stack_name):
body["serviceRoleArn"] = props["ServiceRoleArn"]
_appsync._data_sources.setdefault(api_id, {})[name] = {
"name": name, "type": ds_type, **body,
- "dataSourceArn": f"arn:aws:appsync:{REGION}:{get_account_id()}:apis/{api_id}/datasources/{name}",
+ "dataSourceArn": f"arn:aws:appsync:{get_region()}:{get_account_id()}:apis/{api_id}/datasources/{name}",
}
- return f"{api_id}/{name}", {"Name": name, "DataSourceArn": f"arn:aws:appsync:{REGION}:{get_account_id()}:apis/{api_id}/datasources/{name}"}
+ return f"{api_id}/{name}", {"Name": name, "DataSourceArn": f"arn:aws:appsync:{get_region()}:{get_account_id()}:apis/{api_id}/datasources/{name}"}
def _appsync_ds_delete(physical_id, props):
@@ -1264,7 +1266,7 @@ def _appsync_resolver_create(logical_id, props, stack_name):
resolver = {
"typeName": type_name, "fieldName": field_name,
"dataSourceName": ds_name,
- "resolverArn": f"arn:aws:appsync:{REGION}:{get_account_id()}:apis/{api_id}/types/{type_name}/resolvers/{field_name}",
+ "resolverArn": f"arn:aws:appsync:{get_region()}:{get_account_id()}:apis/{api_id}/types/{type_name}/resolvers/{field_name}",
}
if props.get("RequestMappingTemplate"):
resolver["requestMappingTemplate"] = props["RequestMappingTemplate"]
@@ -1298,7 +1300,7 @@ def _appsync_apikey_create(logical_id, props, stack_name):
"expires": props.get("Expires", int(time.time()) + 604800),
}
_appsync._api_keys.setdefault(api_id, {})[key_id] = key
- return key_id, {"ApiKey": key_id, "Arn": f"arn:aws:appsync:{REGION}:{get_account_id()}:apis/{api_id}/apikeys/{key_id}"}
+ return key_id, {"ApiKey": key_id, "Arn": f"arn:aws:appsync:{get_region()}:{get_account_id()}:apis/{api_id}/apikeys/{key_id}"}
def _appsync_apikey_delete(physical_id, props):
@@ -1333,7 +1335,7 @@ def _sm_secret_create(logical_id, props, stack_name):
else:
secret_string = generated
- arn = f"arn:aws:secretsmanager:{REGION}:{get_account_id()}:secret:{name}-{new_uuid()[:6]}"
+ arn = f"arn:aws:secretsmanager:{get_region()}:{get_account_id()}:secret:{name}-{new_uuid()[:6]}"
import time as _time
_sm._secrets[name] = {
"ARN": arn, "Name": name, "Description": props.get("Description", ""),
@@ -1399,7 +1401,7 @@ def _cognito_user_pool_create(logical_id, props, stack_name):
}
_cognito._user_pools[pid] = pool
arn = _cognito._pool_arn(pid)
- provider_name = f"cognito-idp.{REGION}.amazonaws.com/{pid}"
+ provider_name = f"cognito-idp.{get_region()}.amazonaws.com/{pid}"
return pid, {"Arn": arn, "ProviderName": provider_name}
@@ -1500,12 +1502,12 @@ def _cognito_user_pool_domain_delete(physical_id, props):
def _ecr_repo_create(logical_id, props, stack_name):
name = props.get("RepositoryName", f"{stack_name}-{logical_id}".lower())
- arn = f"arn:aws:ecr:{REGION}:{get_account_id()}:repository/{name}"
+ arn = f"arn:aws:ecr:{get_region()}:{get_account_id()}:repository/{name}"
_ecr._repositories[name] = {
"repositoryName": name,
"repositoryArn": arn,
"registryId": get_account_id(),
- "repositoryUri": f"{get_account_id()}.dkr.ecr.{REGION}.amazonaws.com/{name}",
+ "repositoryUri": f"{get_account_id()}.dkr.ecr.{get_region()}.amazonaws.com/{name}",
"createdAt": __import__("time").time(),
"imageTagMutability": props.get("ImageTagMutability", "MUTABLE"),
"imageScanningConfiguration": props.get("ImageScanningConfiguration", {"scanOnPush": False}),
@@ -1542,7 +1544,7 @@ def _codebuild_project_create(logical_id, props, stack_name):
"serviceRole": props.get("ServiceRole", f"arn:aws:iam::{get_account_id()}:role/codebuild-role"),
"timeoutInMinutes": int(props.get("TimeoutInMinutes", 60)),
"tags": [{"key": t["Key"], "value": t["Value"]} for t in props.get("Tags", [])],
- "encryptionKey": props.get("EncryptionKey", f"arn:aws:kms:{REGION}:{get_account_id()}:alias/aws/codebuild"),
+ "encryptionKey": props.get("EncryptionKey", f"arn:aws:kms:{get_region()}:{get_account_id()}:alias/aws/codebuild"),
}
_codebuild._create_project(data)
arn = _codebuild._project_arn(name)
@@ -1583,7 +1585,7 @@ def _iam_managed_policy_delete(physical_id, props):
def _kms_key_create(logical_id, props, stack_name):
key_id = new_uuid()
- arn = f"arn:aws:kms:{REGION}:{get_account_id()}:key/{key_id}"
+ arn = f"arn:aws:kms:{get_region()}:{get_account_id()}:key/{key_id}"
_kms._keys[key_id] = {
"KeyId": key_id,
"Arn": arn,
@@ -1655,7 +1657,7 @@ def _ec2_vpc_create(logical_id, props, stack_name):
"OwnerId": get_account_id(), "DefaultNetworkAclId": acl_id,
"DefaultSecurityGroupId": sg_id, "MainRouteTableId": rtb_id,
}
- arn = f"arn:aws:ec2:{REGION}:{get_account_id()}:vpc/{vpc_id}"
+ arn = f"arn:aws:ec2:{get_region()}:{get_account_id()}:vpc/{vpc_id}"
return vpc_id, {"VpcId": vpc_id, "DefaultSecurityGroup": sg_id, "DefaultNetworkAcl": acl_id}
@@ -1667,7 +1669,7 @@ def _ec2_subnet_create(logical_id, props, stack_name):
import random, string
vpc_id = props.get("VpcId", "")
cidr = props.get("CidrBlock", "10.0.1.0/24")
- az = props.get("AvailabilityZone", f"{REGION}a")
+ az = props.get("AvailabilityZone", f"{get_region()}a")
subnet_id = _ec2._new_subnet_id()
_ec2._subnets[subnet_id] = {
"SubnetId": subnet_id,
@@ -1721,7 +1723,7 @@ def _ec2_sg_create(logical_id, props, stack_name):
perm["IpRanges"].append({"CidrIp": rule["CidrIp"]})
_ec2._security_groups[sg_id]["IpPermissions"].append(perm)
- arn = f"arn:aws:ec2:{REGION}:{get_account_id()}:security-group/{sg_id}"
+ arn = f"arn:aws:ec2:{get_region()}:{get_account_id()}:security-group/{sg_id}"
return sg_id, {"GroupId": sg_id, "VpcId": vpc_id, "Arn": arn}
@@ -1832,7 +1834,7 @@ def _ec2_subnet_rtb_assoc_delete(physical_id, props):
def _ecs_cluster_create(logical_id, props, stack_name):
name = props.get("ClusterName", f"{stack_name}-{logical_id}")
- arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:cluster/{name}"
+ arn = f"arn:aws:ecs:{get_region()}:{get_account_id()}:cluster/{name}"
_ecs._clusters[name] = {
"clusterArn": arn,
"clusterName": name,
@@ -1886,7 +1888,7 @@ def _ecs_task_def_create(logical_id, props, stack_name):
family = props.get("Family", f"{stack_name}-{logical_id}")
revision = 1
td_key = f"{family}:{revision}"
- arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:task-definition/{td_key}"
+ arn = f"arn:aws:ecs:{get_region()}:{get_account_id()}:task-definition/{td_key}"
td = {
"taskDefinitionArn": arn,
"family": family,
@@ -1926,7 +1928,7 @@ def _ecs_service_create(logical_id, props, stack_name):
"networkConfiguration": props.get("NetworkConfiguration", {}),
"tags": [{"key": t["Key"], "value": t["Value"]} for t in props.get("Tags", [])],
})
- arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:service/{cluster}/{name}"
+ arn = f"arn:aws:ecs:{get_region()}:{get_account_id()}:service/{cluster}/{name}"
return arn, {"ServiceArn": arn, "Name": name}
@@ -2006,10 +2008,10 @@ def _elbv2_load_balancer_create(logical_id, props, stack_name):
)
lb_id = _alb._short_id()
arn = (
- f"arn:aws:elasticloadbalancing:{REGION}:{get_account_id()}:"
+ f"arn:aws:elasticloadbalancing:{get_region()}:{get_account_id()}:"
f"loadbalancer/app/{name}/{lb_id}"
)
- dns_name = f"{name}-{lb_id[:8]}.{REGION}.elb.amazonaws.com"
+ dns_name = f"{name}-{lb_id[:8]}.{get_region()}.elb.amazonaws.com"
lb = {
"LoadBalancerArn": arn,
"LoadBalancerName": name,
@@ -2080,7 +2082,7 @@ def _elbv2_listener_create(logical_id, props, stack_name):
lb_name = lb["LoadBalancerName"]
lb_id = lb_arn.split("/")[-1]
listener_arn = (
- f"arn:aws:elasticloadbalancing:{REGION}:{get_account_id()}:"
+ f"arn:aws:elasticloadbalancing:{get_region()}:{get_account_id()}:"
f"listener/app/{lb_name}/{lb_id}/{listener_id}"
)
@@ -2121,7 +2123,7 @@ def _elbv2_listener_create(logical_id, props, stack_name):
# Match alb service semantics: create a default rule for every listener.
rule_id = _alb._short_id()
rule_arn = (
- f"arn:aws:elasticloadbalancing:{REGION}:{get_account_id()}:"
+ f"arn:aws:elasticloadbalancing:{get_region()}:{get_account_id()}:"
f"listener-rule/app/{lb_name}/{lb_id}/{listener_id}/{rule_id}"
)
_alb._rules[rule_arn] = {
@@ -2168,7 +2170,7 @@ def _lambda_layer_create(logical_id, props, stack_name):
if s3_bucket and s3_key:
zip_data = _s3._get_object_data(s3_bucket, s3_key)
- layer_arn = f"arn:aws:lambda:{REGION}:{get_account_id()}:layer:{layer_name}"
+ layer_arn = f"arn:aws:lambda:{get_region()}:{get_account_id()}:layer:{layer_name}"
version_arn = f"{layer_arn}:{ver}"
ver_config = {
@@ -2212,7 +2214,7 @@ def _sfn_state_machine_create(logical_id, props, stack_name):
definition = _json.dumps(definition)
sm_type = props.get("StateMachineType", "STANDARD")
- arn = f"arn:aws:states:{REGION}:{get_account_id()}:stateMachine:{name}"
+ arn = f"arn:aws:states:{get_region()}:{get_account_id()}:stateMachine:{name}"
ts = now_iso()
_sfn._state_machines[arn] = {
"stateMachineArn": arn,
@@ -2423,7 +2425,7 @@ def _cw_metric_alarm_create(logical_id, props, stack_name):
alarm = {
"AlarmName": name,
- "AlarmArn": f"arn:aws:cloudwatch:{REGION}:{get_account_id()}:alarm:{name}",
+ "AlarmArn": f"arn:aws:cloudwatch:{get_region()}:{get_account_id()}:alarm:{name}",
"AlarmDescription": props.get("AlarmDescription", "") or "",
"MetricName": metric_name,
"Namespace": namespace,
@@ -2553,7 +2555,7 @@ def _waf_web_acl_create(logical_id, props, stack_name):
uid = new_uuid()
lock_token = new_uuid()
scope = props.get("Scope", "REGIONAL")
- arn = f"arn:aws:wafv2:{REGION}:{get_account_id()}:{scope.lower()}/webacl/{name}/{uid}"
+ arn = f"arn:aws:wafv2:{get_region()}:{get_account_id()}:{scope.lower()}/webacl/{name}/{uid}"
_waf._web_acls[uid] = {
"ARN": arn, "Id": uid, "Name": name,
"Description": props.get("Description", ""),
@@ -2609,7 +2611,7 @@ def _rds_db_cluster_create(logical_id, props, stack_name):
engine = props.get("Engine", "aurora-postgresql")
engine_version = props.get("EngineVersion", "15.4")
master_user = props.get("MasterUsername", "admin")
- arn = f"arn:aws:rds:{REGION}:{get_account_id()}:cluster:{cluster_id}"
+ arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:cluster:{cluster_id}"
suffix = new_uuid()[:8]
_rds._clusters[cluster_id] = {
@@ -2621,11 +2623,11 @@ def _rds_db_cluster_create(logical_id, props, stack_name):
"Status": "available",
"MasterUsername": master_user,
"DatabaseName": props.get("DatabaseName", ""),
- "Endpoint": f"{cluster_id}.cluster-{suffix}.{REGION}.rds.amazonaws.com",
- "ReaderEndpoint": f"{cluster_id}.cluster-ro-{suffix}.{REGION}.rds.amazonaws.com",
+ "Endpoint": f"{cluster_id}.cluster-{suffix}.{get_region()}.rds.amazonaws.com",
+ "ReaderEndpoint": f"{cluster_id}.cluster-ro-{suffix}.{get_region()}.rds.amazonaws.com",
"Port": int(props.get("Port", 5432)),
"MultiAZ": props.get("MultiAZ", False),
- "AvailabilityZones": [f"{REGION}a", f"{REGION}b", f"{REGION}c"],
+ "AvailabilityZones": [f"{get_region()}a", f"{get_region()}b", f"{get_region()}c"],
"DBClusterMembers": [],
"VpcSecurityGroups": [],
"DBSubnetGroup": props.get("DBSubnetGroupName", "default"),
@@ -2639,9 +2641,9 @@ def _rds_db_cluster_create(logical_id, props, stack_name):
return cluster_id, {
"Arn": arn,
"ClusterResourceId": f"cluster-{new_uuid()[:20]}",
- "Endpoint.Address": f"{cluster_id}.cluster-{suffix}.{REGION}.rds.amazonaws.com",
+ "Endpoint.Address": f"{cluster_id}.cluster-{suffix}.{get_region()}.rds.amazonaws.com",
"Endpoint.Port": str(int(props.get("Port", 5432))),
- "ReadEndpoint.Address": f"{cluster_id}.cluster-ro-{suffix}.{REGION}.rds.amazonaws.com",
+ "ReadEndpoint.Address": f"{cluster_id}.cluster-ro-{suffix}.{get_region()}.rds.amazonaws.com",
}
@@ -2655,7 +2657,7 @@ def _rds_db_cluster_delete(physical_id, props):
def _asg_create(logical_id, props, stack_name):
name = props.get("AutoScalingGroupName") or _physical_name(stack_name, logical_id, max_len=255)
- arn = f"arn:aws:autoscaling:{REGION}:{get_account_id()}:autoScalingGroup:{new_uuid()}:autoScalingGroupName/{name}"
+ arn = f"arn:aws:autoscaling:{get_region()}:{get_account_id()}:autoScalingGroup:{new_uuid()}:autoScalingGroupName/{name}"
asg = {
"AutoScalingGroupName": name,
"AutoScalingGroupARN": arn,
@@ -2665,7 +2667,7 @@ def _asg_create(logical_id, props, stack_name):
"MaxSize": int(props.get("MaxSize", 0)),
"DesiredCapacity": int(props.get("DesiredCapacity", props.get("MinSize", 0))),
"DefaultCooldown": int(props.get("Cooldown", 300)),
- "AvailabilityZones": props.get("AvailabilityZones", [f"{REGION}a"]),
+ "AvailabilityZones": props.get("AvailabilityZones", [f"{get_region()}a"]),
"HealthCheckType": props.get("HealthCheckType", "EC2"),
"HealthCheckGracePeriod": int(props.get("HealthCheckGracePeriod", 300)),
"Instances": [],
@@ -2705,7 +2707,7 @@ def _asg_delete(physical_id, props):
def _asg_lc_create(logical_id, props, stack_name):
name = props.get("LaunchConfigurationName") or _physical_name(stack_name, logical_id, max_len=255)
- arn = f"arn:aws:autoscaling:{REGION}:{get_account_id()}:launchConfiguration:{new_uuid()}:launchConfigurationName/{name}"
+ arn = f"arn:aws:autoscaling:{get_region()}:{get_account_id()}:launchConfiguration:{new_uuid()}:launchConfigurationName/{name}"
_asg._launch_configs[name] = {
"LaunchConfigurationName": name,
"LaunchConfigurationARN": arn,
@@ -2726,7 +2728,7 @@ def _asg_lc_delete(physical_id, props):
def _asg_policy_create(logical_id, props, stack_name):
asg_name = props.get("AutoScalingGroupName", "")
policy_name = props.get("PolicyName") or _physical_name(stack_name, logical_id, max_len=255)
- arn = f"arn:aws:autoscaling:{REGION}:{get_account_id()}:scalingPolicy:{new_uuid()}:autoScalingGroupName/{asg_name}:policyName/{policy_name}"
+ arn = f"arn:aws:autoscaling:{get_region()}:{get_account_id()}:scalingPolicy:{new_uuid()}:autoScalingGroupName/{asg_name}:policyName/{policy_name}"
key = f"{asg_name}/{policy_name}"
_asg._policies[key] = {
"PolicyARN": arn,
@@ -2772,7 +2774,7 @@ def _asg_hook_delete(physical_id, props):
def _asg_scheduled_create(logical_id, props, stack_name):
asg_name = props.get("AutoScalingGroupName", "")
action_name = props.get("ScheduledActionName") or _physical_name(stack_name, logical_id, max_len=255)
- arn = f"arn:aws:autoscaling:{REGION}:{get_account_id()}:scheduledUpdateGroupAction:{new_uuid()}:autoScalingGroupName/{asg_name}:scheduledActionName/{action_name}"
+ arn = f"arn:aws:autoscaling:{get_region()}:{get_account_id()}:scheduledUpdateGroupAction:{new_uuid()}:autoScalingGroupName/{asg_name}:scheduledActionName/{action_name}"
key = f"{asg_name}/{action_name}"
_asg._scheduled_actions[key] = {
"ScheduledActionARN": arn,
diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.py
index 7d9152b2..cd8fe00b 100644
--- a/ministack/services/cloudwatch.py
+++ b/ministack/services/cloudwatch.py
@@ -21,7 +21,7 @@ from datetime import datetime, timezone
from urllib.parse import parse_qs
from ministack.core.persistence import load_state, PERSIST_STATE
-from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid, get_region
logger = logging.getLogger("cloudwatch")
@@ -700,7 +700,7 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):
name = cbor_data.get("AlarmName", "")
alarm = {
"AlarmName": name,
- "AlarmArn": f"arn:aws:cloudwatch:{REGION}:{get_account_id()}:alarm:{name}",
+ "AlarmArn": f"arn:aws:cloudwatch:{get_region()}:{get_account_id()}:alarm:{name}",
"AlarmDescription": cbor_data.get("AlarmDescription", ""),
"MetricName": cbor_data.get("MetricName"),
"Namespace": cbor_data.get("Namespace"),
@@ -754,7 +754,7 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):
oi += 1
alarm = {
"AlarmName": name,
- "AlarmArn": f"arn:aws:cloudwatch:{REGION}:{get_account_id()}:alarm:{name}",
+ "AlarmArn": f"arn:aws:cloudwatch:{get_region()}:{get_account_id()}:alarm:{name}",
"AlarmDescription": _p(params, "AlarmDescription"),
"MetricName": _p(params, "MetricName"),
"Namespace": _p(params, "Namespace"),
@@ -838,7 +838,7 @@ def _put_composite_alarm(params, cbor_data, is_cbor, is_json=False):
_composite_alarms[name] = {
"AlarmName": name,
- "AlarmArn": f"arn:aws:cloudwatch:{REGION}:{get_account_id()}:alarm:{name}",
+ "AlarmArn": f"arn:aws:cloudwatch:{get_region()}:{get_account_id()}:alarm:{name}",
"AlarmDescription": desc,
"AlarmRule": alarm_rule,
"StateValue": "INSUFFICIENT_DATA",
@@ -1051,7 +1051,7 @@ def _delete_alarms(params, cbor_data, is_cbor, is_json=False):
for n in names:
_alarms.pop(n, None)
_composite_alarms.pop(n, None)
- _resource_tags.pop(f"arn:aws:cloudwatch:{REGION}:{get_account_id()}:alarm:{n}", None)
+ _resource_tags.pop(f"arn:aws:cloudwatch:{get_region()}:{get_account_id()}:alarm:{n}", None)
if is_cbor:
return _cbor_ok({})
@@ -1464,7 +1464,7 @@ def cloudformation_delete_metric_alarm(name: str) -> None:
"""Remove a metric alarm created from a template (not composite alarms)."""
_alarms.pop(name, None)
_resource_tags.pop(
- f"arn:aws:cloudwatch:{REGION}:{get_account_id()}:alarm:{name}", None
+ f"arn:aws:cloudwatch:{get_region()}:{get_account_id()}:alarm:{name}", None
)
diff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.py
index e1a92a9b..568a1451 100644
--- a/ministack/services/cloudwatch_logs.py
+++ b/ministack/services/cloudwatch_logs.py
@@ -22,7 +22,7 @@ import json
import logging
import time
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, get_region
logger = logging.getLogger("logs")
@@ -71,7 +71,7 @@ if _restored:
# ---------------------------------------------------------------------------
def _make_group_arn(name):
- return f"arn:aws:logs:{REGION}:{get_account_id()}:log-group:{name}:*"
+ return f"arn:aws:logs:{get_region()}:{get_account_id()}:log-group:{name}:*"
def _resolve_group_by_arn(arn):
@@ -317,7 +317,7 @@ def _describe_log_streams(data):
"creationTime": s["creationTime"],
"storedBytes": sum(len(e.get("message", "")) for e in s["events"]),
"uploadSequenceToken": s["uploadSequenceToken"],
- "arn": f"arn:aws:logs:{REGION}:{get_account_id()}:log-group:{group}:log-stream:{n}",
+ "arn": f"arn:aws:logs:{get_region()}:{get_account_id()}:log-group:{group}:log-stream:{n}",
}
if s.get("firstEventTimestamp") is not None:
entry["firstEventTimestamp"] = s["firstEventTimestamp"]
@@ -701,7 +701,7 @@ def _put_destination(data):
name = data.get("destinationName")
if not name:
return error_response_json("InvalidParameterException", "destinationName is required.", 400)
- dest_arn = f"arn:aws:logs:{REGION}:{get_account_id()}:destination:{name}"
+ dest_arn = f"arn:aws:logs:{get_region()}:{get_account_id()}:destination:{name}"
_destinations[name] = {
"destinationName": name,
"targetArn": data.get("targetArn", ""),
diff --git a/ministack/services/codebuild.py b/ministack/services/codebuild.py
index c02d3612..a591fc02 100644
--- a/ministack/services/codebuild.py
+++ b/ministack/services/codebuild.py
@@ -16,7 +16,7 @@ import os
import time
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import AccountScopedDict, error_response_json, get_account_id, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, error_response_json, get_account_id, json_response, new_uuid, get_region
logger = logging.getLogger("codebuild")
@@ -56,11 +56,11 @@ if _restored:
# ---------------------------------------------------------------------------
def _project_arn(name):
- return f"arn:aws:codebuild:{REGION}:{get_account_id()}:project/{name}"
+ return f"arn:aws:codebuild:{get_region()}:{get_account_id()}:project/{name}"
def _build_arn(build_id):
- return f"arn:aws:codebuild:{REGION}:{get_account_id()}:build/{build_id}"
+ return f"arn:aws:codebuild:{get_region()}:{get_account_id()}:build/{build_id}"
def _build_id(project_name):
@@ -102,7 +102,7 @@ def _make_build_record(project, build_id, source_version=None):
},
"timeoutInMinutes": project.get("timeoutInMinutes", 60),
"initiator": f"{get_account_id()}/user",
- "encryptionKey": f"arn:aws:kms:{REGION}:{get_account_id()}:alias/aws/codebuild",
+ "encryptionKey": f"arn:aws:kms:{get_region()}:{get_account_id()}:alias/aws/codebuild",
}
@@ -171,7 +171,7 @@ def _create_project(data):
"created": now,
"lastModified": now,
"encryptionKey": data.get("encryptionKey",
- f"arn:aws:kms:{REGION}:{get_account_id()}:alias/aws/codebuild"),
+ f"arn:aws:kms:{get_region()}:{get_account_id()}:alias/aws/codebuild"),
"badge": {"badgeEnabled": False},
}
_projects[name] = project
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 294b640b..dfb9cca2 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -68,7 +68,7 @@ from xml.etree.ElementTree import Element, SubElement, tostring as xml_tostring
from defusedxml.ElementTree import fromstring as safe_xml_parse
from ministack.core.persistence import load_state, PERSIST_STATE
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, get_region
logger = logging.getLogger("cognito")
@@ -125,7 +125,7 @@ def well_known_jwks(pool_id: str):
def well_known_openid_configuration(pool_id: str, region: str | None = None):
"""Return OpenID Connect discovery document."""
- r = region or REGION
+ r = region or get_region()
issuer = f"https://cognito-idp.{r}.amazonaws.com/{pool_id}"
doc = {
"issuer": issuer,
@@ -244,12 +244,12 @@ def _now_epoch() -> float:
def _pool_arn(pool_id: str) -> str:
- return f"arn:aws:cognito-idp:{REGION}:{get_account_id()}:userpool/{pool_id}"
+ return f"arn:aws:cognito-idp:{get_region()}:{get_account_id()}:userpool/{pool_id}"
def _pool_id() -> str:
suffix = "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(26))
- return f"{REGION}_{suffix[:9]}"
+ return f"{get_region()}_{suffix[:9]}"
def _client_id() -> str:
@@ -261,11 +261,11 @@ def _client_secret() -> str:
def _identity_pool_id() -> str:
- return f"{REGION}:{new_uuid()}"
+ return f"{get_region()}:{new_uuid()}"
def _identity_id(pool_id: str) -> str:
- return f"{REGION}:{new_uuid()}"
+ return f"{get_region()}:{new_uuid()}"
def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "access",
@@ -279,7 +279,7 @@ def _fake_token(sub: str, pool_id: str, client_id: str, token_type: str = "acces
origin_jti = new_uuid()
claims = {
"sub": sub,
- "iss": f"https://cognito-idp.{REGION}.amazonaws.com/{pool_id}",
+ "iss": f"https://cognito-idp.{get_region()}.amazonaws.com/{pool_id}",
"token_use": token_type,
"iat": now,
"exp": now + 3600,
@@ -1806,7 +1806,7 @@ def _create_user_pool_domain(data):
return error_response_json("InvalidParameterException", f"Domain {domain} already exists.", 400)
pool["Domain"] = domain
_pool_domain_map[domain] = pid
- return json_response({"CloudFrontDomain": f"{domain}.auth.{REGION}.amazoncognito.com"})
+ return json_response({"CloudFrontDomain": f"{domain}.auth.{get_region()}.amazoncognito.com"})
def _delete_user_pool_domain(data):
@@ -1832,7 +1832,7 @@ def _describe_user_pool_domain(data):
"AWSAccountId": get_account_id(),
"Domain": domain,
"S3Bucket": "",
- "CloudFrontDistribution": f"{domain}.auth.{REGION}.amazoncognito.com",
+ "CloudFrontDistribution": f"{domain}.auth.{get_region()}.amazoncognito.com",
"Version": "1",
"Status": "ACTIVE",
"CustomDomainConfig": {},
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index f4013164..9102486f 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -27,6 +27,7 @@ from ministack.core.responses import (
json_response,
new_uuid,
now_iso,
+ get_region,
)
logger = logging.getLogger("dynamodb")
@@ -93,7 +94,7 @@ def _emit_stream_event(table_name: str, event_name: str, old_item: dict | None,
"eventName": event_name,
"eventVersion": "1.1",
"eventSource": "aws:dynamodb",
- "awsRegion": REGION,
+ "awsRegion": get_region(),
"dynamodb": {
"ApproximateCreationDateTime": int(time.time()),
"Keys": {},
@@ -241,11 +242,11 @@ def _create_table(data):
for gsi in gsis:
gsi.setdefault("IndexStatus", "ACTIVE")
gsi.setdefault("ProvisionedThroughput", gsi_default_throughput)
- gsi["IndexArn"] = f"arn:aws:dynamodb:{REGION}:{get_account_id()}:table/{name}/index/{gsi['IndexName']}"
+ gsi["IndexArn"] = f"arn:aws:dynamodb:{get_region()}:{get_account_id()}:table/{name}/index/{gsi['IndexName']}"
gsi["IndexSizeBytes"] = 0
gsi["ItemCount"] = 0
for lsi in lsis:
- lsi["IndexArn"] = f"arn:aws:dynamodb:{REGION}:{get_account_id()}:table/{name}/index/{lsi['IndexName']}"
+ lsi["IndexArn"] = f"arn:aws:dynamodb:{get_region()}:{get_account_id()}:table/{name}/index/{lsi['IndexName']}"
lsi["IndexSizeBytes"] = 0
lsi["ItemCount"] = 0
@@ -260,7 +261,7 @@ def _create_table(data):
"CreationDateTime": int(time.time()),
"ItemCount": 0,
"TableSizeBytes": 0,
- "TableArn": f"arn:aws:dynamodb:{REGION}:{get_account_id()}:table/{name}",
+ "TableArn": f"arn:aws:dynamodb:{get_region()}:{get_account_id()}:table/{name}",
"TableId": new_uuid(),
"GlobalSecondaryIndexes": gsis,
"LocalSecondaryIndexes": lsis,
@@ -341,7 +342,7 @@ def _update_table(data):
if current_billing == "PAY_PER_REQUEST"
else {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5},
)
- gsi_def["IndexArn"] = f"arn:aws:dynamodb:{REGION}:{get_account_id()}:table/{name}/index/{gsi_def['IndexName']}"
+ gsi_def["IndexArn"] = f"arn:aws:dynamodb:{get_region()}:{get_account_id()}:table/{name}/index/{gsi_def['IndexName']}"
gsi_def["IndexSizeBytes"] = 0
gsi_def["ItemCount"] = 0
table["GlobalSecondaryIndexes"].append(gsi_def)
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index 04c6b2ca..7e388747 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -64,7 +64,7 @@ from urllib.parse import parse_qs
from xml.sax.saxutils import escape as _esc
from ministack.core.persistence import load_state, PERSIST_STATE
-from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid, get_region
logger = logging.getLogger("ec2")
@@ -187,9 +187,9 @@ def _init_defaults():
"MainRouteTableId": _DEFAULT_RTB_ID,
}
_default_subnets = [
- (_DEFAULT_SUBNET_ID, "172.31.0.0/20", f"{REGION}a"),
- (_DEFAULT_SUBNET_ID_B, "172.31.16.0/20", f"{REGION}b"),
- (_DEFAULT_SUBNET_ID_C, "172.31.32.0/20", f"{REGION}c"),
+ (_DEFAULT_SUBNET_ID, "172.31.0.0/20", f"{get_region()}a"),
+ (_DEFAULT_SUBNET_ID_B, "172.31.16.0/20", f"{get_region()}b"),
+ (_DEFAULT_SUBNET_ID_C, "172.31.32.0/20", f"{get_region()}c"),
]
for subnet_id, cidr, az in _default_subnets:
if subnet_id not in _subnets:
@@ -323,7 +323,7 @@ def _run_instances(p):
"RootDeviceName": "/dev/xvda",
"Hypervisor": "xen",
"Virtualization": "hvm",
- "Placement": {"AvailabilityZone": f"{REGION}a", "Tenancy": "default"},
+ "Placement": {"AvailabilityZone": f"{get_region()}a", "Tenancy": "default"},
"Monitoring": {"State": "disabled"},
"AmiLaunchIndex": 0,
"UserData": user_data,
@@ -973,7 +973,7 @@ def _create_default_vpc(p):
subnet_id = _new_subnet_id()
_subnets[subnet_id] = {
"SubnetId": subnet_id, "VpcId": vpc_id, "CidrBlock": sub_cidr,
- "AvailabilityZone": f"{REGION}{az_suffix}",
+ "AvailabilityZone": f"{get_region()}{az_suffix}",
"AvailableIpAddressCount": 4091, "State": "available",
"DefaultForAz": True, "MapPublicIpOnLaunch": True,
"OwnerId": get_account_id(),
@@ -1033,7 +1033,7 @@ def _matches_subnet_filters(subnet, filters):
def _create_subnet(p):
vpc_id = _p(p, "VpcId") or _DEFAULT_VPC_ID
cidr = _p(p, "CidrBlock") or "10.0.1.0/24"
- az = _p(p, "AvailabilityZone") or f"{REGION}a"
+ az = _p(p, "AvailabilityZone") or f"{get_region()}a"
subnet_id = _new_subnet_id()
_subnets[subnet_id] = {
"SubnetId": subnet_id,
@@ -1342,7 +1342,7 @@ def _create_network_interface(p):
sg_ids = [_DEFAULT_SG_ID]
eni_id = "eni-" + "".join(random.choices(string.hexdigits[:16], k=17))
private_ip = _random_ip("10.0")
- az = _subnets.get(subnet_id, {}).get("AvailabilityZone", f"{REGION}a")
+ az = _subnets.get(subnet_id, {}).get("AvailabilityZone", f"{get_region()}a")
_network_interfaces[eni_id] = {
"NetworkInterfaceId": eni_id,
"SubnetId": subnet_id,
@@ -1461,11 +1461,11 @@ def _describe_vpc_endpoints(p):
# ---------------------------------------------------------------------------
def _describe_availability_zones(p):
- azs = [f"{REGION}a", f"{REGION}b", f"{REGION}c"]
+ azs = [f"{get_region()}a", f"{get_region()}b", f"{get_region()}c"]
items = "".join(f"""<item>
<zoneName>{az}</zoneName>
<zoneState>available</zoneState>
- <regionName>{REGION}</regionName>
+ <regionName>{get_region()}</regionName>
<zoneId>{az}</zoneId>
</item>""" for az in azs)
return _xml(200, "DescribeAvailabilityZonesResponse",
@@ -1630,7 +1630,7 @@ def _new_snapshot_id():
def _create_volume(p):
vol_id = _new_volume_id()
- az = _p(p, "AvailabilityZone") or f"{REGION}a"
+ az = _p(p, "AvailabilityZone") or f"{get_region()}a"
size = int(_p(p, "Size") or "8")
vol_type = _p(p, "VolumeType") or "gp2"
snapshot_id = _p(p, "SnapshotId") or ""
@@ -2072,7 +2072,7 @@ def _vpc_xml(vpc):
def _subnet_fields_xml(subnet, tag="item"):
return f"""<{tag}>
<subnetId>{subnet['SubnetId']}</subnetId>
- <subnetArn>arn:aws:ec2:{REGION}:{get_account_id()}:subnet/{subnet['SubnetId']}</subnetArn>
+ <subnetArn>arn:aws:ec2:{get_region()}:{get_account_id()}:subnet/{subnet['SubnetId']}</subnetArn>
<state>{subnet['State']}</state>
<vpcId>{subnet['VpcId']}</vpcId>
<cidrBlock>{subnet['CidrBlock']}</cidrBlock>
@@ -2163,7 +2163,7 @@ def _eni_fields_xml(eni, tag="item"):
<networkInterfaceId>{eni['NetworkInterfaceId']}</networkInterfaceId>
<subnetId>{eni['SubnetId']}</subnetId>
<vpcId>{eni['VpcId']}</vpcId>
- <availabilityZone>{eni.get('AvailabilityZone', REGION + 'a')}</availabilityZone>
+ <availabilityZone>{eni.get('AvailabilityZone', get_region() + 'a')}</availabilityZone>
<description>{eni['Description']}</description>
<ownerId>{eni['OwnerId']}</ownerId>
<status>{eni['Status']}</status>
@@ -2705,13 +2705,13 @@ def _create_vpc_peering_connection(params):
vpc_id = _p(params, "VpcId")
peer_vpc_id = _p(params, "PeerVpcId")
peer_owner_id = _p(params, "PeerOwnerId") or get_account_id()
- peer_region = _p(params, "PeerRegion") or REGION
+ peer_region = _p(params, "PeerRegion") or get_region()
if not vpc_id or not peer_vpc_id:
return _error("MissingParameter", "VpcId and PeerVpcId are required", 400)
pcx_id = "pcx-" + "".join(random.choices(string.hexdigits[:16], k=17))
record = {
"VpcPeeringConnectionId": pcx_id,
- "RequesterVpcInfo": {"VpcId": vpc_id, "OwnerId": get_account_id(), "Region": REGION},
+ "RequesterVpcInfo": {"VpcId": vpc_id, "OwnerId": get_account_id(), "Region": get_region()},
"AccepterVpcInfo": {"VpcId": peer_vpc_id, "OwnerId": peer_owner_id, "Region": peer_region},
"Status": {"Code": "pending-acceptance", "Message": "Pending Acceptance by " + peer_owner_id},
"ExpirationTime": _now_ts(),
@@ -2720,7 +2720,7 @@ def _create_vpc_peering_connection(params):
_vpc_peering[pcx_id] = record
inner = f"""<vpcPeeringConnection>
<vpcPeeringConnectionId>{pcx_id}</vpcPeeringConnectionId>
- <requesterVpcInfo><vpcId>{vpc_id}</vpcId><ownerId>{get_account_id()}</ownerId><region>{REGION}</region></requesterVpcInfo>
+ <requesterVpcInfo><vpcId>{vpc_id}</vpcId><ownerId>{get_account_id()}</ownerId><region>{get_region()}</region></requesterVpcInfo>
<accepterVpcInfo><vpcId>{peer_vpc_id}</vpcId><ownerId>{peer_owner_id}</ownerId><region>{peer_region}</region></accepterVpcInfo>
<status><code>pending-acceptance</code></status>
<tagSet/>
@@ -2992,8 +2992,8 @@ def _describe_prefix_lists(p):
items = ""
# Built-in AWS service prefix lists
for tpl_svc, (pl_id, tpl_name) in _AWS_PREFIX_LISTS.items():
- svc = tpl_svc.replace("{region}", REGION)
- name = tpl_name.replace("{region}", REGION)
+ svc = tpl_svc.replace("{region}", get_region())
+ name = tpl_name.replace("{region}", get_region())
if filter_ids and pl_id not in filter_ids:
continue
if filters.get("prefix-list-name") and name not in filters["prefix-list-name"]:
@@ -3037,7 +3037,7 @@ def _create_managed_prefix_list(p):
"PrefixListId": pl_id, "PrefixListName": name, "State": "create-complete",
"AddressFamily": af, "MaxEntries": max_entries, "Version": 1,
"Entries": entries, "Tags": tags, "OwnerId": get_account_id(),
- "PrefixListArn": f"arn:aws:ec2:{REGION}:{get_account_id()}:prefix-list/{pl_id}",
+ "PrefixListArn": f"arn:aws:ec2:{get_region()}:{get_account_id()}:prefix-list/{pl_id}",
}
if tags:
_tags[pl_id] = tags
diff --git a/ministack/services/ecr.py b/ministack/services/ecr.py
index 06cf7616..bff39279 100644
--- a/ministack/services/ecr.py
+++ b/ministack/services/ecr.py
@@ -12,7 +12,7 @@ import os
import time
from ministack.core.persistence import load_state, PERSIST_STATE
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, get_region
logger = logging.getLogger("ecr")
@@ -49,7 +49,7 @@ if _restored:
def _repo_arn(name):
- return f"arn:aws:ecr:{REGION}:{get_account_id()}:repository/{name}"
+ return f"arn:aws:ecr:{get_region()}:{get_account_id()}:repository/{name}"
def _registry_id():
@@ -57,7 +57,7 @@ def _registry_id():
def _repo_uri(name):
- return f"{get_account_id()}.dkr.ecr.{REGION}.amazonaws.com/{name}"
+ return f"{get_account_id()}.dkr.ecr.{get_region()}.amazonaws.com/{name}"
def _image_digest(manifest):
@@ -345,7 +345,7 @@ def _get_authorization_token(data):
"authorizationData": [{
"authorizationToken": token,
"expiresAt": int(time.time()) + 43200,
- "proxyEndpoint": f"https://{get_account_id()}.dkr.ecr.{REGION}.amazonaws.com",
+ "proxyEndpoint": f"https://{get_account_id()}.dkr.ecr.{get_region()}.amazonaws.com",
}]
})
@@ -515,7 +515,7 @@ def _get_download_url_for_layer(data):
f"The repository with name '{name}' does not exist", 400)
layer_digest = data.get("layerDigest", "")
return json_response({
- "downloadUrl": f"https://{get_account_id()}.dkr.ecr.{REGION}.amazonaws.com/v2/{name}/blobs/{layer_digest}",
+ "downloadUrl": f"https://{get_account_id()}.dkr.ecr.{get_region()}.amazonaws.com/v2/{name}/blobs/{layer_digest}",
"layerDigest": layer_digest,
})
diff --git a/ministack/services/ecs.py b/ministack/services/ecs.py
index c1d91373..bffcda4b 100644
--- a/ministack/services/ecs.py
+++ b/ministack/services/ecs.py
@@ -37,6 +37,7 @@ from ministack.core.responses import (
json_response,
new_uuid,
now_iso,
+ get_region,
)
logger = logging.getLogger("ecs")
@@ -272,7 +273,7 @@ def _create_cluster(data):
if name in _clusters and _clusters[name]["status"] == "ACTIVE":
return json_response({"cluster": _clusters[name]})
- arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:cluster/{name}"
+ arn = f"arn:aws:ecs:{get_region()}:{get_account_id()}:cluster/{name}"
cluster = {
"clusterArn": arn,
"clusterName": name,
@@ -326,7 +327,7 @@ def _describe_clusters(data):
})
result.append(c)
else:
- arn = ref if ref.startswith("arn:") else f"arn:aws:ecs:{REGION}:{get_account_id()}:cluster/{ref}"
+ arn = ref if ref.startswith("arn:") else f"arn:aws:ecs:{get_region()}:{get_account_id()}:cluster/{ref}"
failures.append({"arn": arn, "reason": "MISSING"})
return json_response({"clusters": result, "failures": failures})
@@ -386,7 +387,7 @@ def _register_task_definition(data):
rev = _task_def_latest.get(family, 0) + 1
_task_def_latest[family] = rev
td_key = f"{family}:{rev}"
- arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:task-definition/{td_key}"
+ arn = f"arn:aws:ecs:{get_region()}:{get_account_id()}:task-definition/{td_key}"
compat = data.get("requiresCompatibilities", ["EC2"])
network_mode = data.get("networkMode", "awsvpc" if "FARGATE" in compat else "bridge")
@@ -583,7 +584,7 @@ def _create_service(data):
td_arn = _task_defs[td_key]["taskDefinitionArn"] if td_key in _task_defs else td_ref
desired = data.get("desiredCount", 1)
- arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:service/{cluster_name}/{name}"
+ arn = f"arn:aws:ecs:{get_region()}:{get_account_id()}:service/{cluster_name}/{name}"
now = _iso()
launch_type = data.get("launchType", "EC2")
@@ -684,7 +685,7 @@ def _describe_services(data):
result.append(_sanitize(s))
else:
arn = ref if ref.startswith("arn:") else \
- f"arn:aws:ecs:{REGION}:{get_account_id()}:service/{cluster_name}/{ref}"
+ f"arn:aws:ecs:{get_region()}:{get_account_id()}:service/{cluster_name}/{ref}"
failures.append({"arn": arn, "reason": "MISSING"})
return json_response({"services": result, "failures": failures})
@@ -785,7 +786,7 @@ def _build_task_containers(td, container_overrides):
env.update(env_override)
containers.append({
- "containerArn": f"arn:aws:ecs:{REGION}:{get_account_id()}:container/{new_uuid()}",
+ "containerArn": f"arn:aws:ecs:{get_region()}:{get_account_id()}:container/{new_uuid()}",
"taskArn": "",
"name": cdef["name"],
"image": cdef.get("image", ""),
@@ -827,7 +828,7 @@ def _run_task(data):
for _ in range(count):
task_id = new_uuid()
- task_arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:task/{cluster_name}/{task_id}"
+ task_arn = f"arn:aws:ecs:{get_region()}:{get_account_id()}:task/{cluster_name}/{task_id}"
now = _iso()
containers = _build_task_containers(td, container_overrides)
@@ -838,7 +839,7 @@ def _run_task(data):
"taskArn": task_arn,
"clusterArn": _clusters[cluster_name]["clusterArn"],
"taskDefinitionArn": td["taskDefinitionArn"],
- "containerInstanceArn": f"arn:aws:ecs:{REGION}:{get_account_id()}:container-instance/{cluster_name}/{new_uuid()}",
+ "containerInstanceArn": f"arn:aws:ecs:{get_region()}:{get_account_id()}:container-instance/{cluster_name}/{new_uuid()}",
"overrides": data.get("overrides", {"containerOverrides": [], "inferenceAcceleratorOverrides": []}),
"lastStatus": "RUNNING",
"desiredStatus": "RUNNING",
@@ -862,7 +863,7 @@ def _run_task(data):
"version": 1,
"containers": containers,
"attachments": [],
- "availabilityZone": f"{REGION}a",
+ "availabilityZone": f"{get_region()}a",
"enableExecuteCommand": enable_exec,
"tags": req_tags,
"healthStatus": "UNKNOWN",
@@ -982,7 +983,7 @@ def _describe_tasks(data):
result.append(t)
else:
arn = ref if ref.startswith("arn:") else \
- f"arn:aws:ecs:{REGION}:{get_account_id()}:task/{cluster_name}/{ref}"
+ f"arn:aws:ecs:{get_region()}:{get_account_id()}:task/{cluster_name}/{ref}"
failures.append({"arn": arn, "reason": "MISSING"})
return json_response({"tasks": result, "failures": failures})
@@ -1036,7 +1037,7 @@ def _maybe_mark_stopped(task):
def _list_tasks(data):
cluster_name = _resolve_cluster_name(data.get("cluster", "default"))
- cluster_arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:cluster/{cluster_name}"
+ cluster_arn = f"arn:aws:ecs:{get_region()}:{get_account_id()}:cluster/{cluster_name}"
status_filter = data.get("desiredStatus", "RUNNING")
family = data.get("family", "")
service_name = data.get("serviceName", "")
@@ -1143,7 +1144,7 @@ def _execute_command(data):
"interactive": data.get("interactive", True),
"session": {
"sessionId": new_uuid(),
- "streamUrl": f"wss://ssmmessages.{REGION}.amazonaws.com/v1/data-channel/{new_uuid()}",
+ "streamUrl": f"wss://ssmmessages.{get_region()}.amazonaws.com/v1/data-channel/{new_uuid()}",
"tokenValue": new_uuid(),
},
})
@@ -1197,7 +1198,7 @@ def _describe_capacity_providers(data):
for p in defaults:
if not names or p["name"] in names:
cp = {
- "capacityProviderArn": f"arn:aws:ecs:{REGION}:{get_account_id()}:capacity-provider/{p['name']}",
+ "capacityProviderArn": f"arn:aws:ecs:{get_region()}:{get_account_id()}:capacity-provider/{p['name']}",
"name": p["name"],
"status": p["status"],
"autoScalingGroupProvider": p["autoScalingGroupProvider"],
@@ -1225,7 +1226,7 @@ def _create_capacity_provider(data):
return error_response_json("InvalidParameterException",
f"Capacity provider {name} already exists.", 400)
- arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:capacity-provider/{name}"
+ arn = f"arn:aws:ecs:{get_region()}:{get_account_id()}:capacity-provider/{name}"
asg_provider = data.get("autoScalingGroupProvider", {})
cp = {
@@ -1350,7 +1351,7 @@ def _resolve_task(ref, cluster_name="default"):
task = _tasks.get(ref)
if task:
return task
- cluster_arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:cluster/{cluster_name}"
+ cluster_arn = f"arn:aws:ecs:{get_region()}:{get_account_id()}:cluster/{cluster_name}"
for arn, t in _tasks.items():
if t.get("clusterArn") != cluster_arn:
continue
diff --git a/ministack/services/efs.py b/ministack/services/efs.py
index b717b580..4c9f752f 100644
--- a/ministack/services/efs.py
+++ b/ministack/services/efs.py
@@ -25,7 +25,7 @@ import string
import time
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import AccountScopedDict, get_account_id
+from ministack.core.responses import AccountScopedDict, get_account_id, get_region
logger = logging.getLogger("efs")
@@ -74,7 +74,7 @@ def _create_file_system(body):
return _json(200, _fs_response(fs))
fs_id = _fs_id()
- arn = f"arn:aws:elasticfilesystem:{REGION}:{get_account_id()}:file-system/{fs_id}"
+ arn = f"arn:aws:elasticfilesystem:{get_region()}:{get_account_id()}:file-system/{fs_id}"
now = _now_iso()
record = {
@@ -161,7 +161,7 @@ def _create_mount_target(body):
return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")
mt_id = _mt_id()
- arn = f"arn:aws:elasticfilesystem:{REGION}:{get_account_id()}:file-system/{fs_id}/mount-target/{mt_id}"
+ arn = f"arn:aws:elasticfilesystem:{get_region()}:{get_account_id()}:file-system/{fs_id}/mount-target/{mt_id}"
now = _now_iso()
record = {
@@ -169,7 +169,7 @@ def _create_mount_target(body):
"FileSystemId": fs_id,
"SubnetId": subnet_id,
"AvailabilityZoneId": f"use1-az{random.randint(1,3)}",
- "AvailabilityZoneName": f"{REGION}a",
+ "AvailabilityZoneName": f"{get_region()}a",
"VpcId": "vpc-00000001",
"LifeCycleState": "available",
"IpAddress": ip_address,
@@ -244,7 +244,7 @@ def _create_access_point(body):
return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")
ap_id = _ap_id()
- arn = f"arn:aws:elasticfilesystem:{REGION}:{get_account_id()}:access-point/{ap_id}"
+ arn = f"arn:aws:elasticfilesystem:{get_region()}:{get_account_id()}:access-point/{ap_id}"
now = _now_iso()
tags = body.get("Tags", [])
diff --git a/ministack/services/eks.py b/ministack/services/eks.py
index d424bab9..a3779438 100644
--- a/ministack/services/eks.py
+++ b/ministack/services/eks.py
@@ -21,7 +21,7 @@ import re
import threading
import time
-from ministack.core.responses import AccountScopedDict, get_account_id, json_response, error_response_json, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, json_response, error_response_json, new_uuid, get_region
logger = logging.getLogger("eks")
@@ -100,11 +100,11 @@ def _next_port():
def _cluster_arn(name):
- return f"arn:aws:eks:{REGION}:{get_account_id()}:cluster/{name}"
+ return f"arn:aws:eks:{get_region()}:{get_account_id()}:cluster/{name}"
def _nodegroup_arn(cluster_name, ng_name):
- return f"arn:aws:eks:{REGION}:{get_account_id()}:nodegroup/{cluster_name}/{ng_name}/{new_uuid()[:8]}"
+ return f"arn:aws:eks:{get_region()}:{get_account_id()}:nodegroup/{cluster_name}/{ng_name}/{new_uuid()[:8]}"
def _now():
@@ -232,7 +232,7 @@ def _create_cluster(body):
},
"logging": body.get("logging", {"clusterLogging": []}),
"identity": {
- "oidc": {"issuer": f"https://oidc.eks.{REGION}.amazonaws.com/id/{new_uuid()[:32].replace('-', '').upper()}"}
+ "oidc": {"issuer": f"https://oidc.eks.{get_region()}.amazonaws.com/id/{new_uuid()[:32].replace('-', '').upper()}"}
},
"status": "CREATING",
"certificateAuthority": {"data": ""},
diff --git a/ministack/services/elasticache.py b/ministack/services/elasticache.py
index 27a9cdf3..c4a13a0d 100644
--- a/ministack/services/elasticache.py
+++ b/ministack/services/elasticache.py
@@ -27,7 +27,7 @@ import time
from urllib.parse import parse_qs
from ministack.core.persistence import load_state
-from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid, get_region
logger = logging.getLogger("elasticache")
@@ -122,23 +122,23 @@ def _get_docker():
def _arn_cluster(cluster_id):
- return f"arn:aws:elasticache:{REGION}:{get_account_id()}:cluster:{cluster_id}"
+ return f"arn:aws:elasticache:{get_region()}:{get_account_id()}:cluster:{cluster_id}"
def _arn_replication_group(rg_id):
- return f"arn:aws:elasticache:{REGION}:{get_account_id()}:replicationgroup:{rg_id}"
+ return f"arn:aws:elasticache:{get_region()}:{get_account_id()}:replicationgroup:{rg_id}"
def _arn_subnet_group(name):
- return f"arn:aws:elasticache:{REGION}:{get_account_id()}:subnetgroup:{name}"
+ return f"arn:aws:elasticache:{get_region()}:{get_account_id()}:subnetgroup:{name}"
def _arn_param_group(name):
- return f"arn:aws:elasticache:{REGION}:{get_account_id()}:parametergroup:{name}"
+ return f"arn:aws:elasticache:{get_region()}:{get_account_id()}:parametergroup:{name}"
def _arn_snapshot(name):
- return f"arn:aws:elasticache:{REGION}:{get_account_id()}:snapshot:{name}"
+ return f"arn:aws:elasticache:{get_region()}:{get_account_id()}:snapshot:{name}"
def _record_event(source_id, source_type, message):
@@ -266,7 +266,7 @@ def _create_cache_cluster(p):
"CacheNodeType": node_type,
"NumCacheNodes": num_nodes,
"CacheClusterCreateTime": time.time(),
- "PreferredAvailabilityZone": f"{REGION}a",
+ "PreferredAvailabilityZone": f"{get_region()}a",
"CacheParameterGroup": {
"CacheParameterGroupName": param_group_name,
"ParameterApplyStatus": "in-sync",
@@ -412,7 +412,7 @@ def _create_replication_group(p):
"CacheClusterId": f"{rg_id}-{ng_id}-{r + 1:03d}",
"CacheNodeId": "0001",
"CurrentRole": role,
- "PreferredAvailabilityZone": f"{REGION}{'abcdef'[r % 6]}",
+ "PreferredAvailabilityZone": f"{get_region()}{'abcdef'[r % 6]}",
"ReadEndpoint": {"Address": endpoint_host, "Port": endpoint_port},
})
node_groups.append({
@@ -528,7 +528,7 @@ def _increase_replica_count(p):
"CacheClusterId": f"{rg_id}-{ng['NodeGroupId']}-{current:03d}",
"CacheNodeId": "0001",
"CurrentRole": "replica",
- "PreferredAvailabilityZone": f"{REGION}a",
+ "PreferredAvailabilityZone": f"{get_region()}a",
"ReadEndpoint": {"Address": endpoint_host, "Port": endpoint_port},
})
rg["_replicas_per_node_group"] = new_count
@@ -572,7 +572,7 @@ def _create_subnet_group(p):
while _p(p, f"SubnetIds.member.{idx}"):
subnets.append({
"SubnetIdentifier": _p(p, f"SubnetIds.member.{idx}"),
- "SubnetAvailabilityZone": {"Name": f"{REGION}{'abcdef'[(idx - 1) % 6]}"},
+ "SubnetAvailabilityZone": {"Name": f"{get_region()}{'abcdef'[(idx - 1) % 6]}"},
})
idx += 1
@@ -644,7 +644,7 @@ def _modify_subnet_group(p):
while _p(p, f"SubnetIds.member.{idx}"):
subnets.append({
"SubnetIdentifier": _p(p, f"SubnetIds.member.{idx}"),
- "SubnetAvailabilityZone": {"Name": f"{REGION}{'abcdef'[(idx - 1) % 6]}"},
+ "SubnetAvailabilityZone": {"Name": f"{get_region()}{'abcdef'[(idx - 1) % 6]}"},
})
idx += 1
if subnets:
@@ -992,11 +992,11 @@ def _describe_events(p):
# ---- Users (Redis ACL) ----
def _arn_user(user_id):
- return f"arn:aws:elasticache:{REGION}:{get_account_id()}:user:{user_id}"
+ return f"arn:aws:elasticache:{get_region()}:{get_account_id()}:user:{user_id}"
def _arn_user_group(group_id):
- return f"arn:aws:elasticache:{REGION}:{get_account_id()}:usergroup:{group_id}"
+ return f"arn:aws:elasticache:{get_region()}:{get_account_id()}:usergroup:{group_id}"
def _create_user(p):
diff --git a/ministack/services/emr.py b/ministack/services/emr.py
index 4db3a837..a7454e91 100644
--- a/ministack/services/emr.py
+++ b/ministack/services/emr.py
@@ -23,7 +23,7 @@ import string
import time
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, get_region
logger = logging.getLogger("emr")
@@ -92,7 +92,7 @@ def _run_job_flow(data):
return error_response_json("ValidationException", "Name is required", 400)
cluster_id = _cluster_id()
- arn = f"arn:aws:elasticmapreduce:{REGION}:{get_account_id()}:cluster/{cluster_id}"
+ arn = f"arn:aws:elasticmapreduce:{get_region()}:{get_account_id()}:cluster/{cluster_id}"
instances = data.get("Instances", {})
keep_alive = instances.get("KeepJobFlowAliveWhenNoSteps", False)
tags = data.get("Tags", [])
@@ -181,7 +181,7 @@ def _run_job_flow(data):
"Ec2InstanceAttributes": {
"Ec2KeyName": instances.get("Ec2KeyName", ""),
"Ec2SubnetId": instances.get("Ec2SubnetId", ""),
- "Ec2AvailabilityZone": f"{REGION}a",
+ "Ec2AvailabilityZone": f"{get_region()}a",
"IamInstanceProfile": job_flow_role,
"EmrManagedMasterSecurityGroup": instances.get("EmrManagedMasterSecurityGroup", ""),
"EmrManagedSlaveSecurityGroup": instances.get("EmrManagedSlaveSecurityGroup", ""),
diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.py
index 99b4e1f6..b0e242ec 100644
--- a/ministack/services/eventbridge.py
+++ b/ministack/services/eventbridge.py
@@ -31,7 +31,7 @@ import threading
import time
from datetime import datetime
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, get_region
logger = logging.getLogger("events")
@@ -84,7 +84,7 @@ def _ensure_default_bus():
if "default" not in _event_buses:
_event_buses["default"] = {
"Name": "default",
- "Arn": f"arn:aws:events:{REGION}:{get_account_id()}:event-bus/default",
+ "Arn": f"arn:aws:events:{get_region()}:{get_account_id()}:event-bus/default",
"CreationTime": _now_ts(),
"LastModifiedTime": _now_ts(),
}
@@ -235,7 +235,7 @@ def _create_event_bus(data):
return error_response_json("ValidationException", "Name is required", 400)
if name in _event_buses:
return error_response_json("ResourceAlreadyExistsException", f"Event bus {name} already exists", 400)
- arn = f"arn:aws:events:{REGION}:{get_account_id()}:event-bus/{name}"
+ arn = f"arn:aws:events:{get_region()}:{get_account_id()}:event-bus/{name}"
description = data.get("Description", "")
_event_buses[name] = {
"Name": name,
@@ -333,8 +333,8 @@ def _update_event_bus(data):
def _rule_arn(rule_name: str, bus_name: str) -> str:
if bus_name == "default":
- return f"arn:aws:events:{REGION}:{get_account_id()}:rule/{rule_name}"
- return f"arn:aws:events:{REGION}:{get_account_id()}:rule/{bus_name}/{rule_name}"
+ return f"arn:aws:events:{get_region()}:{get_account_id()}:rule/{rule_name}"
+ return f"arn:aws:events:{get_region()}:{get_account_id()}:rule/{bus_name}/{rule_name}"
def _rule_key(rule_name: str, bus_name: str) -> str:
@@ -563,7 +563,7 @@ def _event_from_test_payload(event_obj: dict) -> dict:
"DetailType": event_obj.get("detail-type", event_obj.get("DetailType", "")),
"Detail": detail,
"Account": event_obj.get("account", event_obj.get("Account", get_account_id())),
- "Region": event_obj.get("region", event_obj.get("Region", REGION)),
+ "Region": event_obj.get("region", event_obj.get("Region", get_region())),
"Resources": event_obj.get("resources", event_obj.get("Resources", [])),
}
@@ -614,7 +614,7 @@ def _put_events(data):
"Time": event_time,
"Resources": entry.get("Resources", []),
"Account": get_account_id(),
- "Region": REGION,
+ "Region": get_region(),
}
_events_log_list().append(event_record)
results.append({"EventId": event_id})
@@ -672,7 +672,7 @@ def _matches_pattern(pattern_str, event):
return False
if "region" in pattern:
- if not _matches_field(event.get("Region", REGION), pattern["region"]):
+ if not _matches_field(event.get("Region", get_region()), pattern["region"]):
return False
if "resources" in pattern:
@@ -772,7 +772,7 @@ def _invoke_target(target, event, rule):
"source": event["Source"],
"account": get_account_id(),
"time": event["Time"],
- "region": REGION,
+ "region": get_region(),
"resources": event.get("Resources", []),
"detail-type": event["DetailType"],
"detail": json.loads(event["Detail"]) if isinstance(event["Detail"], str) else event["Detail"],
@@ -822,7 +822,7 @@ def _apply_input_transformer(transformer, event):
"detail-type": event.get("DetailType", ""),
"detail": full,
"account": get_account_id(),
- "region": REGION,
+ "region": get_region(),
"time": event.get("Time", ""),
"id": event.get("EventId", ""),
"resources": event.get("Resources", []),
@@ -964,7 +964,7 @@ def _create_archive(data):
return error_response_json("ResourceAlreadyExistsException", f"Archive {name} already exists", 400)
source_arn = data.get("EventSourceArn", "")
- arn = f"arn:aws:events:{REGION}:{get_account_id()}:archive/{name}"
+ arn = f"arn:aws:events:{get_region()}:{get_account_id()}:archive/{name}"
_archives[name] = {
"ArchiveName": name,
"ArchiveArn": arn,
@@ -1066,7 +1066,7 @@ def _start_replay(data):
"Destination.Arn is required",
400,
)
- arn = f"arn:aws:events:{REGION}:{get_account_id()}:replay/{name}"
+ arn = f"arn:aws:events:{get_region()}:{get_account_id()}:replay/{name}"
now = _now_ts()
_replays[name] = {
"ReplayName": name,
@@ -1146,7 +1146,7 @@ def _create_endpoint(data):
if name in _endpoints:
return error_response_json("ResourceAlreadyExistsException",
f"Endpoint {name} already exists", 400)
- arn = f"arn:aws:events:{REGION}:{get_account_id()}:endpoint/{name}"
+ arn = f"arn:aws:events:{get_region()}:{get_account_id()}:endpoint/{name}"
now = _now_ts()
_endpoints[name] = {
"Name": name,
@@ -1156,7 +1156,7 @@ def _create_endpoint(data):
"EventBuses": data.get("EventBuses", []),
"RoleArn": data.get("RoleArn", ""),
"Arn": arn,
- "EndpointUrl": f"https://{name}.global-events.{REGION}.amazonaws.com",
+ "EndpointUrl": f"https://{name}.global-events.{get_region()}.amazonaws.com",
"State": "ACTIVE",
"CreationTime": now,
"LastModifiedTime": now,
@@ -1213,7 +1213,7 @@ def _list_endpoints(data):
ep = _endpoints[n]
if prefix and not n.startswith(prefix):
continue
- if home and REGION != home:
+ if home and get_region() != home:
continue
results.append({
"Name": ep["Name"],
@@ -1264,7 +1264,7 @@ def _describe_event_source(data):
return json_response({
"Name": name,
"State": "ENABLED",
- "Arn": f"arn:aws:events:{REGION}::event-source/{name}" if name else "",
+ "Arn": f"arn:aws:events:{get_region()}::event-source/{name}" if name else "",
})
@@ -1281,7 +1281,7 @@ def _create_partner_event_source(data):
if pk in _partner_event_sources:
return error_response_json("ResourceAlreadyExistsException",
"Partner event source already exists", 400)
- arn = f"arn:aws:events:{REGION}:{account}:event-source/{name}"
+ arn = f"arn:aws:events:{get_region()}:{account}:event-source/{name}"
_partner_event_sources[pk] = {
"Name": name,
"Account": account,
@@ -1364,7 +1364,7 @@ def _put_permission(data):
"Effect": "Allow",
"Principal": data.get("Principal", "*"),
"Action": data.get("Action", "events:PutEvents"),
- "Resource": f"arn:aws:events:{REGION}:{get_account_id()}:event-bus/{bus_name}",
+ "Resource": f"arn:aws:events:{get_region()}:{get_account_id()}:event-bus/{bus_name}",
}
condition = data.get("Condition")
if condition:
@@ -1404,7 +1404,7 @@ def _create_connection(data):
return error_response_json("ResourceAlreadyExistsException",
f"Connection {name} already exists", 400)
- arn = f"arn:aws:events:{REGION}:{get_account_id()}:connection/{name}"
+ arn = f"arn:aws:events:{get_region()}:{get_account_id()}:connection/{name}"
now = _now_ts()
_connections[name] = {
"Name": name,
@@ -1520,7 +1520,7 @@ def _create_api_destination(data):
return error_response_json("ResourceAlreadyExistsException",
f"ApiDestination {name} already exists", 400)
- arn = f"arn:aws:events:{REGION}:{get_account_id()}:api-destination/{name}"
+ arn = f"arn:aws:events:{get_region()}:{get_account_id()}:api-destination/{name}"
now = _now_ts()
_api_destinations[name] = {
"Name": name,
diff --git a/ministack/services/firehose.py b/ministack/services/firehose.py
index bbcdb5d7..1777ecc7 100644
--- a/ministack/services/firehose.py
+++ b/ministack/services/firehose.py
@@ -31,6 +31,7 @@ from ministack.core.responses import (
json_response,
new_uuid,
now_epoch,
+ get_region,
)
logger = logging.getLogger("firehose")
@@ -69,7 +70,7 @@ if _restored:
# ─── helpers ─────────────────────────────────────────────────────────────────
def _stream_arn(name: str) -> str:
- return f"arn:aws:firehose:{REGION}:{get_account_id()}:deliverystream/{name}"
+ return f"arn:aws:firehose:{get_region()}:{get_account_id()}:deliverystream/{name}"
def _next_dest_id() -> str:
diff --git a/ministack/services/glue.py b/ministack/services/glue.py
index ef7e2424..110258e9 100644
--- a/ministack/services/glue.py
+++ b/ministack/services/glue.py
@@ -19,7 +19,7 @@ import threading
import time
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, get_region
logger = logging.getLogger("glue")
@@ -76,7 +76,7 @@ if _restored:
def _arn(resource_type, name):
- return f"arn:aws:glue:{REGION}:{get_account_id()}:{resource_type}/{name}"
+ return f"arn:aws:glue:{get_region()}:{get_account_id()}:{resource_type}/{name}"
async def handle_request(method, path, headers, body, query_params):
diff --git a/ministack/services/iam.py b/ministack/services/iam.py
index 1d96e0af..f5d10d00 100644
--- a/ministack/services/iam.py
+++ b/ministack/services/iam.py
@@ -35,7 +35,7 @@ import time
from urllib.parse import parse_qs
from urllib.parse import quote as _url_quote
-from ministack.core.responses import AccountScopedDict, get_account_id, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, json_response, new_uuid, get_region
logger = logging.getLogger("iam")
diff --git a/ministack/services/kinesis.py b/ministack/services/kinesis.py
index 3759b9e5..1b9aac44 100644
--- a/ministack/services/kinesis.py
+++ b/ministack/services/kinesis.py
@@ -21,7 +21,7 @@ import logging
import threading
import time
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, get_region
logger = logging.getLogger("kinesis")
@@ -228,7 +228,7 @@ def _create_stream(data):
if shard_count < 1:
return error_response_json("ValidationException", "ShardCount must be at least 1", 400)
- arn = f"arn:aws:kinesis:{REGION}:{get_account_id()}:stream/{name}"
+ arn = f"arn:aws:kinesis:{get_region()}:{get_account_id()}:stream/{name}"
mode = data.get("StreamModeDetails", {}).get("StreamMode", "PROVISIONED")
_streams[name] = {
"StreamName": name,
diff --git a/ministack/services/kms.py b/ministack/services/kms.py
index 82e2c01b..974ebf69 100644
--- a/ministack/services/kms.py
+++ b/ministack/services/kms.py
@@ -13,7 +13,7 @@ import logging
import os
import time
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, get_region
logger = logging.getLogger("kms")
@@ -107,7 +107,7 @@ if _restored:
def _arn(key_id):
- return f"arn:aws:kms:{REGION}:{get_account_id()}:key/{key_id}"
+ return f"arn:aws:kms:{get_region()}:{get_account_id()}:key/{key_id}"
def _key_metadata(rec):
@@ -749,7 +749,7 @@ def _list_aliases(data):
continue
items.append({
"AliasName": alias_name,
- "AliasArn": f"arn:aws:kms:{REGION}:{get_account_id()}:{alias_name}",
+ "AliasArn": f"arn:aws:kms:{get_region()}:{get_account_id()}:{alias_name}",
"TargetKeyId": target_id,
})
return json_response({"Aliases": items, "Truncated": False})
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index cc6b21b5..df267b8f 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -44,7 +44,7 @@ from typing import Any
from urllib.parse import unquote
from ministack.core.persistence import load_state, PERSIST_STATE
-from ministack.core.responses import AccountScopedDict, get_account_id, _request_account_id, error_response_json, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, _request_account_id, error_response_json, json_response, new_uuid, get_region
from ministack.core.lambda_runtime import get_or_create_worker, invalidate_worker
logger = logging.getLogger("lambda")
@@ -372,11 +372,11 @@ def _resolve_name_and_qualifier(name_or_arn: str) -> tuple[str, str | None]:
def _func_arn(name: str) -> str:
- return f"arn:aws:lambda:{REGION}:{get_account_id()}:function:{name}"
+ return f"arn:aws:lambda:{get_region()}:{get_account_id()}:function:{name}"
def _layer_arn(name: str) -> str:
- return f"arn:aws:lambda:{REGION}:{get_account_id()}:layer:{name}"
+ return f"arn:aws:lambda:{get_region()}:{get_account_id()}:layer:{name}"
def _now_iso() -> str:
@@ -1998,8 +1998,8 @@ def _spawn_lambda_container(config: dict, code_zip: bytes | None):
# Shared environment
container_env: dict[str, str] = {
- "AWS_DEFAULT_REGION": REGION,
- "AWS_REGION": REGION,
+ "AWS_DEFAULT_REGION": get_region(),
+ "AWS_REGION": get_region(),
"AWS_ACCESS_KEY_ID": os.environ.get("AWS_ACCESS_KEY_ID", "test"),
"AWS_SECRET_ACCESS_KEY": os.environ.get("AWS_SECRET_ACCESS_KEY", "test"),
"AWS_SESSION_TOKEN": os.environ.get("AWS_SESSION_TOKEN", ""),
@@ -2543,8 +2543,8 @@ def _execute_function_provided(func: dict, event: dict) -> dict:
proc_env = dict(os.environ)
proc_env.update({
"AWS_LAMBDA_RUNTIME_API": f"127.0.0.1:{port}",
- "AWS_DEFAULT_REGION": REGION,
- "AWS_REGION": REGION,
+ "AWS_DEFAULT_REGION": get_region(),
+ "AWS_REGION": get_region(),
"AWS_ACCESS_KEY_ID": os.environ.get("AWS_ACCESS_KEY_ID", "test"),
"AWS_SECRET_ACCESS_KEY": os.environ.get("AWS_SECRET_ACCESS_KEY", "test"),
"AWS_LAMBDA_FUNCTION_NAME": config.get("FunctionName", "unknown"),
@@ -2675,8 +2675,8 @@ def _execute_function_local(func: dict, event: dict) -> dict:
env = dict(os.environ)
env.update(
{
- "AWS_DEFAULT_REGION": REGION,
- "AWS_REGION": REGION,
+ "AWS_DEFAULT_REGION": get_region(),
+ "AWS_REGION": get_region(),
"AWS_ACCESS_KEY_ID": os.environ.get("AWS_ACCESS_KEY_ID", "test"),
"AWS_SECRET_ACCESS_KEY": os.environ.get("AWS_SECRET_ACCESS_KEY", "test"),
"AWS_SESSION_TOKEN": os.environ.get("AWS_SESSION_TOKEN", ""),
@@ -3772,7 +3772,7 @@ def _poll_sqs():
"md5OfBody": msg.get("md5_body") or msg.get("md5") or "",
"eventSource": "aws:sqs",
"eventSourceARN": source_arn,
- "awsRegion": REGION,
+ "awsRegion": get_region(),
})
# Apply FilterCriteria before invoking — AWS filters records out
@@ -3906,7 +3906,7 @@ def _poll_kinesis():
"eventID": f"{shard_id}:{r['SequenceNumber']}",
"eventName": "aws:kinesis:record",
"invokeIdentityArn": f"arn:aws:iam::{get_account_id()}:role/lambda-role",
- "awsRegion": REGION,
+ "awsRegion": get_region(),
"eventSourceARN": source_arn,
})
@@ -4033,7 +4033,7 @@ def _create_function_url_config(func_name: str, data: dict, qualifier: str | Non
"ResourceConflictException", f"Function URL config already exists for {func_name}", 409
)
cfg = {
- "FunctionUrl": f"https://{new_uuid()}.lambda-url.{REGION}.on.aws/",
+ "FunctionUrl": f"https://{new_uuid()}.lambda-url.{get_region()}.on.aws/",
"FunctionArn": _func_arn(func_name),
"AuthType": data.get("AuthType", "NONE"),
"InvokeMode": data.get("InvokeMode", "BUFFERED"),
diff --git a/ministack/services/pipes.py b/ministack/services/pipes.py
index cee4c063..c9c1879c 100644
--- a/ministack/services/pipes.py
+++ b/ministack/services/pipes.py
@@ -1,173 +1,173 @@
-"""
-Minimal EventBridge Pipes runtime for local CloudFormation use.
-
-Scope intentionally limited to:
-- Source: DynamoDB Streams
-- Target: SNS
-- Lifecycle: create/delete (via CloudFormation handlers)
-"""
-
-import copy
-import json
-import logging
-import os
-import threading
-import time
-
-from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid
-
-logger = logging.getLogger("pipes")
-
-REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
-
-_pipes = AccountScopedDict() # pipe_name -> pipe record
-_positions = AccountScopedDict() # pipe_arn -> next stream record index
-_poller_started = False
-_poller_lock = threading.Lock()
-
-
-def get_state():
- return {
- "pipes": copy.deepcopy(_pipes),
- "positions": copy.deepcopy(_positions),
- }
-
-
-def reset():
- _pipes.clear()
- _positions.clear()
-
-
-def register_pipe(
- *,
- name: str,
- source: str,
- target: str,
- role_arn: str = "",
- desired_state: str = "RUNNING",
- starting_position: str = "LATEST",
- tags: dict | None = None,
-):
- arn = f"arn:aws:pipes:{REGION}:{get_account_id()}:pipe/{name}"
- state = "STOPPED" if str(desired_state).upper() == "STOPPED" else "RUNNING"
- start = str(starting_position or "LATEST").upper()
- if start not in ("LATEST", "TRIM_HORIZON"):
- start = "LATEST"
-
- _pipes[name] = {
- "Name": name,
- "Arn": arn,
- "RoleArn": role_arn,
- "Source": source,
- "Target": target,
- "DesiredState": state,
- "CurrentState": state,
- "StartingPosition": start,
- "Tags": tags or {},
- "CreationTime": int(time.time()),
- }
- _positions[arn] = _initial_position(_pipes[name])
-
- _ensure_poller()
- return _pipes[name]
-
-
-def delete_pipe(name: str):
- pipe = _pipes.pop(name, None)
- if pipe:
- _positions.pop(pipe["Arn"], None)
-
-
-def _ensure_poller():
- global _poller_started
- with _poller_lock:
- if not _poller_started:
- t = threading.Thread(target=_poll_loop, daemon=True)
- t.start()
- _poller_started = True
-
-
-def _poll_loop():
- while True:
- try:
- _poll_once()
- except Exception as e:
- logger.error("Pipes poller error: %s", e)
- time.sleep(1 if _pipes else 5)
-
-
-def _poll_once():
- from ministack.services import dynamodb as _ddb
-
- stream_records = getattr(_ddb, "_stream_records", None)
- if stream_records is None:
- return
-
- for pipe in list(_pipes.values()):
- if pipe.get("CurrentState") != "RUNNING":
- continue
-
- source_arn = pipe.get("Source", "")
- target_arn = pipe.get("Target", "")
- if ":dynamodb:" not in source_arn or "/stream/" not in source_arn:
- continue
- if ":sns:" not in target_arn:
- continue
-
- table_name = _table_name_from_stream_arn(source_arn)
- if not table_name:
- continue
-
- records = stream_records.get(table_name, [])
- pos = int(_positions.get(pipe["Arn"], 0))
- if pos < 0:
- pos = 0
- if pos >= len(records):
- continue
-
- batch = records[pos:]
- for rec in batch:
- _publish_record_to_sns(target_arn, pipe, rec)
- _positions[pipe["Arn"]] = pos + len(batch)
-
-
-def _publish_record_to_sns(topic_arn: str, pipe: dict, record: dict):
- from ministack.services import sns as _sns
-
- topic = _sns._topics.get(topic_arn)
- if not topic:
- logger.warning("Pipes %s: SNS topic not found %s", pipe.get("Name"), topic_arn)
- return
-
- msg_id = new_uuid()
- message = json.dumps(record)
- subject = f"Pipes {pipe.get('Name', '')}"
-
- topic["messages"].append({
- "id": msg_id,
- "message": message,
- "subject": subject,
- "message_structure": "",
- "message_attributes": {},
- "timestamp": int(time.time()),
- })
- _sns._fanout(topic_arn, msg_id, message, subject, "", {})
-
-
-def _table_name_from_stream_arn(stream_arn: str) -> str:
- if "/stream/" not in stream_arn:
- return ""
- return stream_arn.split("/stream/", 1)[0].rsplit("/", 1)[-1]
-
-
-def _initial_position(pipe: dict) -> int:
- from ministack.services import dynamodb as _ddb
-
- table_name = _table_name_from_stream_arn(pipe.get("Source", ""))
- if not table_name:
- return 0
-
- records = getattr(_ddb, "_stream_records", {}).get(table_name, [])
- if pipe.get("StartingPosition") == "TRIM_HORIZON":
- return 0
- return len(records)
+"""
+Minimal EventBridge Pipes runtime for local CloudFormation use.
+
+Scope intentionally limited to:
+- Source: DynamoDB Streams
+- Target: SNS
+- Lifecycle: create/delete (via CloudFormation handlers)
+"""
+
+import copy
+import json
+import logging
+import os
+import threading
+import time
+
+from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid, get_region
+
+logger = logging.getLogger("pipes")
+
+REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+
+_pipes = AccountScopedDict() # pipe_name -> pipe record
+_positions = AccountScopedDict() # pipe_arn -> next stream record index
+_poller_started = False
+_poller_lock = threading.Lock()
+
+
+def get_state():
+ return {
+ "pipes": copy.deepcopy(_pipes),
+ "positions": copy.deepcopy(_positions),
+ }
+
+
+def reset():
+ _pipes.clear()
+ _positions.clear()
+
+
+def register_pipe(
+ *,
+ name: str,
+ source: str,
+ target: str,
+ role_arn: str = "",
+ desired_state: str = "RUNNING",
+ starting_position: str = "LATEST",
+ tags: dict | None = None,
+):
+ arn = f"arn:aws:pipes:{get_region()}:{get_account_id()}:pipe/{name}"
+ state = "STOPPED" if str(desired_state).upper() == "STOPPED" else "RUNNING"
+ start = str(starting_position or "LATEST").upper()
+ if start not in ("LATEST", "TRIM_HORIZON"):
+ start = "LATEST"
+
+ _pipes[name] = {
+ "Name": name,
+ "Arn": arn,
+ "RoleArn": role_arn,
+ "Source": source,
+ "Target": target,
+ "DesiredState": state,
+ "CurrentState": state,
+ "StartingPosition": start,
+ "Tags": tags or {},
+ "CreationTime": int(time.time()),
+ }
+ _positions[arn] = _initial_position(_pipes[name])
+
+ _ensure_poller()
+ return _pipes[name]
+
+
+def delete_pipe(name: str):
+ pipe = _pipes.pop(name, None)
+ if pipe:
+ _positions.pop(pipe["Arn"], None)
+
+
+def _ensure_poller():
+ global _poller_started
+ with _poller_lock:
+ if not _poller_started:
+ t = threading.Thread(target=_poll_loop, daemon=True)
+ t.start()
+ _poller_started = True
+
+
+def _poll_loop():
+ while True:
+ try:
+ _poll_once()
+ except Exception as e:
+ logger.error("Pipes poller error: %s", e)
+ time.sleep(1 if _pipes else 5)
+
+
+def _poll_once():
+ from ministack.services import dynamodb as _ddb
+
+ stream_records = getattr(_ddb, "_stream_records", None)
+ if stream_records is None:
+ return
+
+ for pipe in list(_pipes.values()):
+ if pipe.get("CurrentState") != "RUNNING":
+ continue
+
+ source_arn = pipe.get("Source", "")
+ target_arn = pipe.get("Target", "")
+ if ":dynamodb:" not in source_arn or "/stream/" not in source_arn:
+ continue
+ if ":sns:" not in target_arn:
+ continue
+
+ table_name = _table_name_from_stream_arn(source_arn)
+ if not table_name:
+ continue
+
+ records = stream_records.get(table_name, [])
+ pos = int(_positions.get(pipe["Arn"], 0))
+ if pos < 0:
+ pos = 0
+ if pos >= len(records):
+ continue
+
+ batch = records[pos:]
+ for rec in batch:
+ _publish_record_to_sns(target_arn, pipe, rec)
+ _positions[pipe["Arn"]] = pos + len(batch)
+
+
+def _publish_record_to_sns(topic_arn: str, pipe: dict, record: dict):
+ from ministack.services import sns as _sns
+
+ topic = _sns._topics.get(topic_arn)
+ if not topic:
+ logger.warning("Pipes %s: SNS topic not found %s", pipe.get("Name"), topic_arn)
+ return
+
+ msg_id = new_uuid()
+ message = json.dumps(record)
+ subject = f"Pipes {pipe.get('Name', '')}"
+
+ topic["messages"].append({
+ "id": msg_id,
+ "message": message,
+ "subject": subject,
+ "message_structure": "",
+ "message_attributes": {},
+ "timestamp": int(time.time()),
+ })
+ _sns._fanout(topic_arn, msg_id, message, subject, "", {})
+
+
+def _table_name_from_stream_arn(stream_arn: str) -> str:
+ if "/stream/" not in stream_arn:
+ return ""
+ return stream_arn.split("/stream/", 1)[0].rsplit("/", 1)[-1]
+
+
+def _initial_position(pipe: dict) -> int:
+ from ministack.services import dynamodb as _ddb
+
+ table_name = _table_name_from_stream_arn(pipe.get("Source", ""))
+ if not table_name:
+ return 0
+
+ records = getattr(_ddb, "_stream_records", {}).get(table_name, [])
+ if pipe.get("StartingPosition") == "TRIM_HORIZON":
+ return 0
+ return len(records)
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index 6a4db04e..700e7aea 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -35,7 +35,7 @@ from urllib.parse import parse_qs
from xml.sax.saxutils import escape as _esc
from ministack.core.persistence import load_state
-from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid, get_region
logger = logging.getLogger("rds")
@@ -251,7 +251,7 @@ def _create_db_instance(p):
storage_type = _p(p, "StorageType") or "gp2"
subnet_group_name = _p(p, "DBSubnetGroupName") or "default"
- arn = f"arn:aws:rds:{REGION}:{get_account_id()}:db:{db_id}"
+ arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:db:{db_id}"
dbi_resource_id = f"db-{new_uuid().replace('-', '')[:20].upper()}"
endpoint_host = "localhost"
endpoint_port = port
@@ -339,7 +339,7 @@ def _create_db_instance(p):
"SubnetGroupStatus": "Complete",
"Subnets": [],
"VpcId": "vpc-00000000",
- "DBSubnetGroupArn": f"arn:aws:rds:{REGION}:{get_account_id()}:subgrp:{subnet_group_name}",
+ "DBSubnetGroupArn": f"arn:aws:rds:{get_region()}:{get_account_id()}:subgrp:{subnet_group_name}",
})
instance = {
@@ -365,7 +365,7 @@ def _create_db_instance(p):
"DBParameterGroupName": param_group_name,
"ParameterApplyStatus": "in-sync",
}],
- "AvailabilityZone": _p(p, "AvailabilityZone") or f"{REGION}a",
+ "AvailabilityZone": _p(p, "AvailabilityZone") or f"{get_region()}a",
"DBSubnetGroup": subnet_group,
"PreferredMaintenanceWindow": "sun:05:00-sun:06:00",
"PendingModifiedValues": {},
@@ -656,7 +656,7 @@ def _create_read_replica(p):
if replica_id in _instances:
return _error("DBInstanceAlreadyExistsFault", f"DBInstance {replica_id} already exists.", 400)
- arn = f"arn:aws:rds:{REGION}:{get_account_id()}:db:{replica_id}"
+ arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:db:{replica_id}"
replica = dict(source)
replica.update({
"DBInstanceIdentifier": replica_id,
@@ -701,7 +701,7 @@ def _restore_from_snapshot(p):
if not snap:
return _error("DBSnapshotNotFound", f"DBSnapshot {snap_id} not found.", 404)
- arn = f"arn:aws:rds:{REGION}:{get_account_id()}:db:{db_id}"
+ arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:db:{db_id}"
instance = {
"DBInstanceIdentifier": db_id,
"DBInstanceClass": _p(p, "DBInstanceClass") or snap.get("DBInstanceClass", "db.t3.micro"),
@@ -725,7 +725,7 @@ def _restore_from_snapshot(p):
"DBParameterGroupName": f"default.{snap.get('Engine', 'postgres')}",
"ParameterApplyStatus": "in-sync",
}],
- "AvailabilityZone": _p(p, "AvailabilityZone") or f"{REGION}a",
+ "AvailabilityZone": _p(p, "AvailabilityZone") or f"{get_region()}a",
"DBSubnetGroup": {"DBSubnetGroupName": _p(p, "DBSubnetGroupName") or "default",
"SubnetGroupStatus": "Complete", "Subnets": [], "VpcId": "vpc-00000000",
"DBSubnetGroupArn": ""},
@@ -774,7 +774,7 @@ def _create_db_cluster(p):
engine_version = _p(p, "EngineVersion") or _default_engine_version(engine)
port = int(_p(p, "Port") or _default_port(engine))
master_user = _p(p, "MasterUsername") or "admin"
- arn = f"arn:aws:rds:{REGION}:{get_account_id()}:cluster:{cluster_id}"
+ arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:cluster:{cluster_id}"
unique_suffix = new_uuid()[:8]
now_ts = time.time()
@@ -782,7 +782,7 @@ def _create_db_cluster(p):
vpc_sg_list = [{"VpcSecurityGroupId": sg, "Status": "active"} for sg in vpc_sgs] if vpc_sgs else []
az_list = _parse_member_list(p, "AvailabilityZones")
if not az_list:
- az_list = [f"{REGION}a", f"{REGION}b", f"{REGION}c"]
+ az_list = [f"{get_region()}a", f"{get_region()}b", f"{get_region()}c"]
master_pass = _p(p, "MasterUserPassword") or "password"
@@ -796,8 +796,8 @@ def _create_db_cluster(p):
"MasterUsername": master_user,
"_MasterUserPassword": master_pass,
"DatabaseName": _p(p, "DatabaseName") or "",
- "Endpoint": f"{cluster_id}.cluster-{unique_suffix}.{REGION}.rds.amazonaws.com",
- "ReaderEndpoint": f"{cluster_id}.cluster-ro-{unique_suffix}.{REGION}.rds.amazonaws.com",
+ "Endpoint": f"{cluster_id}.cluster-{unique_suffix}.{get_region()}.rds.amazonaws.com",
+ "ReaderEndpoint": f"{cluster_id}.cluster-ro-{unique_suffix}.{get_region()}.rds.amazonaws.com",
"Port": port,
"MultiAZ": _p(p, "MultiAZ") == "true",
"AvailabilityZones": az_list,
@@ -961,7 +961,7 @@ def _modify_db_cluster(p):
def _create_snapshot_internal(snap_id, instance):
"""Internal helper — creates a snapshot dict from an instance."""
- arn = f"arn:aws:rds:{REGION}:{get_account_id()}:snapshot:{snap_id}"
+ arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:snapshot:{snap_id}"
now_ts = time.time()
snap = {
"DBSnapshotIdentifier": snap_id,
@@ -973,7 +973,7 @@ def _create_snapshot_internal(snap_id, instance):
"InstanceCreateTime": instance.get("InstanceCreateTime", _format_time(now_ts)),
"Status": "available",
"AllocatedStorage": instance.get("AllocatedStorage", 20),
- "AvailabilityZone": instance.get("AvailabilityZone", f"{REGION}a"),
+ "AvailabilityZone": instance.get("AvailabilityZone", f"{get_region()}a"),
"VpcId": "vpc-00000000",
"Port": instance.get("Endpoint", {}).get("Port", 5432),
"MasterUsername": instance.get("MasterUsername", "admin"),
@@ -1063,9 +1063,9 @@ def _create_subnet_group(p):
return _error("MissingParameter", "DBSubnetGroupName is required", 400)
desc = _p(p, "DBSubnetGroupDescription") or name
subnet_ids = _parse_member_list(p, "SubnetIds")
- arn = f"arn:aws:rds:{REGION}:{get_account_id()}:subgrp:{name}"
+ arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:subgrp:{name}"
- subnets = [{"SubnetIdentifier": sid, "SubnetAvailabilityZone": {"Name": f"{REGION}a"},
+ subnets = [{"SubnetIdentifier": sid, "SubnetAvailabilityZone": {"Name": f"{get_region()}a"},
"SubnetOutpost": {}, "SubnetStatus": "Active"} for sid in subnet_ids]
_subnet_groups[name] = {
@@ -1123,7 +1123,7 @@ def _create_param_group(p):
return _error("MissingParameter", "DBParameterGroupName is required", 400)
family = _p(p, "DBParameterGroupFamily") or "postgres15"
desc = _p(p, "Description") or name
- arn = f"arn:aws:rds:{REGION}:{get_account_id()}:pg:{name}"
+ arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:pg:{name}"
_param_groups[name] = {
"DBParameterGroupName": name,
@@ -1301,7 +1301,7 @@ def _create_db_cluster_param_group(p):
return _error("MissingParameter", "DBClusterParameterGroupName is required", 400)
family = _p(p, "DBParameterGroupFamily") or "aurora-postgresql15"
desc = _p(p, "Description") or name
- arn = f"arn:aws:rds:{REGION}:{get_account_id()}:cluster-pg:{name}"
+ arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:cluster-pg:{name}"
_db_cluster_param_groups[name] = {
"DBClusterParameterGroupName": name,
@@ -1455,7 +1455,7 @@ def _create_db_cluster_snapshot(p):
if not cluster:
return _error("DBClusterNotFoundFault", f"DBCluster {cluster_id} not found.", 404)
- arn = f"arn:aws:rds:{REGION}:{get_account_id()}:cluster-snapshot:{snap_id}"
+ arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:cluster-snapshot:{snap_id}"
now_ts = time.time()
snap = {
"DBClusterSnapshotIdentifier": snap_id,
@@ -1543,7 +1543,7 @@ def _modify_subnet_group(p):
subnet_ids = _parse_member_list(p, "SubnetIds")
if subnet_ids:
sg["Subnets"] = [
- {"SubnetIdentifier": sid, "SubnetAvailabilityZone": {"Name": f"{REGION}a"},
+ {"SubnetIdentifier": sid, "SubnetAvailabilityZone": {"Name": f"{get_region()}a"},
"SubnetOutpost": {}, "SubnetStatus": "Active"} for sid in subnet_ids
]
@@ -1590,7 +1590,7 @@ def _create_option_group(p):
engine = _p(p, "EngineName") or "postgres"
major_version = _p(p, "MajorEngineVersion") or "15"
desc = _p(p, "OptionGroupDescription") or name
- arn = f"arn:aws:rds:{REGION}:{get_account_id()}:og:{name}"
+ arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:og:{name}"
_option_groups[name] = {
"OptionGroupName": name,
@@ -1970,8 +1970,8 @@ def _describe_orderable_options(p):
<DBInstanceClass>{cls}</DBInstanceClass>
<LicenseModel>{_license_model(engine)}</LicenseModel>
<AvailabilityZones>
- <AvailabilityZone><Name>{REGION}a</Name></AvailabilityZone>
- <AvailabilityZone><Name>{REGION}b</Name></AvailabilityZone>
+ <AvailabilityZone><Name>{get_region()}a</Name></AvailabilityZone>
+ <AvailabilityZone><Name>{get_region()}b</Name></AvailabilityZone>
</AvailabilityZones>
<MultiAZCapable>true</MultiAZCapable>
<ReadReplicaCapable>true</ReadReplicaCapable>
@@ -2043,7 +2043,7 @@ def _instance_xml(i):
subnet_xml = ""
for s in subnet.get("Subnets", []):
- az = s.get("SubnetAvailabilityZone", {}).get("Name", f"{REGION}a") if isinstance(s.get("SubnetAvailabilityZone"), dict) else f"{REGION}a"
+ az = s.get("SubnetAvailabilityZone", {}).get("Name", f"{get_region()}a") if isinstance(s.get("SubnetAvailabilityZone"), dict) else f"{get_region()}a"
subnet_xml += f"""<Subnet>
<SubnetIdentifier>{s.get('SubnetIdentifier','')}</SubnetIdentifier>
<SubnetAvailabilityZone><Name>{az}</Name></SubnetAvailabilityZone>
@@ -2086,7 +2086,7 @@ def _instance_xml(i):
<DBSecurityGroups>{db_sg_xml}</DBSecurityGroups>
<VpcSecurityGroups>{vpc_sg_xml}</VpcSecurityGroups>
<DBParameterGroups>{param_xml}</DBParameterGroups>
- <AvailabilityZone>{i.get('AvailabilityZone',f'{REGION}a')}</AvailabilityZone>
+ <AvailabilityZone>{i.get('AvailabilityZone',f'{get_region()}a')}</AvailabilityZone>
<DBSubnetGroup>
<DBSubnetGroupName>{subnet.get('DBSubnetGroupName','default')}</DBSubnetGroupName>
<DBSubnetGroupDescription>{subnet.get('DBSubnetGroupDescription','')}</DBSubnetGroupDescription>
@@ -2216,7 +2216,7 @@ def _snapshot_xml(s):
<InstanceCreateTime>{s.get('InstanceCreateTime','')}</InstanceCreateTime>
<Status>{s['Status']}</Status>
<AllocatedStorage>{s.get('AllocatedStorage',20)}</AllocatedStorage>
- <AvailabilityZone>{s.get('AvailabilityZone',f'{REGION}a')}</AvailabilityZone>
+ <AvailabilityZone>{s.get('AvailabilityZone',f'{get_region()}a')}</AvailabilityZone>
<VpcId>{s.get('VpcId','vpc-00000000')}</VpcId>
<Port>{s.get('Port',5432)}</Port>
<MasterUsername>{s.get('MasterUsername','admin')}</MasterUsername>
@@ -2240,7 +2240,7 @@ def _snapshot_xml(s):
def _subnet_group_xml(sg):
subnets_xml = ""
for s in sg.get("Subnets", []):
- az = s.get("SubnetAvailabilityZone", {}).get("Name", f"{REGION}a") if isinstance(s.get("SubnetAvailabilityZone"), dict) else f"{REGION}a"
+ az = s.get("SubnetAvailabilityZone", {}).get("Name", f"{get_region()}a") if isinstance(s.get("SubnetAvailabilityZone"), dict) else f"{get_region()}a"
subnets_xml += f"""<Subnet>
<SubnetIdentifier>{s.get('SubnetIdentifier','')}</SubnetIdentifier>
<SubnetAvailabilityZone><Name>{az}</Name></SubnetAvailabilityZone>
diff --git a/ministack/services/rds_data.py b/ministack/services/rds_data.py
index f32a8ccf..04f2438c 100644
--- a/ministack/services/rds_data.py
+++ b/ministack/services/rds_data.py
@@ -11,7 +11,7 @@ import re
import threading
import uuid
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, get_region
logger = logging.getLogger("rds-data")
diff --git a/ministack/services/s3files.py b/ministack/services/s3files.py
index 8576e980..59ece9fe 100644
--- a/ministack/services/s3files.py
+++ b/ministack/services/s3files.py
@@ -19,7 +19,7 @@ import os
import time
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, get_region
logger = logging.getLogger("s3files")
@@ -70,7 +70,7 @@ def reset():
def _arn(resource_type, resource_id):
- return f"arn:aws:s3files:{REGION}:{get_account_id()}:{resource_type}/{resource_id}"
+ return f"arn:aws:s3files:{get_region()}:{get_account_id()}:{resource_type}/{resource_id}"
def _now_iso():
@@ -239,7 +239,7 @@ def _create_mount_target(data):
"LifeCycleState": "available",
"IpAddress": data.get("IpAddress", "10.0.0.1"),
"VpcId": data.get("VpcId", "vpc-00000001"),
- "AvailabilityZone": data.get("AvailabilityZone", f"{REGION}a"),
+ "AvailabilityZone": data.get("AvailabilityZone", f"{get_region()}a"),
}
_mount_targets[mt_id] = mt
logger.info("Created mount target %s for fs %s", mt_id, fs_id)
diff --git a/ministack/services/scheduler.py b/ministack/services/scheduler.py
index e66b06f4..6cdd1ba9 100644
--- a/ministack/services/scheduler.py
+++ b/ministack/services/scheduler.py
@@ -17,7 +17,7 @@ import os
import re
import time
-from ministack.core.responses import AccountScopedDict, get_account_id
+from ministack.core.responses import AccountScopedDict, get_account_id, get_region
logger = logging.getLogger("scheduler")
@@ -61,11 +61,11 @@ def _now():
def _schedule_arn(group, name):
- return f"arn:aws:scheduler:{REGION}:{get_account_id()}:schedule/{group}/{name}"
+ return f"arn:aws:scheduler:{get_region()}:{get_account_id()}:schedule/{group}/{name}"
def _group_arn(name):
- return f"arn:aws:scheduler:{REGION}:{get_account_id()}:schedule-group/{name}"
+ return f"arn:aws:scheduler:{get_region()}:{get_account_id()}:schedule-group/{name}"
def _json_resp(status, body):
diff --git a/ministack/services/secretsmanager.py b/ministack/services/secretsmanager.py
index 32ef8591..dc498c77 100644
--- a/ministack/services/secretsmanager.py
+++ b/ministack/services/secretsmanager.py
@@ -19,7 +19,7 @@ import secrets as stdlib_secrets
import string
import time
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, get_region
logger = logging.getLogger("secretsmanager")
@@ -210,7 +210,7 @@ def _create_secret(data):
f"The operation failed because the secret {name} already exists.", 400,
)
- arn = f"arn:aws:secretsmanager:{REGION}:{get_account_id()}:secret:{name}-{new_uuid()[:6]}"
+ arn = f"arn:aws:secretsmanager:{get_region()}:{get_account_id()}:secret:{name}-{new_uuid()[:6]}"
vid = new_uuid()
now = int(time.time())
diff --git a/ministack/services/servicediscovery.py b/ministack/services/servicediscovery.py
index c9ee93fa..7bf94588 100644
--- a/ministack/services/servicediscovery.py
+++ b/ministack/services/servicediscovery.py
@@ -10,7 +10,7 @@ import os
import time
import xml.etree.ElementTree as ET
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, get_region
from ministack.services import route53
logger = logging.getLogger("servicediscovery")
@@ -123,11 +123,11 @@ async def handle_request(method, path, headers, body, query_params):
def _namespace_arn(ns_id: str) -> str:
- return f"arn:aws:servicediscovery:{REGION}:{get_account_id()}:namespace/{ns_id}"
+ return f"arn:aws:servicediscovery:{get_region()}:{get_account_id()}:namespace/{ns_id}"
def _service_arn(svc_id: str) -> str:
- return f"arn:aws:servicediscovery:{REGION}:{get_account_id()}:service/{svc_id}"
+ return f"arn:aws:servicediscovery:{get_region()}:{get_account_id()}:service/{svc_id}"
def _create_operation(op_type: str, targets=None):
diff --git a/ministack/services/ses.py b/ministack/services/ses.py
index 89cf8d94..2548707b 100644
--- a/ministack/services/ses.py
+++ b/ministack/services/ses.py
@@ -39,7 +39,7 @@ from email.policy import default as default_policy
from urllib.parse import parse_qs, unquote
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid, get_region
logger = logging.getLogger("ses")
diff --git a/ministack/services/ses_v2.py b/ministack/services/ses_v2.py
index 569962c6..bbad2cba 100644
--- a/ministack/services/ses_v2.py
+++ b/ministack/services/ses_v2.py
@@ -15,7 +15,7 @@ import os
import re
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import AccountScopedDict, get_account_id, json_response, new_uuid, now_iso
+from ministack.core.responses import AccountScopedDict, get_account_id, json_response, new_uuid, now_iso, get_region
from ministack.services.ses import _build_mime_message, _smtp_relay
logger = logging.getLogger("ses-v2")
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index 5f770812..cdc8791f 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -27,7 +27,7 @@ _HOST = os.environ.get("MINISTACK_HOST", "localhost")
_PORT = os.environ.get("GATEWAY_PORT", "4566")
import ministack.services.lambda_svc as _lambda_svc
-from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid, get_region
from ministack.services import sqs as _sqs
logger = logging.getLogger("sns")
@@ -147,7 +147,7 @@ def _create_topic(params):
if is_fifo and "ContentBasedDeduplication" not in explicit_attrs:
explicit_attrs["ContentBasedDeduplication"] = "false"
- arn = f"arn:aws:sns:{REGION}:{get_account_id()}:{name}"
+ arn = f"arn:aws:sns:{get_region()}:{get_account_id()}:{name}"
if arn not in _topics:
default_policy = json.dumps({
"Version": "2008-10-17",
@@ -984,7 +984,7 @@ def _create_platform_application(params):
if not name or not platform:
return _error("InvalidParameterException", "Name and Platform are required", 400)
- arn = f"arn:aws:sns:{REGION}:{get_account_id()}:app/{platform}/{name}"
+ arn = f"arn:aws:sns:{get_region()}:{get_account_id()}:app/{platform}/{name}"
attrs = {}
i = 1
while _p(params, f"Attributes.entry.{i}.key"):
@@ -1262,7 +1262,7 @@ def _build_envelope(topic_arn: str, msg_id: str, message: str, subject: str,
"SignatureVersion": "1",
"Signature": "FAKE",
"SigningCertURL": "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-fake.pem",
- "UnsubscribeURL": f"http://{_HOST}:{_PORT}/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:{REGION}:{get_account_id()}:example",
+ "UnsubscribeURL": f"http://{_HOST}:{_PORT}/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:{get_region()}:{get_account_id()}:example",
}
if message_attributes:
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index 70c55487..6ed0e772 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -35,7 +35,7 @@ from urllib.parse import parse_qs
from xml.sax.saxutils import escape as _esc
from ministack.core.persistence import load_state, PERSIST_STATE
-from ministack.core.responses import AccountScopedDict, get_account_id, md5_hash, new_uuid, now_iso
+from ministack.core.responses import AccountScopedDict, get_account_id, md5_hash, new_uuid, now_iso, get_region
logger = logging.getLogger("sqs")
@@ -188,7 +188,7 @@ def _act_create_queue(data: dict, _u: str) -> dict:
q: dict = {
"name": name, "url": url, "is_fifo": is_fifo,
"attributes": {
- "QueueArn": f"arn:aws:sqs:{REGION}:{get_account_id()}:{name}",
+ "QueueArn": f"arn:aws:sqs:{get_region()}:{get_account_id()}:{name}",
"CreatedTimestamp": ts,
"LastModifiedTimestamp": ts,
"VisibilityTimeout": "30",
diff --git a/ministack/services/ssm.py b/ministack/services/ssm.py
index 407c8449..72efd878 100644
--- a/ministack/services/ssm.py
+++ b/ministack/services/ssm.py
@@ -15,7 +15,7 @@ import logging
import time
from datetime import datetime, timezone
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, get_region
logger = logging.getLogger("ssm")
@@ -54,7 +54,7 @@ def _now_epoch() -> float:
def _param_arn(name: str) -> str:
- return f"arn:aws:ssm:{REGION}:{get_account_id()}:parameter{name}"
+ return f"arn:aws:ssm:{get_region()}:{get_account_id()}:parameter{name}"
def _encode_next_token(index: int) -> str:
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index 7cfe9a9d..6d52a202 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -39,6 +39,7 @@ from ministack.core.responses import (
json_response,
new_uuid,
now_iso,
+ get_region,
)
logger = logging.getLogger("states")
@@ -258,7 +259,7 @@ def _create_state_machine(data):
if not name:
return error_response_json("ValidationException", "name is required", 400)
- arn = f"arn:aws:states:{REGION}:{get_account_id()}:stateMachine:{name}"
+ arn = f"arn:aws:states:{get_region()}:{get_account_id()}:stateMachine:{name}"
if arn in _state_machines:
return error_response_json(
"StateMachineAlreadyExists",
@@ -367,7 +368,7 @@ def _start_execution(data):
sm = _state_machines[sm_arn]
name = data.get("name") or new_uuid()
- exec_arn = (f"arn:aws:states:{REGION}:{get_account_id()}"
+ exec_arn = (f"arn:aws:states:{get_region()}:{get_account_id()}"
f":execution:{sm['name']}:{name}")
# Reject duplicate execution names
@@ -515,7 +516,7 @@ def _start_sync_execution(data):
sm = _state_machines[sm_arn]
name = data.get("name") or new_uuid()
- exec_arn = (f"arn:aws:states:{REGION}:{get_account_id()}"
+ exec_arn = (f"arn:aws:states:{get_region()}:{get_account_id()}"
f":execution:{sm['name']}:{name}")
start_date = now_iso()
@@ -642,7 +643,7 @@ def _create_activity(data):
if not name:
return error_response_json("ValidationException", "name is required", 400)
- arn = f"arn:aws:states:{REGION}:{get_account_id()}:activity:{name}"
+ arn = f"arn:aws:states:{get_region()}:{get_account_id()}:activity:{name}"
if arn in _activities:
return error_response_json(
"ActivityAlreadyExists", f"Activity already exists: {arn}", 400)
@@ -811,7 +812,7 @@ def _test_state(data):
ctx = {}
else:
ctx = {}
- ctx.setdefault("Execution", {"Id": f"arn:aws:states:{REGION}:{get_account_id()}:execution:test:{new_uuid()}", "Name": "test", "StartTime": now_iso()})
+ ctx.setdefault("Execution", {"Id": f"arn:aws:states:{get_region()}:{get_account_id()}:execution:test:{new_uuid()}", "Name": "test", "StartTime": now_iso()})
ctx.setdefault("StateMachine", {"Id": "test", "Name": "test"})
ctx["State"] = {"Name": state_name, "EnteredTime": now_iso()}
@@ -2310,9 +2311,9 @@ def _dispatch_aws_sdk_json(service_info, service_name, action, input_data):
headers = {
"x-amz-target": target,
"content-type": "application/x-amz-json-1.0",
- "host": f"{service_key}.{REGION}.amazonaws.com",
+ "host": f"{service_key}.{get_region()}.amazonaws.com",
"authorization": (
- f"AWS4-HMAC-SHA256 Credential=test/20260101/{REGION}/{service_key}/aws4_request"
+ f"AWS4-HMAC-SHA256 Credential=test/20260101/{get_region()}/{service_key}/aws4_request"
),
}
@@ -2596,9 +2597,9 @@ def _dispatch_aws_sdk_query(service_info, service_name, action, input_data):
headers = {
"content-type": "application/x-www-form-urlencoded",
- "host": f"{service_key}.{REGION}.amazonaws.com",
+ "host": f"{service_key}.{get_region()}.amazonaws.com",
"authorization": (
- f"AWS4-HMAC-SHA256 Credential=test/20260101/{REGION}/{service_key}/aws4_request"
+ f"AWS4-HMAC-SHA256 Credential=test/20260101/{get_region()}/{service_key}/aws4_request"
),
}
@@ -2698,9 +2699,9 @@ def _dispatch_aws_sdk_rest_json(service_info, service_name, action, input_data):
body = json.dumps(wire_data).encode("utf-8")
headers = {
"content-type": "application/json",
- "host": f"{service_key}.{REGION}.amazonaws.com",
+ "host": f"{service_key}.{get_region()}.amazonaws.com",
"authorization": (
- f"AWS4-HMAC-SHA256 Credential=test/20260101/{REGION}/{service_key}/aws4_request"
+ f"AWS4-HMAC-SHA256 Credential=test/20260101/{get_region()}/{service_key}/aws4_request"
),
}
diff --git a/ministack/services/tagging.py b/ministack/services/tagging.py
index 7194c0ab..4cbc1380 100644
--- a/ministack/services/tagging.py
+++ b/ministack/services/tagging.py
@@ -1,16 +1,42 @@
"""
Resource Groups Tagging API emulator.
-Phase 2: extends GetResources to 15 services and adds GetTagKeys, GetTagValues.
+
+Supports the five operations of the real ResourceGroupsTaggingAPI_20170126
+target (`GetResources`, `GetTagKeys`, `GetTagValues`, `TagResources`,
+`UntagResources`) across the services listed in ``_COLLECTORS`` / ``_WRITERS``.
+
+Architecture:
+- **Collectors** (one per service) yield ``(arn, [{"Key":..., "Value":...}])``
+ tuples by reading each service module's tag state. Used by GetResources.
+- **Writers** apply a ``{key: value}`` dict onto a service's tag state for a
+ given ARN. Used by TagResources. Writers raise ``_ResourceNotFound`` when
+ the ARN points at a resource that does not exist in the caller's account;
+ the entry point catches it and surfaces the ARN in ``FailedResourcesMap``
+ with ``InvalidParameterException``, matching AWS.
+- **Removers** do the inverse for UntagResources.
+
+Each service keeps its own tag format (S3 flat dict, DynamoDB key/value list,
+KMS TagKey/TagValue, ECS lowercase key/value, …); the helpers in this file
+normalise to the standard ``[{"Key":..., "Value":...}]`` shape on read and
+denormalise on write.
"""
import json
import logging
import os
+from ministack.core.responses import get_region
logger = logging.getLogger("tagging")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+class _ResourceNotFound(Exception):
+ """Raised by a writer/remover when the target ARN refers to a resource
+ that does not exist in the caller's account. Caught by the TagResources /
+ UntagResources entry points and surfaced in ``FailedResourcesMap`` with
+ ``InvalidParameterException`` (matches real AWS behaviour)."""
+
+
# ── Tag format normalisation ──────────────────────────────────────────────────
def _normalise_flat(tag_dict):
@@ -44,7 +70,7 @@ def _collect_s3():
def _collect_lambda():
import ministack.services.lambda_svc as svc
for name, fn in svc._functions.items():
- arn = f"arn:aws:lambda:{REGION}:{_account()}:function:{name}"
+ arn = f"arn:aws:lambda:{get_region()}:{_account()}:function:{name}"
yield arn, _normalise_flat(fn.get("tags", {}))
@@ -89,14 +115,14 @@ def _collect_eventbridge():
def _collect_kms():
import ministack.services.kms as svc
for key_id, rec in svc._keys.items():
- arn = f"arn:aws:kms:{REGION}:{_account()}:key/{key_id}"
+ arn = f"arn:aws:kms:{get_region()}:{_account()}:key/{key_id}"
yield arn, _normalise_kms(rec.get("Tags", []))
def _collect_ecr():
import ministack.services.ecr as svc
for name, repo in svc._repositories.items():
- arn = f"arn:aws:ecr:{REGION}:{_account()}:repository/{name}"
+ arn = f"arn:aws:ecr:{get_region()}:{_account()}:repository/{name}"
yield arn, _normalise_list(repo.get("tags", []))
@@ -115,10 +141,10 @@ def _collect_glue():
def _collect_cognito():
import ministack.services.cognito as svc
for pool_id, pool in svc._user_pools.items():
- arn = f"arn:aws:cognito-idp:{REGION}:{_account()}:userpool/{pool_id}"
+ arn = f"arn:aws:cognito-idp:{get_region()}:{_account()}:userpool/{pool_id}"
yield arn, _normalise_flat(pool.get("UserPoolTags", {}))
for pool_id, tags in svc._identity_tags.items():
- arn = f"arn:aws:cognito-identity:{REGION}:{_account()}:identitypool/{pool_id}"
+ arn = f"arn:aws:cognito-identity:{get_region()}:{_account()}:identitypool/{pool_id}"
yield arn, _normalise_flat(tags)
@@ -143,10 +169,10 @@ def _collect_cloudfront():
def _collect_efs():
import ministack.services.efs as svc
for fs_id, fs in svc._file_systems.items():
- arn = f"arn:aws:elasticfilesystem:{REGION}:{_account()}:file-system/{fs_id}"
+ arn = f"arn:aws:elasticfilesystem:{get_region()}:{_account()}:file-system/{fs_id}"
yield arn, _normalise_list(fs.get("Tags", []))
for ap_id, ap in svc._access_points.items():
- arn = f"arn:aws:elasticfilesystem:{REGION}:{_account()}:access-point/{ap_id}"
+ arn = f"arn:aws:elasticfilesystem:{get_region()}:{_account()}:access-point/{ap_id}"
yield arn, _normalise_list(ap.get("Tags", []))
@@ -220,24 +246,38 @@ def _write_s3(arn, tags):
def _write_lambda(arn, tags):
+ """Merge ``tags`` into the Lambda function's ``tags`` field.
+
+ Raises ``_ResourceNotFound`` if the function does not exist in the caller's
+ account (AWS returns InvalidParameterException in that case)."""
import ministack.services.lambda_svc as svc
name = arn.split("function:")[-1]
- if name in svc._functions:
- svc._functions[name].setdefault("tags", {}).update(tags)
+ if name not in svc._functions:
+ raise _ResourceNotFound(arn)
+ svc._functions[name].setdefault("tags", {}).update(tags)
def _write_sqs(arn, tags):
+ """Merge ``tags`` into the SQS queue keyed by ``QueueArn``.
+
+ Raises ``_ResourceNotFound`` if no queue in the caller's account matches."""
import ministack.services.sqs as svc
for q in svc._queues.values():
if q.get("attributes", {}).get("QueueArn") == arn:
q.setdefault("tags", {}).update(tags)
- break
+ return
+ raise _ResourceNotFound(arn)
def _write_sns(arn, tags):
+ """Merge ``tags`` into the SNS topic at ``arn``.
+
+ Raises ``_ResourceNotFound`` if the topic does not exist in the caller's
+ account."""
import ministack.services.sns as svc
- if arn in svc._topics:
- svc._topics[arn].setdefault("tags", {}).update(tags)
+ if arn not in svc._topics:
+ raise _ResourceNotFound(arn)
+ svc._topics[arn].setdefault("tags", {}).update(tags)
def _write_dynamodb(arn, tags):
@@ -283,10 +323,15 @@ def _write_glue(arn, tags):
def _write_cognito_idp(arn, tags):
+ """Merge ``tags`` into the Cognito user pool's ``UserPoolTags`` field.
+
+ Raises ``_ResourceNotFound`` if the pool does not exist in the caller's
+ account."""
import ministack.services.cognito as svc
pool_id = arn.split("userpool/")[-1]
- if pool_id in svc._user_pools:
- svc._user_pools[pool_id].setdefault("UserPoolTags", {}).update(tags)
+ if pool_id not in svc._user_pools:
+ raise _ResourceNotFound(arn)
+ svc._user_pools[pool_id].setdefault("UserPoolTags", {}).update(tags)
def _write_cognito_identity(arn, tags):
@@ -345,30 +390,38 @@ def _remove_s3(arn, keys):
def _remove_lambda(arn, keys):
+ """Remove ``keys`` from the Lambda function's ``tags`` field.
+
+ Raises ``_ResourceNotFound`` if the function does not exist."""
import ministack.services.lambda_svc as svc
name = arn.split("function:")[-1]
- if name in svc._functions:
- tags = svc._functions[name].get("tags", {})
- for k in keys:
- tags.pop(k, None)
+ if name not in svc._functions:
+ raise _ResourceNotFound(arn)
+ tags = svc._functions[name].get("tags", {})
+ for k in keys:
+ tags.pop(k, None)
def _remove_sqs(arn, keys):
+ """Remove ``keys`` from the SQS queue's tags. Raises ``_ResourceNotFound``."""
import ministack.services.sqs as svc
for q in svc._queues.values():
if q.get("attributes", {}).get("QueueArn") == arn:
tags = q.get("tags", {})
for k in keys:
tags.pop(k, None)
- break
+ return
+ raise _ResourceNotFound(arn)
def _remove_sns(arn, keys):
+ """Remove ``keys`` from the SNS topic's tags. Raises ``_ResourceNotFound``."""
import ministack.services.sns as svc
- if arn in svc._topics:
- tags = svc._topics[arn].get("tags", {})
- for k in keys:
- tags.pop(k, None)
+ if arn not in svc._topics:
+ raise _ResourceNotFound(arn)
+ tags = svc._topics[arn].get("tags", {})
+ for k in keys:
+ tags.pop(k, None)
def _remove_dynamodb(arn, keys):
@@ -414,12 +467,14 @@ def _remove_glue(arn, keys):
def _remove_cognito_idp(arn, keys):
+ """Remove ``keys`` from a Cognito user pool's tags. Raises ``_ResourceNotFound``."""
import ministack.services.cognito as svc
pool_id = arn.split("userpool/")[-1]
- if pool_id in svc._user_pools:
- tags = svc._user_pools[pool_id].get("UserPoolTags", {})
- for k in keys:
- tags.pop(k, None)
+ if pool_id not in svc._user_pools:
+ raise _ResourceNotFound(arn)
+ tags = svc._user_pools[pool_id].get("UserPoolTags", {})
+ for k in keys:
+ tags.pop(k, None)
def _remove_cognito_identity(arn, keys):
@@ -538,6 +593,13 @@ def _get_tag_values(data):
# ── Entry point ───────────────────────────────────────────────────────────────
def _tag_resources(data):
+ """TagResources: apply ``Tags`` to every ARN in ``ResourceARNList``.
+
+ Per ARN, failures are reported in ``FailedResourcesMap``:
+ - Unknown service segment → ``InvalidParameterException`` (400).
+ - Resource not found in caller's account → ``InvalidParameterException`` (400).
+ - Anything else raised by the writer → ``InternalServiceException`` (500).
+ The top-level response is always 200 with a (possibly empty) map, matching AWS."""
arn_list = data.get("ResourceARNList", [])
tags = data.get("Tags", {})
failed = {}
@@ -547,13 +609,19 @@ def _tag_resources(data):
writer = _WRITERS.get(svc_key)
if writer is None:
failed[arn] = {
- "ErrorCode": "InternalServiceException",
+ "ErrorCode": "InvalidParameterException",
"ErrorMessage": f"Unsupported resource type: {svc_key}",
- "StatusCode": 501,
+ "StatusCode": 400,
}
continue
try:
writer(arn, tags)
+ except _ResourceNotFound:
+ failed[arn] = {
+ "ErrorCode": "InvalidParameterException",
+ "ErrorMessage": f"Resource not found: {arn}",
+ "StatusCode": 400,
+ }
except Exception as exc:
failed[arn] = {
"ErrorCode": "InternalServiceException",
@@ -567,6 +635,10 @@ def _tag_resources(data):
def _untag_resources(data):
+ """UntagResources: remove ``TagKeys`` from every ARN in ``ResourceARNList``.
+
+ Per-ARN failure semantics match :func:`_tag_resources`. Missing tag keys on
+ an existing resource are a no-op, not a failure."""
arn_list = data.get("ResourceARNList", [])
tag_keys = data.get("TagKeys", [])
failed = {}
@@ -576,13 +648,19 @@ def _untag_resources(data):
remover = _REMOVERS.get(svc_key)
if remover is None:
failed[arn] = {
- "ErrorCode": "InternalServiceException",
+ "ErrorCode": "InvalidParameterException",
"ErrorMessage": f"Unsupported resource type: {svc_key}",
- "StatusCode": 501,
+ "StatusCode": 400,
}
continue
try:
remover(arn, tag_keys)
+ except _ResourceNotFound:
+ failed[arn] = {
+ "ErrorCode": "InvalidParameterException",
+ "ErrorMessage": f"Resource not found: {arn}",
+ "StatusCode": 400,
+ }
except Exception as exc:
failed[arn] = {
"ErrorCode": "InternalServiceException",
diff --git a/ministack/services/transfer.py b/ministack/services/transfer.py
index 6aacee50..29415dfb 100644
--- a/ministack/services/transfer.py
+++ b/ministack/services/transfer.py
@@ -22,6 +22,7 @@ from ministack.core.responses import (
json_response,
new_uuid,
now_iso,
+ get_region,
)
logger = logging.getLogger("transfer")
@@ -70,11 +71,11 @@ def _key_id():
def _server_arn(server_id):
- return f"arn:aws:transfer:{REGION}:{get_account_id()}:server/{server_id}"
+ return f"arn:aws:transfer:{get_region()}:{get_account_id()}:server/{server_id}"
def _user_arn(server_id, user_name):
- return f"arn:aws:transfer:{REGION}:{get_account_id()}:user/{server_id}/{user_name}"
+ return f"arn:aws:transfer:{get_region()}:{get_account_id()}:user/{server_id}/{user_name}"
def _user_key(server_id, user_name):
diff --git a/ministack/services/waf.py b/ministack/services/waf.py
index 44194fc4..d1fd0679 100644
--- a/ministack/services/waf.py
+++ b/ministack/services/waf.py
@@ -15,7 +15,7 @@ import os
import logging
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, now_iso
+from ministack.core.responses import AccountScopedDict, get_account_id, error_response_json, json_response, new_uuid, now_iso, get_region
logger = logging.getLogger("wafv2")
@@ -56,15 +56,15 @@ def _waf_err(code, message):
def _acl_arn(name, uid):
- return f"arn:aws:wafv2:{REGION}:{get_account_id()}:regional/webacl/{name}/{uid}"
+ return f"arn:aws:wafv2:{get_region()}:{get_account_id()}:regional/webacl/{name}/{uid}"
def _ipset_arn(name, uid):
- return f"arn:aws:wafv2:{REGION}:{get_account_id()}:regional/ipset/{name}/{uid}"
+ return f"arn:aws:wafv2:{get_region()}:{get_account_id()}:regional/ipset/{name}/{uid}"
def _rg_arn(name, uid):
- return f"arn:aws:wafv2:{REGION}:{get_account_id()}:regional/rulegroup/{name}/{uid}"
+ return f"arn:aws:wafv2:{get_region()}:{get_account_id()}:regional/rulegroup/{name}/{uid}"
async def handle_request(method, path, headers, body, query_params):
diff --git a/pyproject.toml b/pyproject.toml
index bf1bc328..c517720f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.3.4"
+version = "1.3.5"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index f93f80a2..112839a1 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -2050,3 +2050,59 @@ def test_cfn_eventbus_default_name_fails(cfn, eb):
# Default bus must still exist and be unaffected
bus = eb.describe_event_bus(Name="default")
assert bus["Name"] == "default"
+
+
+def test_cfn_aws_region_pseudo_param_uses_caller_region():
+ """CFN's AWS::Region pseudo-param must resolve to the caller's request region,
+ not MINISTACK_REGION (issue #398 — CDK bootstrap resources inheriting wrong region)."""
+ import boto3
+ from botocore.config import Config
+
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+
+ # Caller explicitly uses us-east-2 via SigV4 Credential scope.
+ def _client(svc: str):
+ return boto3.client(
+ svc, endpoint_url=endpoint, region_name="us-east-2",
+ aws_access_key_id="test", aws_secret_access_key="test",
+ config=Config(retries={"mode": "standard"}),
+ )
+
+ cfn_us2 = _client("cloudformation")
+ s3_us2 = _client("s3")
+
+ template = """
+AWSTemplateFormatVersion: '2010-09-09'
+Resources:
+ RegionalBucket:
+ Type: AWS::S3::Bucket
+ Properties:
+ BucketName: !Sub "rgn-test-${AWS::Region}"
+Outputs:
+ Region:
+ Value: !Ref AWS::Region
+ BucketName:
+ Value: !Ref RegionalBucket
+"""
+
+ stack_name = "cfn-region-398"
+ try:
+ cfn_us2.delete_stack(StackName=stack_name)
+ except Exception:
+ pass
+
+ cfn_us2.create_stack(StackName=stack_name, TemplateBody=template)
+ _wait_stack(cfn_us2, stack_name)
+
+ stack = cfn_us2.describe_stacks(StackName=stack_name)["Stacks"][0]
+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}
+ assert outputs["Region"] == "us-east-2", \
+ f"AWS::Region should resolve to caller's region, got {outputs['Region']!r}"
+ assert outputs["BucketName"] == "rgn-test-us-east-2"
+
+ # Stack ARN itself must carry the caller's region, not us-east-1.
+ assert ":us-east-2:" in stack["StackId"], f"StackId missing caller region: {stack['StackId']!r}"
+
+ # And the bucket was actually created with that name.
+ buckets = [b["Name"] for b in s3_us2.list_buckets()["Buckets"]]
+ assert "rgn-test-us-east-2" in buckets
diff --git a/tests/test_tagging.py b/tests/test_tagging.py
index dc7ca434..2490826f 100644
--- a/tests/test_tagging.py
+++ b/tests/test_tagging.py
@@ -1,3 +1,5 @@
+import os
+
import pytest
from botocore.exceptions import ClientError
@@ -629,3 +631,71 @@ def test_tagging_tag_resources_visible_in_get_tag_keys(tagging, s3):
tagging.tag_resources(ResourceARNList=[arn], Tags={"phase3-key": "phase3-val"})
resp = tagging.get_tag_keys()
assert "phase3-key" in resp["TagKeys"]
+
+
+# ========== Error shape (1.3.5) ==========
+
+def test_tagging_tag_resources_unknown_service_returns_invalid_parameter(tagging):
+ """Unknown ARN service segment returns InvalidParameterException/400, not
+ InternalServiceException/501 — matches real AWS."""
+ resp = tagging.tag_resources(
+ ResourceARNList=["arn:aws:unknownsvc:::no-such"],
+ Tags={"k": "v"},
+ )
+ entry = resp["FailedResourcesMap"]["arn:aws:unknownsvc:::no-such"]
+ assert entry["ErrorCode"] == "InvalidParameterException"
+ assert entry["StatusCode"] == 400
+
+
+def test_tagging_tag_resources_missing_lambda_surfaces_in_failed_map(tagging):
+ """Tagging a Lambda that does not exist in the caller's account surfaces
+ InvalidParameterException in FailedResourcesMap instead of silently no-op'ing."""
+ arn = "arn:aws:lambda:us-east-1:000000000000:function:no-such-fn-tag-missing"
+ resp = tagging.tag_resources(ResourceARNList=[arn], Tags={"k": "v"})
+ assert arn in resp["FailedResourcesMap"]
+ entry = resp["FailedResourcesMap"][arn]
+ assert entry["ErrorCode"] == "InvalidParameterException"
+ assert entry["StatusCode"] == 400
+
+
+def test_tagging_untag_missing_sns_surfaces_in_failed_map(tagging):
+ arn = "arn:aws:sns:us-east-1:000000000000:no-such-topic-untag-missing"
+ resp = tagging.untag_resources(ResourceARNList=[arn], TagKeys=["k"])
+ assert arn in resp["FailedResourcesMap"]
+ entry = resp["FailedResourcesMap"][arn]
+ assert entry["ErrorCode"] == "InvalidParameterException"
+
+
+def test_tagging_tag_resources_cross_account_isolation(s3):
+ """Tags applied in account A must not be visible in account B. Guard for
+ the multi-tenant property guaranteed by AccountScopedDict under the hood."""
+ import boto3
+ from botocore.config import Config
+
+ def _client(svc: str, account: str):
+ return boto3.client(
+ svc, endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),
+ region_name="us-east-1",
+ aws_access_key_id=account, aws_secret_access_key="test",
+ config=Config(retries={"mode": "standard"}),
+ )
+
+ s3_a = _client("s3", "111111111111")
+ s3_b = _client("s3", "222222222222")
+ tag_a = _client("resourcegroupstaggingapi", "111111111111")
+ tag_b = _client("resourcegroupstaggingapi", "222222222222")
+
+ s3_a.create_bucket(Bucket="tg-iso-acct-a")
+ s3_b.create_bucket(Bucket="tg-iso-acct-b")
+ arn_a = "arn:aws:s3:::tg-iso-acct-a"
+ tag_a.tag_resources(ResourceARNList=[arn_a], Tags={"tenant": "A"})
+
+ # Account B must not see A's tag.
+ resp_b = tag_b.get_resources(TagFilters=[{"Key": "tenant", "Values": ["A"]}])
+ arns_b = [r["ResourceARN"] for r in resp_b["ResourceTagMappingList"]]
+ assert arn_a not in arns_b
+
+ # Account A still sees its own tag.
+ resp_a = tag_a.get_resources(TagFilters=[{"Key": "tenant", "Values": ["A"]}])
+ arns_a = [r["ResourceARN"] for r in resp_a["ResourceTagMappingList"]]
+ assert arn_a in arns_a