Skip to content

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

feat: multi-tenancy, CDK deploy fixes, STS JSON protocol support (#196)

Nahuel Nucera6a788bf8327c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 829c65cd..feb349cf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,19 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.1.54] — 2026-04-08
+
+### Added
+- **Multi-tenancy via dynamic Account ID** — When `AWS_ACCESS_KEY_ID` is a 12-digit number (e.g. `048408301323`), MiniStack uses it as the Account ID for all ARN generation. Non-numeric keys fall back to `MINISTACK_ACCOUNT_ID` env var or `000000000000`. Enables lightweight tenant isolation on shared endpoints without configuration changes.
+- **CloudFormation `TemplateURL` support** — `CreateStack`, `UpdateStack`, `CreateChangeSet`, and `GetTemplateSummary` now fetch templates from S3 when `TemplateURL` is provided instead of `TemplateBody`. This unblocks `cdk deploy` which publishes templates to S3 and passes a URL.
+- **CloudFormation `AWS::CDK::Metadata` support** — CDK metadata resources are now handled as no-ops instead of failing with "Unsupported resource type".
+- **STS JSON protocol support** — STS now handles `AwsJson1_1` protocol requests (used by newer AWS SDK versions and CDK CLI). Previously, STS only accepted Query/form-encoded requests, causing CDK to fail with "The security token included in the request is invalid" when it tried to AssumeRole using the JSON protocol.
+
+### Fixed
+- **Test coverage for v1.1.53 fixes** — added unit tests for `_convert_parameters` (RDS Data API parameter binding) and SSM epoch timestamp in CloudFormation provisioner.
+
+---
+
## [1.1.53] — 2026-04-08
### Added
diff --git a/README.md b/README.md
index f2ed94a9..81a5dc99 100644
--- a/README.md
+++ b/README.md
@@ -90,6 +90,54 @@ curl http://localhost:4566/health
---
+## Multi-Tenancy
+
+MiniStack supports lightweight multi-tenancy without any configuration. If the `AWS_ACCESS_KEY_ID` is a **12-digit number**, it is used as the **Account ID** for all ARN generation. Non-numeric keys (like `test`) fall back to the `MINISTACK_ACCOUNT_ID` env var or `000000000000`.
+
+```bash
+# Team A — gets account 111111111111
+export AWS_ACCESS_KEY_ID=111111111111
+export AWS_SECRET_ACCESS_KEY=anything
+aws --endpoint-url=http://localhost:4566 sts get-caller-identity
+# → { "Account": "111111111111", ... }
+
+# Team B — gets account 222222222222
+export AWS_ACCESS_KEY_ID=222222222222
+export AWS_SECRET_ACCESS_KEY=anything
+aws --endpoint-url=http://localhost:4566 sts get-caller-identity
+# → { "Account": "222222222222", ... }
+```
+
+All ARNs (SQS queues, Lambda functions, IAM roles, etc.) reflect the caller's account ID. This allows multiple developers or CI pipelines to share a single MiniStack endpoint with isolated namespaces — no extra setup needed.
+
+| Access Key | Account ID Used |
+|---|---|
+| `111111111111` | `111111111111` |
+| `048408301323` | `048408301323` |
+| `test` | `000000000000` (default) |
+| `AKIAIOSFODNN7EXAMPLE` | `000000000000` (default) |
+
+**Terraform** — set `access_key` in your provider block:
+```hcl
+provider "aws" {
+ access_key = "048408301323"
+ secret_key = "test"
+ region = "us-east-1"
+ endpoints { ... }
+}
+```
+
+**boto3** — pass `aws_access_key_id`:
+```python
+boto3.client("s3",
+ endpoint_url="http://localhost:4566",
+ aws_access_key_id="048408301323",
+ aws_secret_access_key="test",
+)
+```
+
+---
+
## Using with AWS CLI
```bash
@@ -519,6 +567,7 @@ ecs.stop_task(cluster="dev", task=task_arn)
|----------|---------|-------------|
| `GATEWAY_PORT` | `4566` | Port to listen on. Also accepts `EDGE_PORT` (LocalStack compatibility alias) |
| `MINISTACK_HOST` | `localhost` | Hostname used in response URLs (SQS queues, SNS subscriptions, API Gateway endpoints, Lambda layers) |
+| `MINISTACK_ACCOUNT_ID` | `000000000000` | Default AWS account ID. Overridden per-request when `AWS_ACCESS_KEY_ID` is a 12-digit number (see [Multi-Tenancy](#multi-tenancy)) |
| `MINISTACK_REGION` | `us-east-1` | AWS region reported in ARNs and service responses across all services |
| `LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING`, `ERROR` |
| `S3_PERSIST` | `0` | Set `1` to persist S3 objects to disk |
diff --git a/ministack/app.py b/ministack/app.py
index 0f702072..151fe417 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -38,7 +38,8 @@ _S3_VHOST_RE = re.compile(
_S3_VHOST_EXCLUDE_RE = re.compile(r"\.(execute-api|alb|emr|efs|elasticache|s3-control)\.")
from ministack.core.persistence import PERSIST_STATE, load_state, save_all
-from ministack.core.router import detect_service, extract_account_id, extract_region
+from ministack.core.responses import set_request_account_id
+from ministack.core.router import detect_service, extract_access_key_id, extract_account_id, extract_region
from ministack.services import (
acm,
alb,
@@ -251,6 +252,12 @@ async def app(scope, receive, send):
request_id = str(uuid.uuid4())
+ # Set per-request account ID from credentials (multi-tenancy support).
+ # If the access key is a 12-digit number, it becomes the account ID.
+ _access_key = extract_access_key_id(headers)
+ if _access_key:
+ set_request_account_id(_access_key)
+
# Lambda layer content download: /_ministack/lambda-layers/{name}/{ver}/content
if path.startswith("/_ministack/lambda-layers/") and method == "GET":
lp = path.split("/") # ['', '_ministack', 'lambda-layers', name, ver, 'content']
diff --git a/ministack/core/responses.py b/ministack/core/responses.py
index 0d08057b..4a63d0ca 100644
--- a/ministack/core/responses.py
+++ b/ministack/core/responses.py
@@ -4,12 +4,41 @@ Handles XML responses (S3, SQS, SNS, IAM, STS, CloudWatch) and
JSON responses (DynamoDB, Lambda, SecretsManager, CloudWatch Logs).
"""
+import contextvars
import hashlib
import json
+import os
+import re
import uuid
from datetime import datetime, timezone
from xml.etree.ElementTree import Element, SubElement, tostring
+# Request-scoped account ID for multi-tenancy.
+# Set per-request in app.py from the Authorization header.
+_request_account_id: contextvars.ContextVar[str] = contextvars.ContextVar(
+ "_request_account_id",
+ default=os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000"),
+)
+
+_12_DIGIT_RE = re.compile(r"^\d{12}$")
+
+
+def set_request_account_id(access_key_id: str) -> None:
+ """Set the account ID for the current request from the access key.
+ If the access key is a 12-digit number, use it as the account ID.
+ Otherwise fall back to the MINISTACK_ACCOUNT_ID env var or 000000000000."""
+ if access_key_id and _12_DIGIT_RE.match(access_key_id):
+ _request_account_id.set(access_key_id)
+ else:
+ _request_account_id.set(
+ os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
+ )
+
+
+def get_account_id() -> str:
+ """Return the account ID for the current request."""
+ return _request_account_id.get()
+
def xml_response(root_tag: str, namespace: str, children: dict, status: int = 200) -> tuple:
"""Build an AWS-style XML response."""
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 4dbda57c..cdc91a0f 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -476,6 +476,18 @@ def extract_region(headers: dict) -> str:
return os.environ.get("MINISTACK_REGION", "us-east-1")
+def extract_access_key_id(headers: dict) -> str:
+ """Extract the AWS access key ID from the Authorization header."""
+ auth = headers.get("authorization", "")
+ if auth:
+ match = re.search(r"Credential=([^/]+)/", auth)
+ if match:
+ return match.group(1)
+ return ""
+
+
def extract_account_id(headers: dict) -> str:
- """Extract or generate account ID."""
- return os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
+ """Extract account ID from credentials or env var.
+ If the access key is a 12-digit number, use it as the account ID."""
+ from ministack.core.responses import get_account_id
+ return get_account_id()
diff --git a/ministack/services/acm.py b/ministack/services/acm.py
index 71a7fbed..db1cb33b 100644
--- a/ministack/services/acm.py
+++ b/ministack/services/acm.py
@@ -15,11 +15,10 @@ import time
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import error_response_json, json_response, new_uuid, now_iso
+from ministack.core.responses import get_account_id, error_response_json, json_response, new_uuid, now_iso
logger = logging.getLogger("acm")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
_certificates: dict = {} # arn -> certificate dict
@@ -43,7 +42,7 @@ def _future_iso(seconds):
def _cert_arn():
- return f"arn:aws:acm:{REGION}:{ACCOUNT_ID}:certificate/{new_uuid()}"
+ return f"arn:aws:acm:{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 5ceb20da..07603586 100644
--- a/ministack/services/alb.py
+++ b/ministack/services/alb.py
@@ -27,11 +27,10 @@ import time
from urllib.parse import parse_qs
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import new_uuid
+from ministack.core.responses import get_account_id, new_uuid
logger = logging.getLogger("alb")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
NS = "http://elasticloadbalancing.amazonaws.com/doc/2015-12-01/"
@@ -345,7 +344,7 @@ 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}:{ACCOUNT_ID}:loadbalancer/app/{name}/{lid}"
+ arn = f"arn:aws:elasticloadbalancing:{REGION}:{get_account_id()}:loadbalancer/app/{name}/{lid}"
lb = {
"LoadBalancerArn": arn,
"LoadBalancerName": name,
@@ -433,7 +432,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}:{ACCOUNT_ID}:targetgroup/{name}/{tid}"
+ arn = f"arn:aws:elasticloadbalancing:{REGION}:{get_account_id()}:targetgroup/{name}/{tid}"
tg = {
"TargetGroupArn": arn,
"TargetGroupName": name,
@@ -556,7 +555,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}:{ACCOUNT_ID}"
+ l_arn = (f"arn:aws:elasticloadbalancing:{REGION}:{get_account_id()}"
f":listener/app/{lb_name}/{lb_id}/{lid}")
actions = _parse_actions(params, "DefaultActions")
for action in actions:
@@ -574,7 +573,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}:{ACCOUNT_ID}"
+ rule_arn = (f"arn:aws:elasticloadbalancing:{REGION}:{get_account_id()}"
f":listener-rule/app/{lb_name}/{lb_id}/{lid}/{rule_id}")
_rules[rule_arn] = {
"RuleArn": rule_arn, "ListenerArn": l_arn,
@@ -636,7 +635,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}:{ACCOUNT_ID}"
+ rule_arn = (f"arn:aws:elasticloadbalancing:{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 4c925d2d..cb92ce4c 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -49,14 +49,13 @@ import time
import urllib.error
import urllib.request
-from ministack.core.responses import error_response_json, new_uuid
+from ministack.core.responses import get_account_id, error_response_json, new_uuid
_HOST = os.environ.get("MINISTACK_HOST", "localhost")
_PORT = os.environ.get("GATEWAY_PORT", "4566")
logger = logging.getLogger("apigateway")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# ---- Module-level state ----
@@ -343,7 +342,7 @@ async def _invoke_lambda_proxy(integration, api_id, stage, path, method, headers
"headers": dict(headers),
"queryStringParameters": qs,
"requestContext": {
- "accountId": ACCOUNT_ID,
+ "accountId": get_account_id(),
"apiId": api_id,
"domainName": f"{api_id}.execute-api.{_HOST}",
"http": {
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 4d3d4586..a184c3d1 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 new_uuid
+from ministack.core.responses import get_account_id, new_uuid
def _now_unix():
@@ -88,7 +88,6 @@ def _now_unix():
logger = logging.getLogger("apigateway_v1")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# ---- Module-level state ----
@@ -637,7 +636,7 @@ async def _invoke_lambda_proxy_v1(integration, api_id, stage_name, stage, resour
"pathParameters": path_params or None,
"stageVariables": stage.get("variables") or None,
"requestContext": {
- "accountId": ACCOUNT_ID,
+ "accountId": get_account_id(),
"resourceId": resource["id"],
"stage": stage_name,
"requestId": request_id,
diff --git a/ministack/services/appsync.py b/ministack/services/appsync.py
index 9febffb6..f5a865e8 100644
--- a/ministack/services/appsync.py
+++ b/ministack/services/appsync.py
@@ -25,11 +25,10 @@ import re
import time
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import error_response_json, json_response, new_uuid
+from ministack.core.responses import get_account_id, error_response_json, json_response, new_uuid
logger = logging.getLogger("appsync")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# ---------------------------------------------------------------------------
@@ -65,7 +64,7 @@ def _now():
def _api_arn(api_id):
- return f"arn:aws:appsync:{REGION}:{ACCOUNT_ID}:apis/{api_id}"
+ return f"arn:aws:appsync:{REGION}:{get_account_id()}:apis/{api_id}"
def _json(status, body):
diff --git a/ministack/services/athena.py b/ministack/services/athena.py
index 17683809..d1aa0ed0 100644
--- a/ministack/services/athena.py
+++ b/ministack/services/athena.py
@@ -22,11 +22,10 @@ import threading
import time
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import error_response_json, json_response, new_uuid
+from ministack.core.responses import get_account_id, error_response_json, json_response, new_uuid
logger = logging.getLogger("athena")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
S3_DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/ministack-data/s3")
ATHENA_ENGINE = os.environ.get("ATHENA_ENGINE", "auto") # "auto" | "duckdb" | "mock"
@@ -133,11 +132,11 @@ _DUCKDB_TYPE_MAP = {
def _arn_workgroup(name):
- return f"arn:aws:athena:{REGION}:{ACCOUNT_ID}:workgroup/{name}"
+ return f"arn:aws:athena:{REGION}:{get_account_id()}:workgroup/{name}"
def _arn_datacatalog(name):
- return f"arn:aws:athena:{REGION}:{ACCOUNT_ID}:datacatalog/{name}"
+ return f"arn:aws:athena:{REGION}:{get_account_id()}:datacatalog/{name}"
async def handle_request(method, path, headers, body, query_params):
diff --git a/ministack/services/cloudformation/__init__.py b/ministack/services/cloudformation/__init__.py
index fc22cd51..7279b540 100644
--- a/ministack/services/cloudformation/__init__.py
+++ b/ministack/services/cloudformation/__init__.py
@@ -15,7 +15,6 @@ from urllib.parse import parse_qs
logger = logging.getLogger("cloudformation")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# In-memory state (shared across all submodules)
@@ -63,3 +62,4 @@ def reset():
# Must be last — handlers imports from this module
from .handlers import _ACTION_HANDLERS, _validate_template # noqa: E402
+from ministack.core.responses import get_account_id
diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.py
index cc2279d3..665db39f 100644
--- a/ministack/services/cloudformation/changesets.py
+++ b/ministack/services/cloudformation/changesets.py
@@ -7,15 +7,15 @@ import copy
import json
import logging
-from ministack.core.responses import new_uuid, now_iso
+from ministack.core.responses import get_account_id, new_uuid, now_iso
from .engine import (
_evaluate_conditions, _parse_template, _resolve_parameters,
_resolve_refs, _NO_VALUE,
)
from .stacks import _add_event, _deploy_stack_async, _diff_resources
-from .provisioners import ACCOUNT_ID, REGION
-from .helpers import _xml, _error, _p, _esc, _extract_members, CFN_NS
+from .provisioners import REGION
+from .helpers import _xml, _error, _p, _esc, _extract_members, _resolve_template, CFN_NS
logger = logging.getLogger("cloudformation")
@@ -45,10 +45,9 @@ def _create_change_set(params):
if not cs_name:
return _error("ValidationError", "ChangeSetName is required")
- template_body = _p(params, "TemplateBody")
- if _p(params, "TemplateURL"):
- return _error("ValidationError",
- "TemplateURL is not supported; use TemplateBody")
+ template_body, resolve_err = _resolve_template(params)
+ if resolve_err:
+ return resolve_err
provided_params = _extract_members(params, "Parameters")
tags = _extract_members(params, "Tags")
@@ -62,11 +61,11 @@ def _create_change_set(params):
return _error("AlreadyExistsException",
f"Stack [{stack_name}] already exists")
if not template_body:
- return _error("ValidationError", "TemplateBody is required")
+ return _error("ValidationError", "TemplateBody or TemplateURL is required")
# Create a placeholder stack in REVIEW_IN_PROGRESS
stack_id = (
- f"arn:aws:cloudformation:{REGION}:{ACCOUNT_ID}:"
+ f"arn:aws:cloudformation:{REGION}:{get_account_id()}:"
f"stack/{stack_name}/{new_uuid()}"
)
stack = {
@@ -112,7 +111,7 @@ def _create_change_set(params):
changes = _diff_resources(old_template, template)
cs_id = (
- f"arn:aws:cloudformation:{REGION}:{ACCOUNT_ID}:"
+ f"arn:aws:cloudformation:{REGION}:{get_account_id()}:"
f"changeSet/{cs_name}/{new_uuid()}"
)
diff --git a/ministack/services/cloudformation/engine.py b/ministack/services/cloudformation/engine.py
index c6c5ec17..087de5a0 100644
--- a/ministack/services/cloudformation/engine.py
+++ b/ministack/services/cloudformation/engine.py
@@ -12,14 +12,13 @@ from collections import defaultdict
import yaml
-from ministack.core.responses import new_uuid
+from ministack.core.responses import get_account_id, new_uuid
# Sentinel for AWS::NoValue
_NO_VALUE = object()
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
-# Note: ACCOUNT_ID/REGION duplicated here to keep engine.py free of __init__ imports (avoids circular deps)
+# Note: get_account_id()/REGION duplicated here to keep engine.py free of __init__ imports (avoids circular deps)
# ===========================================================================
@@ -254,7 +253,7 @@ def _resolve_refs(value, resources, params, conditions, mappings,
"AWS::StackName": stack_name,
"AWS::StackId": stack_id,
"AWS::Region": REGION,
- "AWS::AccountId": ACCOUNT_ID,
+ "AWS::AccountId": get_account_id(),
"AWS::NoValue": _NO_VALUE,
"AWS::URLSuffix": "amazonaws.com",
"AWS::Partition": "aws",
@@ -320,7 +319,7 @@ def _resolve_refs(value, resources, params, conditions, mappings,
"AWS::StackName": stack_name,
"AWS::StackId": stack_id,
"AWS::Region": REGION,
- "AWS::AccountId": ACCOUNT_ID,
+ "AWS::AccountId": get_account_id(),
"AWS::URLSuffix": "amazonaws.com",
"AWS::Partition": "aws",
}
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index e415b80b..09b8a097 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -7,15 +7,15 @@ import copy
import json
import logging
-from ministack.core.responses import new_uuid, now_iso
+from ministack.core.responses import get_account_id, new_uuid, now_iso
from .engine import (
_evaluate_conditions, _parse_template, _resolve_parameters,
_resolve_refs, _NO_VALUE,
)
from .stacks import _add_event, _deploy_stack_async, _delete_stack_async, _diff_resources
-from .provisioners import _provision_resource, ACCOUNT_ID, REGION
-from .helpers import _xml, _error, _p, _esc, _extract_members, _extract_stack_status_filters, CFN_NS
+from .provisioners import _provision_resource, 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,
_delete_change_set, _list_change_sets,
@@ -32,14 +32,11 @@ def _create_stack(params):
if not stack_name:
return _error("ValidationError", "StackName is required")
- # Check TemplateURL (not supported)
- if _p(params, "TemplateURL"):
- return _error("ValidationError",
- "TemplateURL is not supported; use TemplateBody")
-
- template_body = _p(params, "TemplateBody")
+ template_body, resolve_err = _resolve_template(params)
+ if resolve_err:
+ return resolve_err
if not template_body:
- return _error("ValidationError", "TemplateBody is required")
+ return _error("ValidationError", "TemplateBody or TemplateURL is required")
# Check stack name uniqueness (active stacks)
existing = _stacks.get(stack_name)
@@ -64,7 +61,7 @@ def _create_stack(params):
return _error("ValidationError", str(exc))
stack_id = (
- f"arn:aws:cloudformation:{REGION}:{ACCOUNT_ID}:"
+ f"arn:aws:cloudformation:{REGION}:{get_account_id()}:"
f"stack/{stack_name}/{new_uuid()}"
)
@@ -412,16 +409,15 @@ def _update_stack(params):
f"Stack [{stack_name}] is in {current_status} state "
f"and cannot be updated")
- template_body = _p(params, "TemplateBody")
- if _p(params, "TemplateURL"):
- return _error("ValidationError",
- "TemplateURL is not supported; use TemplateBody")
+ template_body, resolve_err = _resolve_template(params)
+ if resolve_err:
+ return resolve_err
if not template_body:
# Use previous template if UsePreviousTemplate
if _p(params, "UsePreviousTemplate", "false").lower() == "true":
template_body = stack.get("_template_body", "{}")
else:
- return _error("ValidationError", "TemplateBody is required")
+ return _error("ValidationError", "TemplateBody or TemplateURL is required")
try:
template = _parse_template(template_body)
@@ -531,10 +527,12 @@ def _list_exports(params):
def _get_template_summary(params):
from ministack.services.cloudformation import _stacks
- template_body = _p(params, "TemplateBody")
+ template_body, resolve_err = _resolve_template(params)
+ if resolve_err:
+ return resolve_err
stack_name = _p(params, "StackName")
- if stack_name:
+ if stack_name and not template_body:
stack = _stacks.get(stack_name)
if not stack:
return _error("ValidationError",
@@ -543,7 +541,7 @@ def _get_template_summary(params):
if not template_body:
return _error("ValidationError",
- "Either TemplateBody or StackName must be provided")
+ "Either TemplateBody, TemplateURL, or StackName must be provided")
try:
template = _parse_template(template_body)
diff --git a/ministack/services/cloudformation/helpers.py b/ministack/services/cloudformation/helpers.py
index 811c4c77..94e67b30 100644
--- a/ministack/services/cloudformation/helpers.py
+++ b/ministack/services/cloudformation/helpers.py
@@ -2,10 +2,14 @@
CloudFormation helpers — XML response formatting and parameter extraction utilities.
"""
+import logging
from html import escape as _esc
+from urllib.parse import urlparse
from ministack.core.responses import new_uuid
+logger = logging.getLogger("cloudformation")
+
CFN_NS = "http://cloudformation.amazonaws.com/doc/2010-05-08/"
@@ -55,6 +59,43 @@ def _extract_members(params, prefix):
return result
+def _resolve_template(params):
+ """Resolve TemplateBody or TemplateURL to a template string.
+ If TemplateURL is provided, fetch the template from S3.
+ Returns (template_body, error_tuple) — error_tuple is None on success."""
+ template_body = _p(params, "TemplateBody")
+ template_url = _p(params, "TemplateURL")
+
+ if template_body:
+ return template_body, None
+
+ if template_url:
+ try:
+ from ministack.services import s3 as _s3
+ parsed = urlparse(template_url)
+ # Support formats:
+ # http://localhost:4566/bucket/key
+ # https://s3.amazonaws.com/bucket/key
+ # https://bucket.s3.amazonaws.com/key
+ path = parsed.path.lstrip("/")
+ parts = path.split("/", 1)
+ if len(parts) < 2:
+ return None, _error("ValidationError",
+ f"Invalid TemplateURL: {template_url}")
+ bucket_name, key = parts[0], parts[1]
+ obj_data = _s3._get_object_data(bucket_name, key)
+ if obj_data is None:
+ return None, _error("ValidationError",
+ f"Template not found at {template_url}")
+ return obj_data.decode("utf-8"), None
+ except Exception as e:
+ logger.warning("Failed to fetch TemplateURL %s: %s", template_url, e)
+ return None, _error("ValidationError",
+ f"Error fetching TemplateURL: {e}")
+
+ return None, None # neither provided
+
+
def _extract_stack_status_filters(params):
"""Extract StackStatusFilter.member.N values."""
filters = []
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 3c18e136..23c7d71b 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 new_uuid, now_iso
+from ministack.core.responses import get_account_id, new_uuid, now_iso
import ministack.services.s3 as _s3
import ministack.services.sqs as _sqs
@@ -35,7 +35,6 @@ import ministack.services.ecs as _ecs
logger = logging.getLogger("cloudformation")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
@@ -138,8 +137,8 @@ def _s3_delete(physical_id, props):
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}/{ACCOUNT_ID}/{name}"
- arn = f"arn:aws:sqs:{REGION}:{ACCOUNT_ID}:{name}"
+ url = f"http://{_sqs.DEFAULT_HOST}:{_sqs.DEFAULT_PORT}/{get_account_id()}/{name}"
+ arn = f"arn:aws:sqs:{REGION}:{get_account_id()}:{name}"
now_ts = str(int(time.time()))
attributes = {
@@ -182,7 +181,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}:{ACCOUNT_ID}:{name}"
+ arn = f"arn:aws:sns:{REGION}:{get_account_id()}:{name}"
default_policy = json.dumps({
"Version": "2008-10-17",
"Id": "__default_policy_ID",
@@ -200,7 +199,7 @@ def _sns_create(logical_id, props, stack_name):
"attributes": {
"TopicArn": arn,
"DisplayName": props.get("DisplayName", name),
- "Owner": ACCOUNT_ID,
+ "Owner": get_account_id(),
"Policy": default_policy,
"SubscriptionsConfirmed": "0",
"SubscriptionsPending": "0",
@@ -232,7 +231,7 @@ def _sns_create(logical_id, props, stack_name):
"protocol": protocol,
"endpoint": endpoint,
"confirmed": protocol not in ("http", "https"),
- "owner": ACCOUNT_ID,
+ "owner": get_account_id(),
"attributes": {},
}
_sns._topics[arn]["subscriptions"].append(sub)
@@ -266,7 +265,7 @@ def _sns_sub_create(logical_id, props, stack_name):
"protocol": protocol,
"endpoint": endpoint,
"confirmed": protocol not in ("http", "https"),
- "owner": ACCOUNT_ID,
+ "owner": get_account_id(),
"attributes": {},
}
topic["subscriptions"].append(sub)
@@ -288,7 +287,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}:{ACCOUNT_ID}:table/{name}"
+ arn = f"arn:aws:dynamodb:{REGION}:{get_account_id()}:table/{name}"
key_schema = props.get("KeySchema", [])
pk_name = None
@@ -363,10 +362,10 @@ def _zip_inline(source: str | None, handler: str) -> bytes | None:
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}:{ACCOUNT_ID}:function:{name}"
+ arn = f"arn:aws:lambda:{REGION}:{get_account_id()}:function:{name}"
runtime = props.get("Runtime", "python3.9")
handler = props.get("Handler", "index.handler")
- role = props.get("Role", f"arn:aws:iam::{ACCOUNT_ID}:role/dummy-role")
+ role = props.get("Role", f"arn:aws:iam::{get_account_id()}:role/dummy-role")
timeout = int(props.get("Timeout", 3))
memory = int(props.get("MemorySize", 128))
env_vars = props.get("Environment", {}).get("Variables", {})
@@ -420,7 +419,7 @@ def _lambda_delete(physical_id, props):
def _iam_role_create(logical_id, props, stack_name):
name = props.get("RoleName") or _physical_name(stack_name, logical_id, max_len=64)
- arn = f"arn:aws:iam::{ACCOUNT_ID}:role/{name}"
+ arn = f"arn:aws:iam::{get_account_id()}:role/{name}"
role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()
assume_doc = props.get("AssumeRolePolicyDocument", {})
if isinstance(assume_doc, dict):
@@ -475,7 +474,7 @@ def _iam_role_delete(physical_id, props):
def _iam_policy_create(logical_id, props, stack_name):
name = props.get("PolicyName") or _physical_name(stack_name, logical_id, max_len=128)
path = props.get("Path", "/")
- arn = f"arn:aws:iam::{ACCOUNT_ID}:policy{path}{name}"
+ arn = f"arn:aws:iam::{get_account_id()}:policy{path}{name}"
pol_doc = props.get("PolicyDocument", {})
if isinstance(pol_doc, dict):
pol_doc = json.dumps(pol_doc)
@@ -524,7 +523,7 @@ def _iam_policy_delete(physical_id, props):
def _iam_ip_create(logical_id, props, stack_name):
name = props.get("InstanceProfileName") or _physical_name(stack_name, logical_id, max_len=128)
path = props.get("Path", "/")
- arn = f"arn:aws:iam::{ACCOUNT_ID}:instance-profile{path}{name}"
+ arn = f"arn:aws:iam::{get_account_id()}:instance-profile{path}{name}"
ip_id = new_uuid().replace("-", "")[:21].upper()
roles = []
@@ -562,7 +561,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}:{ACCOUNT_ID}:parameter{name}"
+ param_arn = f"arn:aws:ssm:{REGION}:{get_account_id()}:parameter{name}"
_ssm._parameters[name] = {
"Name": name,
@@ -588,7 +587,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}:{ACCOUNT_ID}:log-group:{name}:*"
+ arn = f"arn:aws:logs:{REGION}:{get_account_id()}:log-group:{name}:*"
retention = props.get("RetentionInDays")
_cw_logs._log_groups[name] = {
@@ -612,7 +611,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 = f"{name}|{bus}"
- arn = f"arn:aws:events:{REGION}:{ACCOUNT_ID}:rule/{bus}/{name}"
+ arn = f"arn:aws:events:{REGION}:{get_account_id()}:rule/{bus}/{name}"
_eb._rules[key] = {
"Name": name,
@@ -702,7 +701,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}:{ACCOUNT_ID}:function:{func_name}:1"
+ ver_arn = f"arn:aws:lambda:{REGION}:{get_account_id()}:function:{func_name}:1"
return ver_arn, {"Version": "1"}
@@ -868,7 +867,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}:{ACCOUNT_ID}:function:{func_name}"
+ func_arn = func["config"]["FunctionArn"] if func else f"arn:aws:lambda:{REGION}:{get_account_id()}:function:{func_name}"
esm = {
"UUID": esm_id,
@@ -905,7 +904,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}:{ACCOUNT_ID}:function:{func_name}:{alias_name}",
+ "AliasArn": f"arn:aws:lambda:{REGION}:{get_account_id()}:function:{func_name}:{alias_name}",
"Name": alias_name,
"FunctionVersion": func_version,
"Description": props.get("Description", ""),
@@ -917,7 +916,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}:{ACCOUNT_ID}:function:{func_name}:{alias_name}"
+ alias_arn = f"arn:aws:lambda:{REGION}:{get_account_id()}:function:{func_name}:{alias_name}"
return alias_arn, {"AliasArn": alias_arn}
@@ -985,7 +984,7 @@ 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}:{ACCOUNT_ID}:apis/{api_id}"
+ arn = f"arn:aws:appsync:{REGION}:{get_account_id()}:apis/{api_id}"
now = _time.time()
_appsync._apis[api_id] = {
"apiId": api_id, "name": name, "authenticationType": auth_type,
@@ -1023,9 +1022,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}:{ACCOUNT_ID}:apis/{api_id}/datasources/{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:{REGION}:{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}"}
def _appsync_ds_delete(physical_id, props):
@@ -1042,7 +1041,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}:{ACCOUNT_ID}:apis/{api_id}/types/{type_name}/resolvers/{field_name}",
+ "resolverArn": f"arn:aws:appsync:{REGION}:{get_account_id()}:apis/{api_id}/types/{type_name}/resolvers/{field_name}",
}
if props.get("RequestMappingTemplate"):
resolver["requestMappingTemplate"] = props["RequestMappingTemplate"]
@@ -1076,7 +1075,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}:{ACCOUNT_ID}:apis/{api_id}/apikeys/{key_id}"}
+ return key_id, {"ApiKey": key_id, "Arn": f"arn:aws:appsync:{REGION}:{get_account_id()}:apis/{api_id}/apikeys/{key_id}"}
def _appsync_apikey_delete(physical_id, props):
@@ -1111,7 +1110,7 @@ def _sm_secret_create(logical_id, props, stack_name):
else:
secret_string = generated
- arn = f"arn:aws:secretsmanager:{REGION}:{ACCOUNT_ID}:secret:{name}-{new_uuid()[:6]}"
+ arn = f"arn:aws:secretsmanager:{REGION}:{get_account_id()}:secret:{name}-{new_uuid()[:6]}"
import time as _time
_sm._secrets[name] = {
"ARN": arn, "Name": name, "Description": props.get("Description", ""),
@@ -1278,12 +1277,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}:{ACCOUNT_ID}:repository/{name}"
+ arn = f"arn:aws:ecr:{REGION}:{get_account_id()}:repository/{name}"
_ecr._repositories[name] = {
"repositoryName": name,
"repositoryArn": arn,
- "registryId": ACCOUNT_ID,
- "repositoryUri": f"{ACCOUNT_ID}.dkr.ecr.{REGION}.amazonaws.com/{name}",
+ "registryId": get_account_id(),
+ "repositoryUri": f"{get_account_id()}.dkr.ecr.{REGION}.amazonaws.com/{name}",
"createdAt": __import__("time").time(),
"imageTagMutability": props.get("ImageTagMutability", "MUTABLE"),
"imageScanningConfiguration": props.get("ImageScanningConfiguration", {"scanOnPush": False}),
@@ -1301,7 +1300,7 @@ def _ecr_repo_delete(physical_id, props):
def _iam_managed_policy_create(logical_id, props, stack_name):
name = props.get("ManagedPolicyName", f"{stack_name}-{logical_id}")
- arn = f"arn:aws:iam::{ACCOUNT_ID}:policy/{name}"
+ arn = f"arn:aws:iam::{get_account_id()}:policy/{name}"
policy_doc = props.get("PolicyDocument", {})
_iam_sts._policies[arn] = {
"PolicyName": name,
@@ -1327,7 +1326,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}:{ACCOUNT_ID}:key/{key_id}"
+ arn = f"arn:aws:kms:{REGION}:{get_account_id()}:key/{key_id}"
_kms._keys[key_id] = {
"KeyId": key_id,
"Arn": arn,
@@ -1376,12 +1375,12 @@ def _ec2_vpc_create(logical_id, props, stack_name):
{"RuleNumber": 100, "Protocol": "-1", "RuleAction": "allow", "Egress": True, "CidrBlock": "0.0.0.0/0"},
{"RuleNumber": 32767, "Protocol": "-1", "RuleAction": "deny", "Egress": True, "CidrBlock": "0.0.0.0/0"},
],
- "Associations": [], "Tags": [], "OwnerId": ACCOUNT_ID,
+ "Associations": [], "Tags": [], "OwnerId": get_account_id(),
}
rtb_id = "rtb-" + "".join(random.choices(string.hexdigits[:16], k=17))
rtb_assoc_id = "rtbassoc-" + "".join(random.choices(string.hexdigits[:16], k=17))
_ec2._route_tables[rtb_id] = {
- "RouteTableId": rtb_id, "VpcId": vpc_id, "OwnerId": ACCOUNT_ID,
+ "RouteTableId": rtb_id, "VpcId": vpc_id, "OwnerId": get_account_id(),
"Routes": [{"DestinationCidrBlock": cidr, "GatewayId": "local", "State": "active", "Origin": "CreateRouteTable"}],
"Associations": [{"RouteTableAssociationId": rtb_assoc_id, "RouteTableId": rtb_id, "Main": True,
"AssociationState": {"State": "associated"}}],
@@ -1389,17 +1388,17 @@ def _ec2_vpc_create(logical_id, props, stack_name):
sg_id = _ec2._new_sg_id()
_ec2._security_groups[sg_id] = {
"GroupId": sg_id, "GroupName": "default", "Description": "default VPC security group",
- "VpcId": vpc_id, "OwnerId": ACCOUNT_ID, "IpPermissions": [],
+ "VpcId": vpc_id, "OwnerId": get_account_id(), "IpPermissions": [],
"IpPermissionsEgress": [{"IpProtocol": "-1", "IpRanges": [{"CidrIp": "0.0.0.0/0"}],
"Ipv6Ranges": [], "PrefixListIds": [], "UserIdGroupPairs": []}],
}
_ec2._vpcs[vpc_id] = {
"VpcId": vpc_id, "CidrBlock": cidr, "State": "available", "IsDefault": False,
"DhcpOptionsId": "dopt-00000001", "InstanceTenancy": props.get("InstanceTenancy", "default"),
- "OwnerId": ACCOUNT_ID, "DefaultNetworkAclId": acl_id,
+ "OwnerId": get_account_id(), "DefaultNetworkAclId": acl_id,
"DefaultSecurityGroupId": sg_id, "MainRouteTableId": rtb_id,
}
- arn = f"arn:aws:ec2:{REGION}:{ACCOUNT_ID}:vpc/{vpc_id}"
+ arn = f"arn:aws:ec2:{REGION}:{get_account_id()}:vpc/{vpc_id}"
return vpc_id, {"VpcId": vpc_id, "DefaultSecurityGroup": sg_id, "DefaultNetworkAcl": acl_id}
@@ -1422,7 +1421,7 @@ def _ec2_subnet_create(logical_id, props, stack_name):
"AvailableIpAddressCount": 251,
"DefaultForAz": False,
"MapPublicIpOnLaunch": props.get("MapPublicIpOnLaunch", False),
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
}
return subnet_id, {"SubnetId": subnet_id, "AvailabilityZone": az}
@@ -1441,7 +1440,7 @@ def _ec2_sg_create(logical_id, props, stack_name):
"GroupName": name,
"Description": desc,
"VpcId": vpc_id,
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
"IpPermissions": [],
"IpPermissionsEgress": [
{"IpProtocol": "-1", "IpRanges": [{"CidrIp": "0.0.0.0/0"}],
@@ -1465,7 +1464,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}:{ACCOUNT_ID}:security-group/{sg_id}"
+ arn = f"arn:aws:ec2:{REGION}:{get_account_id()}:security-group/{sg_id}"
return sg_id, {"GroupId": sg_id, "VpcId": vpc_id, "Arn": arn}
@@ -1478,7 +1477,7 @@ def _ec2_igw_create(logical_id, props, stack_name):
igw_id = "igw-" + "".join(random.choices(string.hexdigits[:16], k=17))
_ec2._internet_gateways[igw_id] = {
"InternetGatewayId": igw_id,
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
"Attachments": [],
}
return igw_id, {"InternetGatewayId": igw_id}
@@ -1513,7 +1512,7 @@ def _ec2_rtb_create(logical_id, props, stack_name):
_ec2._route_tables[rtb_id] = {
"RouteTableId": rtb_id,
"VpcId": vpc_id,
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
"Routes": [
{"DestinationCidrBlock": _ec2._vpcs.get(vpc_id, {}).get("CidrBlock", "10.0.0.0/16"),
"GatewayId": "local", "State": "active", "Origin": "CreateRouteTable"},
@@ -1576,7 +1575,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}:{ACCOUNT_ID}:cluster/{name}"
+ arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:cluster/{name}"
_ecs._clusters[name] = {
"clusterArn": arn,
"clusterName": name,
@@ -1601,7 +1600,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}:{ACCOUNT_ID}:task-definition/{td_key}"
+ arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:task-definition/{td_key}"
td = {
"taskDefinitionArn": arn,
"family": family,
@@ -1629,11 +1628,11 @@ def _ecs_task_def_delete(physical_id, props):
def _ecs_service_create(logical_id, props, stack_name):
name = props.get("ServiceName", f"{stack_name}-{logical_id}")
cluster = props.get("Cluster", "default")
- arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:service/{cluster}/{name}"
+ arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:service/{cluster}/{name}"
svc = {
"serviceArn": arn,
"serviceName": name,
- "clusterArn": f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:cluster/{cluster}",
+ "clusterArn": f"arn:aws:ecs:{REGION}:{get_account_id()}:cluster/{cluster}",
"taskDefinition": props.get("TaskDefinition", ""),
"desiredCount": props.get("DesiredCount", 1),
"runningCount": 0,
@@ -1754,4 +1753,6 @@ _RESOURCE_HANDLERS = {
"AWS::ECS::TaskDefinition": {"create": _ecs_task_def_create, "delete": _ecs_task_def_delete},
"AWS::ECS::Service": {"create": _ecs_service_create, "delete": _ecs_service_delete},
"AWS::EC2::LaunchTemplate": {"create": _ec2_launch_template_create, "delete": _ec2_launch_template_delete},
+ # CDK metadata — safe to ignore
+ "AWS::CDK::Metadata": {"create": lambda lid, props, sn: (f"CDKMetadata-{lid}", {}), "delete": lambda pid, props: None},
}
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index a7fac699..edb582b0 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -8,13 +8,13 @@ import json
import logging
import time
-from ministack.core.responses import new_uuid, now_iso
+from ministack.core.responses import get_account_id, new_uuid, now_iso
from .engine import (
_evaluate_conditions, _parse_template, _resolve_parameters,
_resolve_refs, _topological_sort, _NO_VALUE,
)
-from .provisioners import _provision_resource, _delete_resource, ACCOUNT_ID, REGION
+from .provisioners import _provision_resource, _delete_resource, REGION
logger = logging.getLogger("cloudformation")
diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.py
index ae813bc3..2ee36b1a 100644
--- a/ministack/services/cloudfront.py
+++ b/ministack/services/cloudfront.py
@@ -20,11 +20,10 @@ from defusedxml.ElementTree import fromstring
from xml.etree.ElementTree import Element, SubElement, tostring
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import new_uuid
+from ministack.core.responses import get_account_id, new_uuid
logger = logging.getLogger("cloudfront")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
NS = "http://cloudfront.amazonaws.com/doc/2020-05-31/"
# ---------------------------------------------------------------------------
@@ -251,7 +250,7 @@ def _create_distribution(headers, body):
dist = {
"Id": dist_id,
- "ARN": f"arn:aws:cloudfront::{ACCOUNT_ID}:distribution/{dist_id}",
+ "ARN": f"arn:aws:cloudfront::{get_account_id()}:distribution/{dist_id}",
"Status": "Deployed",
"DomainName": f"{dist_id}.cloudfront.net",
"LastModifiedTime": now,
diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.py
index d8d27526..bc8830e4 100644
--- a/ministack/services/cloudwatch.py
+++ b/ministack/services/cloudwatch.py
@@ -21,11 +21,10 @@ 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 new_uuid
+from ministack.core.responses import get_account_id, new_uuid
logger = logging.getLogger("cloudwatch")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
TWO_WEEKS_SECONDS = 14 * 24 * 3600
@@ -677,7 +676,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}:{ACCOUNT_ID}:alarm:{name}",
+ "AlarmArn": f"arn:aws:cloudwatch:{REGION}:{get_account_id()}:alarm:{name}",
"AlarmDescription": cbor_data.get("AlarmDescription", ""),
"MetricName": cbor_data.get("MetricName"),
"Namespace": cbor_data.get("Namespace"),
@@ -731,7 +730,7 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):
oi += 1
alarm = {
"AlarmName": name,
- "AlarmArn": f"arn:aws:cloudwatch:{REGION}:{ACCOUNT_ID}:alarm:{name}",
+ "AlarmArn": f"arn:aws:cloudwatch:{REGION}:{get_account_id()}:alarm:{name}",
"AlarmDescription": _p(params, "AlarmDescription"),
"MetricName": _p(params, "MetricName"),
"Namespace": _p(params, "Namespace"),
@@ -815,7 +814,7 @@ def _put_composite_alarm(params, cbor_data, is_cbor, is_json=False):
_composite_alarms[name] = {
"AlarmName": name,
- "AlarmArn": f"arn:aws:cloudwatch:{REGION}:{ACCOUNT_ID}:alarm:{name}",
+ "AlarmArn": f"arn:aws:cloudwatch:{REGION}:{get_account_id()}:alarm:{name}",
"AlarmDescription": desc,
"AlarmRule": alarm_rule,
"StateValue": "INSUFFICIENT_DATA",
@@ -1028,7 +1027,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}:{ACCOUNT_ID}:alarm:{n}", None)
+ _resource_tags.pop(f"arn:aws:cloudwatch:{REGION}:{get_account_id()}:alarm:{n}", None)
if is_cbor:
return _cbor_ok({})
@@ -1224,7 +1223,7 @@ def _put_dashboard(params, cbor_data, is_cbor, is_json=False):
_dashboards[name] = {
"DashboardName": name,
"DashboardBody": body,
- "DashboardArn": f"arn:aws:cloudwatch::{ACCOUNT_ID}:dashboard/{name}",
+ "DashboardArn": f"arn:aws:cloudwatch::{get_account_id()}:dashboard/{name}",
"LastModified": time.time(),
"Size": len(body),
}
diff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.py
index 3ae00478..0b4322b9 100644
--- a/ministack/services/cloudwatch_logs.py
+++ b/ministack/services/cloudwatch_logs.py
@@ -22,11 +22,10 @@ import json
import logging
import time
-from ministack.core.responses import error_response_json, json_response, new_uuid
+from ministack.core.responses import get_account_id, error_response_json, json_response, new_uuid
logger = logging.getLogger("logs")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
from ministack.core.persistence import load_state, PERSIST_STATE
@@ -72,7 +71,7 @@ if _restored:
# ---------------------------------------------------------------------------
def _make_group_arn(name):
- return f"arn:aws:logs:{REGION}:{ACCOUNT_ID}:log-group:{name}:*"
+ return f"arn:aws:logs:{REGION}:{get_account_id()}:log-group:{name}:*"
def _resolve_group_by_arn(arn):
@@ -318,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}:{ACCOUNT_ID}:log-group:{group}:log-stream:{n}",
+ "arn": f"arn:aws:logs:{REGION}:{get_account_id()}:log-group:{group}:log-stream:{n}",
}
if s.get("firstEventTimestamp") is not None:
entry["firstEventTimestamp"] = s["firstEventTimestamp"]
@@ -702,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}:{ACCOUNT_ID}:destination:{name}"
+ dest_arn = f"arn:aws:logs:{REGION}:{get_account_id()}:destination:{name}"
_destinations[name] = {
"destinationName": name,
"targetArn": data.get("targetArn", ""),
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 8c1d322e..4867d3e3 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -55,7 +55,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 error_response_json, json_response, new_uuid
+from ministack.core.responses import get_account_id, error_response_json, json_response, new_uuid
logger = logging.getLogger("cognito")
@@ -125,7 +125,6 @@ def well_known_openid_configuration(pool_id: str, region: str | None = None):
}
return 200, {"Content-Type": "application/json"}, json.dumps(doc).encode()
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# ---------------------------------------------------------------------------
@@ -196,7 +195,7 @@ def _now_epoch() -> float:
def _pool_arn(pool_id: str) -> str:
- return f"arn:aws:cognito-idp:{REGION}:{ACCOUNT_ID}:userpool/{pool_id}"
+ return f"arn:aws:cognito-idp:{REGION}:{get_account_id()}:userpool/{pool_id}"
def _pool_id() -> str:
@@ -1561,7 +1560,7 @@ def _describe_user_pool_domain(data):
return json_response({
"DomainDescription": {
"UserPoolId": pid,
- "AWSAccountId": ACCOUNT_ID,
+ "AWSAccountId": get_account_id(),
"Domain": domain,
"S3Bucket": "",
"CloudFrontDistribution": f"{domain}.auth.{REGION}.amazoncognito.com",
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index 224732ce..c0b83ce9 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -20,6 +20,7 @@ from collections import defaultdict
from decimal import Decimal, InvalidOperation
from ministack.core.responses import (
+ get_account_id,
error_response_json,
json_response,
new_uuid,
@@ -28,7 +29,6 @@ from ministack.core.responses import (
logger = logging.getLogger("dynamodb")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
from ministack.core.persistence import load_state, PERSIST_STATE
@@ -227,11 +227,11 @@ def _create_table(data):
for gsi in gsis:
gsi.setdefault("IndexStatus", "ACTIVE")
gsi.setdefault("ProvisionedThroughput", {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5})
- gsi["IndexArn"] = f"arn:aws:dynamodb:{REGION}:{ACCOUNT_ID}:table/{name}/index/{gsi['IndexName']}"
+ gsi["IndexArn"] = f"arn:aws:dynamodb:{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}:{ACCOUNT_ID}:table/{name}/index/{lsi['IndexName']}"
+ lsi["IndexArn"] = f"arn:aws:dynamodb:{REGION}:{get_account_id()}:table/{name}/index/{lsi['IndexName']}"
lsi["IndexSizeBytes"] = 0
lsi["ItemCount"] = 0
@@ -246,7 +246,7 @@ def _create_table(data):
"CreationDateTime": time.time(),
"ItemCount": 0,
"TableSizeBytes": 0,
- "TableArn": f"arn:aws:dynamodb:{REGION}:{ACCOUNT_ID}:table/{name}",
+ "TableArn": f"arn:aws:dynamodb:{REGION}:{get_account_id()}:table/{name}",
"TableId": new_uuid(),
"GlobalSecondaryIndexes": gsis,
"LocalSecondaryIndexes": lsis,
@@ -311,7 +311,7 @@ def _update_table(data):
gsi_def = copy.deepcopy(update["Create"])
gsi_def.setdefault("IndexStatus", "ACTIVE")
gsi_def.setdefault("ProvisionedThroughput", {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5})
- gsi_def["IndexArn"] = f"arn:aws:dynamodb:{REGION}:{ACCOUNT_ID}:table/{name}/index/{gsi_def['IndexName']}"
+ gsi_def["IndexArn"] = f"arn:aws:dynamodb:{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 20b3d664..19e08a39 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -64,11 +64,10 @@ 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 new_uuid
+from ministack.core.responses import get_account_id, new_uuid
logger = logging.getLogger("ec2")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# ---------------------------------------------------------------------------
@@ -180,7 +179,7 @@ def _init_defaults():
"IsDefault": True,
"DhcpOptionsId": "dopt-00000001",
"InstanceTenancy": "default",
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
"DefaultNetworkAclId": _DEFAULT_ACL_ID,
"DefaultSecurityGroupId": _DEFAULT_SG_ID,
"MainRouteTableId": _DEFAULT_RTB_ID,
@@ -195,7 +194,7 @@ def _init_defaults():
"State": "available",
"DefaultForAz": True,
"MapPublicIpOnLaunch": True,
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
}
if _DEFAULT_SG_ID not in _security_groups:
_security_groups[_DEFAULT_SG_ID] = {
@@ -203,7 +202,7 @@ def _init_defaults():
"GroupName": "default",
"Description": "default VPC security group",
"VpcId": _DEFAULT_VPC_ID,
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
"IpPermissions": [],
"IpPermissionsEgress": [
{"IpProtocol": "-1", "IpRanges": [{"CidrIp": "0.0.0.0/0"}],
@@ -213,7 +212,7 @@ def _init_defaults():
if _DEFAULT_IGW_ID not in _internet_gateways:
_internet_gateways[_DEFAULT_IGW_ID] = {
"InternetGatewayId": _DEFAULT_IGW_ID,
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
"Attachments": [{"VpcId": _DEFAULT_VPC_ID, "State": "available"}],
}
default_rtb = "rtb-00000001"
@@ -221,7 +220,7 @@ def _init_defaults():
_route_tables[default_rtb] = {
"RouteTableId": default_rtb,
"VpcId": _DEFAULT_VPC_ID,
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
"Routes": [
{"DestinationCidrBlock": "172.31.0.0/16", "GatewayId": "local",
"State": "active", "Origin": "CreateRouteTable"},
@@ -312,7 +311,7 @@ def _run_instances(p):
items = "".join(_instance_xml(i) for i in created)
inner = f"""<instancesSet>{items}</instancesSet>
<reservationId>r-{new_uuid().replace('-','')[:17]}</reservationId>
- <ownerId>{ACCOUNT_ID}</ownerId>
+ <ownerId>{get_account_id()}</ownerId>
<groupSet/>"""
return _xml(200, "RunInstancesResponse", inner)
@@ -339,7 +338,7 @@ def _describe_instances(p):
items = "".join(
f"""<item>
<reservationId>r-{inst['InstanceId'][2:]}</reservationId>
- <ownerId>{ACCOUNT_ID}</ownerId>
+ <ownerId>{get_account_id()}</ownerId>
<groupSet/>
<instancesSet>{_instance_xml(inst)}</instancesSet>
</item>"""
@@ -422,7 +421,7 @@ def _describe_images(p):
<imageId>{ami_id}</imageId>
<imageLocation>{name}</imageLocation>
<imageState>available</imageState>
- <imageOwnerId>{ACCOUNT_ID}</imageOwnerId>
+ <imageOwnerId>{get_account_id()}</imageOwnerId>
<isPublic>true</isPublic>
<architecture>x86_64</architecture>
<imageType>machine</imageType>
@@ -457,7 +456,7 @@ def _create_security_group(p):
"GroupName": name,
"Description": desc,
"VpcId": vpc_id,
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
"IpPermissions": [],
"IpPermissionsEgress": [
{"IpProtocol": "-1", "IpRanges": [{"CidrIp": "0.0.0.0/0"}],
@@ -636,13 +635,13 @@ def _create_vpc(p):
{"RuleNumber": 100, "Protocol": "-1", "RuleAction": "allow", "Egress": True, "CidrBlock": "0.0.0.0/0"},
{"RuleNumber": 32767, "Protocol": "-1", "RuleAction": "deny", "Egress": True, "CidrBlock": "0.0.0.0/0"},
],
- "Associations": [], "Tags": [], "OwnerId": ACCOUNT_ID,
+ "Associations": [], "Tags": [], "OwnerId": get_account_id(),
}
# Per-VPC main route table
rtb_id = "rtb-" + "".join(random.choices(string.hexdigits[:16], k=17))
rtb_assoc_id = "rtbassoc-" + "".join(random.choices(string.hexdigits[:16], k=17))
_route_tables[rtb_id] = {
- "RouteTableId": rtb_id, "VpcId": vpc_id, "OwnerId": ACCOUNT_ID,
+ "RouteTableId": rtb_id, "VpcId": vpc_id, "OwnerId": get_account_id(),
"Routes": [{"DestinationCidrBlock": cidr, "GatewayId": "local", "State": "active", "Origin": "CreateRouteTable"}],
"Associations": [{"RouteTableAssociationId": rtb_assoc_id, "RouteTableId": rtb_id, "Main": True,
"AssociationState": {"State": "associated"}}],
@@ -651,7 +650,7 @@ def _create_vpc(p):
sg_id = _new_sg_id()
_security_groups[sg_id] = {
"GroupId": sg_id, "GroupName": "default", "Description": "default VPC security group",
- "VpcId": vpc_id, "OwnerId": ACCOUNT_ID, "IpPermissions": [],
+ "VpcId": vpc_id, "OwnerId": get_account_id(), "IpPermissions": [],
"IpPermissionsEgress": [
{"IpProtocol": "-1", "IpRanges": [{"CidrIp": "0.0.0.0/0"}],
"Ipv6Ranges": [], "PrefixListIds": [], "UserIdGroupPairs": []},
@@ -660,7 +659,7 @@ def _create_vpc(p):
_vpcs[vpc_id] = {
"VpcId": vpc_id, "CidrBlock": cidr, "State": "available", "IsDefault": False,
"DhcpOptionsId": "dopt-00000001", "InstanceTenancy": _p(p, "InstanceTenancy") or "default",
- "OwnerId": ACCOUNT_ID, "DefaultNetworkAclId": acl_id,
+ "OwnerId": get_account_id(), "DefaultNetworkAclId": acl_id,
"DefaultSecurityGroupId": sg_id, "MainRouteTableId": rtb_id,
}
return _xml(200, "CreateVpcResponse", _vpc_fields_xml(_vpcs[vpc_id], tag="vpc"))
@@ -702,7 +701,7 @@ def _create_subnet(p):
"State": "available",
"DefaultForAz": False,
"MapPublicIpOnLaunch": False,
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
}
return _xml(200, "CreateSubnetResponse", _subnet_fields_xml(_subnets[subnet_id], tag="subnet"))
@@ -724,7 +723,7 @@ def _create_internet_gateway(p):
igw_id = _new_igw_id()
_internet_gateways[igw_id] = {
"InternetGatewayId": igw_id,
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
"Attachments": [],
}
return _xml(200, "CreateInternetGatewayResponse",
@@ -827,7 +826,7 @@ def _create_route_table(p):
_route_tables[rtb_id] = {
"RouteTableId": rtb_id,
"VpcId": vpc_id,
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
"Routes": [
{"DestinationCidrBlock": _vpcs.get(vpc_id, {}).get("CidrBlock", "10.0.0.0/16"),
"GatewayId": "local", "State": "active", "Origin": "CreateRouteTable"},
@@ -990,7 +989,7 @@ def _create_network_interface(p):
"VpcId": _subnets.get(subnet_id, {}).get("VpcId", _DEFAULT_VPC_ID),
"AvailabilityZone": az,
"Description": description,
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
"Status": "available",
"PrivateIpAddress": private_ip,
"InterfaceType": "interface",
@@ -1073,7 +1072,7 @@ def _create_vpc_endpoint(p):
"State": "available",
"RouteTableIds": _parse_member_list(p, "RouteTableId"),
"SubnetIds": _parse_member_list(p, "SubnetId"),
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
}
return _xml(200, "CreateVpcEndpointResponse",
_vpce_fields_xml(_vpc_endpoints[vpce_id], tag="vpcEndpoint"))
@@ -1456,7 +1455,7 @@ def _create_snapshot(p):
"State": "completed",
"StartTime": now,
"Progress": "100%",
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
"Encrypted": vol["Encrypted"],
"StorageTier": "standard",
}
@@ -1643,7 +1642,7 @@ def _vpc_xml(vpc):
def _subnet_fields_xml(subnet, tag="item"):
return f"""<{tag}>
<subnetId>{subnet['SubnetId']}</subnetId>
- <subnetArn>arn:aws:ec2:{REGION}:{ACCOUNT_ID}:subnet/{subnet['SubnetId']}</subnetArn>
+ <subnetArn>arn:aws:ec2:{REGION}:{get_account_id()}:subnet/{subnet['SubnetId']}</subnetArn>
<state>{subnet['State']}</state>
<vpcId>{subnet['VpcId']}</vpcId>
<cidrBlock>{subnet['CidrBlock']}</cidrBlock>
@@ -2044,7 +2043,7 @@ def _create_network_acl(params):
"Entries": [],
"Associations": [],
"Tags": tags,
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
}
_network_acls[acl_id] = record
if tags:
@@ -2056,7 +2055,7 @@ def _create_network_acl(params):
<entrySet/>
<associationSet/>
<tagSet/>
- <ownerId>{ACCOUNT_ID}</ownerId>
+ <ownerId>{get_account_id()}</ownerId>
</networkAcl>"""
return _xml(200, "CreateNetworkAclResponse", inner)
@@ -2236,14 +2235,14 @@ def _delete_flow_logs(params):
def _create_vpc_peering_connection(params):
vpc_id = _p(params, "VpcId")
peer_vpc_id = _p(params, "PeerVpcId")
- peer_owner_id = _p(params, "PeerOwnerId") or ACCOUNT_ID
+ peer_owner_id = _p(params, "PeerOwnerId") or get_account_id()
peer_region = _p(params, "PeerRegion") or 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": ACCOUNT_ID, "Region": REGION},
+ "RequesterVpcInfo": {"VpcId": vpc_id, "OwnerId": get_account_id(), "Region": 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(),
@@ -2252,7 +2251,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>{ACCOUNT_ID}</ownerId><region>{REGION}</region></requesterVpcInfo>
+ <requesterVpcInfo><vpcId>{vpc_id}</vpcId><ownerId>{get_account_id()}</ownerId><region>{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/>
@@ -2333,7 +2332,7 @@ def _create_dhcp_options(params):
record = {
"DhcpOptionsId": dopt_id,
"DhcpConfigurations": configs,
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
"Tags": tags,
}
_dhcp_options[dopt_id] = record
@@ -2346,7 +2345,7 @@ def _create_dhcp_options(params):
inner = f"""<dhcpOptions>
<dhcpOptionsId>{dopt_id}</dhcpOptionsId>
<dhcpConfigurationSet>{configs_xml}</dhcpConfigurationSet>
- <ownerId>{ACCOUNT_ID}</ownerId>
+ <ownerId>{get_account_id()}</ownerId>
<tagSet/>
</dhcpOptions>"""
return _xml(200, "CreateDhcpOptionsResponse", inner)
@@ -2568,8 +2567,8 @@ def _create_managed_prefix_list(p):
_prefix_lists[pl_id] = {
"PrefixListId": pl_id, "PrefixListName": name, "State": "create-complete",
"AddressFamily": af, "MaxEntries": max_entries, "Version": 1,
- "Entries": entries, "Tags": tags, "OwnerId": ACCOUNT_ID,
- "PrefixListArn": f"arn:aws:ec2:{REGION}:{ACCOUNT_ID}:prefix-list/{pl_id}",
+ "Entries": entries, "Tags": tags, "OwnerId": get_account_id(),
+ "PrefixListArn": f"arn:aws:ec2:{REGION}:{get_account_id()}:prefix-list/{pl_id}",
}
if tags:
_tags[pl_id] = tags
@@ -2646,7 +2645,7 @@ def _prefix_list_xml(pl, tag="item"):
<maxEntries>{pl.get('MaxEntries',10)}</maxEntries>
<version>{pl.get('Version',1)}</version>
<prefixListArn>{pl.get('PrefixListArn','')}</prefixListArn>
- <ownerId>{pl.get('OwnerId', ACCOUNT_ID)}</ownerId>
+ <ownerId>{pl.get('OwnerId', get_account_id())}</ownerId>
<tagSet/>
</{tag}>"""
@@ -2664,7 +2663,7 @@ def _create_vpn_gateway(p):
_vpn_gateways[vgw_id] = {
"VpnGatewayId": vgw_id, "Type": gw_type, "State": "available",
"AvailabilityZone": az, "AmazonSideAsn": asn,
- "Attachments": [], "Tags": tags, "OwnerId": ACCOUNT_ID,
+ "Attachments": [], "Tags": tags, "OwnerId": get_account_id(),
}
if tags:
_tags[vgw_id] = tags
@@ -2771,7 +2770,7 @@ def _create_customer_gateway(p):
tags = _parse_tags(p)
_customer_gateways[cgw_id] = {
"CustomerGatewayId": cgw_id, "BgpAsn": bgp_asn, "IpAddress": ip_address,
- "Type": gw_type, "State": "available", "Tags": tags, "OwnerId": ACCOUNT_ID,
+ "Type": gw_type, "State": "available", "Tags": tags, "OwnerId": get_account_id(),
}
if tags:
_tags[cgw_id] = tags
@@ -3038,7 +3037,7 @@ def _describe_security_group_rules(p):
items += f"""<item>
<securityGroupRuleId>{rule_id}</securityGroupRuleId>
<groupId>{sg_id}</groupId>
- <groupOwnerId>{ACCOUNT_ID}</groupOwnerId>
+ <groupOwnerId>{get_account_id()}</groupOwnerId>
<isEgress>false</isEgress>
<ipProtocol>{rule.get('IpProtocol', '-1')}</ipProtocol>
<fromPort>{rule.get('FromPort', -1)}</fromPort>
@@ -3051,7 +3050,7 @@ def _describe_security_group_rules(p):
items += f"""<item>
<securityGroupRuleId>{rule_id}</securityGroupRuleId>
<groupId>{sg_id}</groupId>
- <groupOwnerId>{ACCOUNT_ID}</groupOwnerId>
+ <groupOwnerId>{get_account_id()}</groupOwnerId>
<isEgress>true</isEgress>
<ipProtocol>{rule.get('IpProtocol', '-1')}</ipProtocol>
<fromPort>{rule.get('FromPort', -1)}</fromPort>
@@ -3313,7 +3312,7 @@ def _lt_version_xml(ver):
<versionDescription>{_esc(ver.get('VersionDescription', ''))}</versionDescription>
<defaultVersion>{str(ver.get('DefaultVersion', False)).lower()}</defaultVersion>
<createTime>{ver['CreateTime']}</createTime>
- <createdBy>arn:aws:iam::{ACCOUNT_ID}:root</createdBy>
+ <createdBy>arn:aws:iam::{get_account_id()}:root</createdBy>
<launchTemplateData>{_lt_data_xml(ver.get('LaunchTemplateData', {}))}</launchTemplateData>
</item>"""
return xml
@@ -3376,7 +3375,7 @@ def _create_launch_template(p):
<launchTemplateId>{lt_id}</launchTemplateId>
<launchTemplateName>{_esc(name)}</launchTemplateName>
<createTime>{now}</createTime>
- <createdBy>arn:aws:iam::{ACCOUNT_ID}:root</createdBy>
+ <createdBy>arn:aws:iam::{get_account_id()}:root</createdBy>
<defaultVersionNumber>1</defaultVersionNumber>
<latestVersionNumber>1</latestVersionNumber>
<tags>{tags_xml}</tags>
@@ -3449,7 +3448,7 @@ def _describe_launch_templates(p):
<launchTemplateId>{lt['LaunchTemplateId']}</launchTemplateId>
<launchTemplateName>{_esc(lt['LaunchTemplateName'])}</launchTemplateName>
<createTime>{lt['CreateTime']}</createTime>
- <createdBy>arn:aws:iam::{ACCOUNT_ID}:root</createdBy>
+ <createdBy>arn:aws:iam::{get_account_id()}:root</createdBy>
<defaultVersionNumber>{lt['DefaultVersionNumber']}</defaultVersionNumber>
<latestVersionNumber>{lt['LatestVersionNumber']}</latestVersionNumber>
<tags>{tags_xml}</tags>
@@ -3524,7 +3523,7 @@ def _modify_launch_template(p):
<launchTemplateId>{lt['LaunchTemplateId']}</launchTemplateId>
<launchTemplateName>{_esc(lt['LaunchTemplateName'])}</launchTemplateName>
<createTime>{lt['CreateTime']}</createTime>
- <createdBy>arn:aws:iam::{ACCOUNT_ID}:root</createdBy>
+ <createdBy>arn:aws:iam::{get_account_id()}:root</createdBy>
<defaultVersionNumber>{lt['DefaultVersionNumber']}</defaultVersionNumber>
<latestVersionNumber>{lt['LatestVersionNumber']}</latestVersionNumber>
</launchTemplate>""")
diff --git a/ministack/services/ecr.py b/ministack/services/ecr.py
index 0b0fdd5e..22c1123c 100644
--- a/ministack/services/ecr.py
+++ b/ministack/services/ecr.py
@@ -12,11 +12,10 @@ import os
import time
from ministack.core.persistence import load_state, PERSIST_STATE
-from ministack.core.responses import error_response_json, json_response, new_uuid
+from ministack.core.responses import get_account_id, error_response_json, json_response, new_uuid
logger = logging.getLogger("ecr")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
_repositories: dict = {}
@@ -50,15 +49,15 @@ if _restored:
def _repo_arn(name):
- return f"arn:aws:ecr:{REGION}:{ACCOUNT_ID}:repository/{name}"
+ return f"arn:aws:ecr:{REGION}:{get_account_id()}:repository/{name}"
def _registry_id():
- return ACCOUNT_ID
+ return get_account_id()
def _repo_uri(name):
- return f"{ACCOUNT_ID}.dkr.ecr.{REGION}.amazonaws.com/{name}"
+ return f"{get_account_id()}.dkr.ecr.{REGION}.amazonaws.com/{name}"
def _image_digest(manifest):
@@ -346,7 +345,7 @@ def _get_authorization_token(data):
"authorizationData": [{
"authorizationToken": token,
"expiresAt": time.time() + 43200,
- "proxyEndpoint": f"https://{ACCOUNT_ID}.dkr.ecr.{REGION}.amazonaws.com",
+ "proxyEndpoint": f"https://{get_account_id()}.dkr.ecr.{REGION}.amazonaws.com",
}]
})
@@ -516,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://{ACCOUNT_ID}.dkr.ecr.{REGION}.amazonaws.com/v2/{name}/blobs/{layer_digest}",
+ "downloadUrl": f"https://{get_account_id()}.dkr.ecr.{REGION}.amazonaws.com/v2/{name}/blobs/{layer_digest}",
"layerDigest": layer_digest,
})
diff --git a/ministack/services/ecs.py b/ministack/services/ecs.py
index 7cf27826..cbebb888 100644
--- a/ministack/services/ecs.py
+++ b/ministack/services/ecs.py
@@ -31,6 +31,7 @@ import time
from ministack.core.persistence import load_state
from ministack.core.responses import (
+ get_account_id,
error_response_json,
json_response,
new_uuid,
@@ -39,7 +40,6 @@ from ministack.core.responses import (
logger = logging.getLogger("ecs")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
_clusters: dict = {}
@@ -261,7 +261,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}:{ACCOUNT_ID}:cluster/{name}"
+ arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:cluster/{name}"
cluster = {
"clusterArn": arn,
"clusterName": name,
@@ -315,7 +315,7 @@ def _describe_clusters(data):
})
result.append(c)
else:
- arn = ref if ref.startswith("arn:") else f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:cluster/{ref}"
+ arn = ref if ref.startswith("arn:") else f"arn:aws:ecs:{REGION}:{get_account_id()}:cluster/{ref}"
failures.append({"arn": arn, "reason": "MISSING"})
return json_response({"clusters": result, "failures": failures})
@@ -382,7 +382,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}:{ACCOUNT_ID}:task-definition/{td_key}"
+ arn = f"arn:aws:ecs:{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")
@@ -407,7 +407,7 @@ def _register_task_definition(data):
"runtimePlatform": data.get("runtimePlatform", None),
"ephemeralStorage": data.get("ephemeralStorage", None),
"registeredAt": _iso(),
- "registeredBy": f"arn:aws:iam::{ACCOUNT_ID}:root",
+ "registeredBy": f"arn:aws:iam::{get_account_id()}:root",
"compatibilities": compat + (["EC2"] if "FARGATE" in compat and "EC2" not in compat else []),
}
_task_defs[td_key] = td
@@ -509,7 +509,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}:{ACCOUNT_ID}:service/{cluster_name}/{name}"
+ arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:service/{cluster_name}/{name}"
now = _iso()
launch_type = data.get("launchType", "EC2")
@@ -547,7 +547,7 @@ def _create_service(data):
}],
"roleArn": data.get("role", ""),
"createdAt": now,
- "createdBy": f"arn:aws:iam::{ACCOUNT_ID}:root",
+ "createdBy": f"arn:aws:iam::{get_account_id()}:root",
"enableECSManagedTags": data.get("enableECSManagedTags", False),
"propagateTags": data.get("propagateTags", "NONE"),
"enableExecuteCommand": data.get("enableExecuteCommand", False),
@@ -603,7 +603,7 @@ def _describe_services(data):
result.append(_sanitize(s))
else:
arn = ref if ref.startswith("arn:") else \
- f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:service/{cluster_name}/{ref}"
+ f"arn:aws:ecs:{REGION}:{get_account_id()}:service/{cluster_name}/{ref}"
failures.append({"arn": arn, "reason": "MISSING"})
return json_response({"services": result, "failures": failures})
@@ -706,7 +706,7 @@ def _build_task_containers(td, container_overrides):
env.update(env_override)
containers.append({
- "containerArn": f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:container/{new_uuid()}",
+ "containerArn": f"arn:aws:ecs:{REGION}:{get_account_id()}:container/{new_uuid()}",
"taskArn": "",
"name": cdef["name"],
"image": cdef.get("image", ""),
@@ -748,7 +748,7 @@ def _run_task(data):
for _ in range(count):
task_id = new_uuid()
- task_arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:task/{cluster_name}/{task_id}"
+ task_arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:task/{cluster_name}/{task_id}"
now = _iso()
containers = _build_task_containers(td, container_overrides)
@@ -759,7 +759,7 @@ def _run_task(data):
"taskArn": task_arn,
"clusterArn": _clusters[cluster_name]["clusterArn"],
"taskDefinitionArn": td["taskDefinitionArn"],
- "containerInstanceArn": f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:container-instance/{cluster_name}/{new_uuid()}",
+ "containerInstanceArn": f"arn:aws:ecs:{REGION}:{get_account_id()}:container-instance/{cluster_name}/{new_uuid()}",
"overrides": data.get("overrides", {"containerOverrides": [], "inferenceAcceleratorOverrides": []}),
"lastStatus": "RUNNING",
"desiredStatus": "RUNNING",
@@ -902,7 +902,7 @@ def _describe_tasks(data):
result.append(t)
else:
arn = ref if ref.startswith("arn:") else \
- f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:task/{cluster_name}/{ref}"
+ f"arn:aws:ecs:{REGION}:{get_account_id()}:task/{cluster_name}/{ref}"
failures.append({"arn": arn, "reason": "MISSING"})
return json_response({"tasks": result, "failures": failures})
@@ -956,7 +956,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}:{ACCOUNT_ID}:cluster/{cluster_name}"
+ cluster_arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:cluster/{cluster_name}"
status_filter = data.get("desiredStatus", "RUNNING")
family = data.get("family", "")
service_name = data.get("serviceName", "")
@@ -1076,7 +1076,7 @@ def _list_account_settings(data):
settings.append({
"name": setting_name,
"value": _account_settings.get(setting_name, "enabled"),
- "principalArn": f"arn:aws:iam::{ACCOUNT_ID}:root",
+ "principalArn": f"arn:aws:iam::{get_account_id()}:root",
"type": "user" if setting_name in _account_settings else "aws",
})
return json_response({"settings": settings})
@@ -1091,7 +1091,7 @@ def _put_account_setting(data):
return json_response({"setting": {
"name": name,
"value": value,
- "principalArn": f"arn:aws:iam::{ACCOUNT_ID}:root",
+ "principalArn": f"arn:aws:iam::{get_account_id()}:root",
"type": "user",
}})
@@ -1107,7 +1107,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}:{ACCOUNT_ID}:capacity-provider/{p['name']}",
+ "capacityProviderArn": f"arn:aws:ecs:{REGION}:{get_account_id()}:capacity-provider/{p['name']}",
"name": p["name"],
"status": p["status"],
"autoScalingGroupProvider": p["autoScalingGroupProvider"],
@@ -1135,7 +1135,7 @@ def _create_capacity_provider(data):
return error_response_json("InvalidParameterException",
f"Capacity provider {name} already exists.", 400)
- arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:capacity-provider/{name}"
+ arn = f"arn:aws:ecs:{REGION}:{get_account_id()}:capacity-provider/{name}"
asg_provider = data.get("autoScalingGroupProvider", {})
cp = {
@@ -1260,7 +1260,7 @@ def _resolve_task(ref, cluster_name="default"):
task = _tasks.get(ref)
if task:
return task
- cluster_arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:cluster/{cluster_name}"
+ cluster_arn = f"arn:aws:ecs:{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 bfadce08..34168a99 100644
--- a/ministack/services/efs.py
+++ b/ministack/services/efs.py
@@ -25,10 +25,10 @@ import string
import time
from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.responses import get_account_id
logger = logging.getLogger("efs")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# ---------------------------------------------------------------------------
@@ -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}:{ACCOUNT_ID}:file-system/{fs_id}"
+ arn = f"arn:aws:elasticfilesystem:{REGION}:{get_account_id()}:file-system/{fs_id}"
now = _now_iso()
record = {
@@ -90,7 +90,7 @@ def _create_file_system(body):
"Encrypted": encrypted,
"KmsKeyId": kms_key_id,
"Tags": tags,
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
"Name": next((t["Value"] for t in tags if t["Key"] == "Name"), ""),
}
if provisioned_throughput:
@@ -158,7 +158,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}:{ACCOUNT_ID}:file-system/{fs_id}/mount-target/{mt_id}"
+ arn = f"arn:aws:elasticfilesystem:{REGION}:{get_account_id()}:file-system/{fs_id}/mount-target/{mt_id}"
now = _now_iso()
record = {
@@ -171,7 +171,7 @@ def _create_mount_target(body):
"LifeCycleState": "available",
"IpAddress": ip_address,
"NetworkInterfaceId": f"eni-{random.choices(string.hexdigits[:16], k=17)}",
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
"MountTargetArn": arn,
"SecurityGroups": security_groups,
}
@@ -238,7 +238,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}:{ACCOUNT_ID}:access-point/{ap_id}"
+ arn = f"arn:aws:elasticfilesystem:{REGION}:{get_account_id()}:access-point/{ap_id}"
now = _now_iso()
tags = body.get("Tags", [])
@@ -251,7 +251,7 @@ def _create_access_point(body):
"PosixUser": body.get("PosixUser", {}),
"RootDirectory": body.get("RootDirectory", {"Path": "/"}),
"Tags": tags,
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
"Name": next((t["Value"] for t in tags if t["Key"] == "Name"), ""),
}
_access_points[ap_id] = record
diff --git a/ministack/services/elasticache.py b/ministack/services/elasticache.py
index 840209d9..ac462d1b 100644
--- a/ministack/services/elasticache.py
+++ b/ministack/services/elasticache.py
@@ -27,11 +27,10 @@ import time
from urllib.parse import parse_qs
from ministack.core.persistence import load_state
-from ministack.core.responses import new_uuid
+from ministack.core.responses import get_account_id, new_uuid
logger = logging.getLogger("elasticache")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
REDIS_DEFAULT_HOST = os.environ.get("REDIS_HOST", "redis")
REDIS_DEFAULT_PORT = int(os.environ.get("REDIS_PORT", "6379"))
@@ -111,23 +110,23 @@ def _get_docker():
def _arn_cluster(cluster_id):
- return f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:cluster:{cluster_id}"
+ return f"arn:aws:elasticache:{REGION}:{get_account_id()}:cluster:{cluster_id}"
def _arn_replication_group(rg_id):
- return f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:replicationgroup:{rg_id}"
+ return f"arn:aws:elasticache:{REGION}:{get_account_id()}:replicationgroup:{rg_id}"
def _arn_subnet_group(name):
- return f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:subnetgroup:{name}"
+ return f"arn:aws:elasticache:{REGION}:{get_account_id()}:subnetgroup:{name}"
def _arn_param_group(name):
- return f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:parametergroup:{name}"
+ return f"arn:aws:elasticache:{REGION}:{get_account_id()}:parametergroup:{name}"
def _arn_snapshot(name):
- return f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:snapshot:{name}"
+ return f"arn:aws:elasticache:{REGION}:{get_account_id()}:snapshot:{name}"
def _record_event(source_id, source_type, message):
@@ -958,11 +957,11 @@ def _describe_events(p):
# ---- Users (Redis ACL) ----
def _arn_user(user_id):
- return f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:user:{user_id}"
+ return f"arn:aws:elasticache:{REGION}:{get_account_id()}:user:{user_id}"
def _arn_user_group(group_id):
- return f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:usergroup:{group_id}"
+ return f"arn:aws:elasticache:{REGION}:{get_account_id()}:usergroup:{group_id}"
def _create_user(p):
diff --git a/ministack/services/emr.py b/ministack/services/emr.py
index d226b6ae..cfbc1b8c 100644
--- a/ministack/services/emr.py
+++ b/ministack/services/emr.py
@@ -23,11 +23,10 @@ import string
import time
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import error_response_json, json_response, new_uuid
+from ministack.core.responses import get_account_id, error_response_json, json_response, new_uuid
logger = logging.getLogger("emr")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# ---------------------------------------------------------------------------
@@ -93,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}:{ACCOUNT_ID}:cluster/{cluster_id}"
+ arn = f"arn:aws:elasticmapreduce:{REGION}:{get_account_id()}:cluster/{cluster_id}"
instances = data.get("Instances", {})
keep_alive = instances.get("KeepJobFlowAliveWhenNoSteps", False)
tags = data.get("Tags", [])
@@ -528,7 +527,7 @@ def _get_block_public_access_configuration(data):
"BlockPublicAccessConfiguration": _block_public_access,
"BlockPublicAccessConfigurationMetadata": {
"CreationDateTime": _now_iso(),
- "CreatedByArn": f"arn:aws:iam::{ACCOUNT_ID}:root",
+ "CreatedByArn": f"arn:aws:iam::{get_account_id()}:root",
},
})
diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.py
index ec46cc80..cf3e24f4 100644
--- a/ministack/services/eventbridge.py
+++ b/ministack/services/eventbridge.py
@@ -23,11 +23,10 @@ import threading
import time
from datetime import datetime
-from ministack.core.responses import error_response_json, json_response, new_uuid
+from ministack.core.responses import get_account_id, error_response_json, json_response, new_uuid
logger = logging.getLogger("events")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
@@ -54,7 +53,7 @@ from ministack.core.persistence import load_state, PERSIST_STATE
_event_buses: dict = {
"default": {
"Name": "default",
- "Arn": f"arn:aws:events:{REGION}:{ACCOUNT_ID}:event-bus/default",
+ "Arn": f"arn:aws:events:{REGION}:{get_account_id()}:event-bus/default",
"CreationTime": _now_ts(),
"LastModifiedTime": _now_ts(),
}
@@ -166,7 +165,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}:{ACCOUNT_ID}:event-bus/{name}"
+ arn = f"arn:aws:events:{REGION}:{get_account_id()}:event-bus/{name}"
description = data.get("Description", "")
_event_buses[name] = {
"Name": name,
@@ -264,8 +263,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}:{ACCOUNT_ID}:rule/{rule_name}"
- return f"arn:aws:events:{REGION}:{ACCOUNT_ID}:rule/{bus_name}/{rule_name}"
+ 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}"
def _rule_key(rule_name: str, bus_name: str) -> str:
@@ -322,7 +321,7 @@ def _put_rule(data):
"Description": data.get("Description", existing.get("Description", "")),
"RoleArn": data.get("RoleArn", existing.get("RoleArn", "")),
"ManagedBy": existing.get("ManagedBy", ""),
- "CreatedBy": ACCOUNT_ID,
+ "CreatedBy": get_account_id(),
"CreationTime": existing.get("CreationTime", _now_ts()),
}
@@ -464,7 +463,7 @@ def _put_events(data):
"EventBusName": bus_name,
"Time": event_time,
"Resources": entry.get("Resources", []),
- "Account": ACCOUNT_ID,
+ "Account": get_account_id(),
"Region": REGION,
}
_events_log.append(event_record)
@@ -519,7 +518,7 @@ def _matches_pattern(pattern_str, event):
return False
if "account" in pattern:
- if not _matches_field(event.get("Account", ACCOUNT_ID), pattern["account"]):
+ if not _matches_field(event.get("Account", get_account_id()), pattern["account"]):
return False
if "region" in pattern:
@@ -612,7 +611,7 @@ def _invoke_target(target, event, rule):
"version": "0",
"id": event["EventId"],
"source": event["Source"],
- "account": ACCOUNT_ID,
+ "account": get_account_id(),
"time": event["Time"],
"region": REGION,
"resources": event.get("Resources", []),
@@ -663,7 +662,7 @@ def _apply_input_transformer(transformer, event):
"source": event.get("Source", ""),
"detail-type": event.get("DetailType", ""),
"detail": full,
- "account": ACCOUNT_ID,
+ "account": get_account_id(),
"region": REGION,
"time": event.get("Time", ""),
"id": event.get("EventId", ""),
@@ -806,7 +805,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}:{ACCOUNT_ID}:archive/{name}"
+ arn = f"arn:aws:events:{REGION}:{get_account_id()}:archive/{name}"
_archives[name] = {
"ArchiveName": name,
"ArchiveArn": arn,
@@ -873,7 +872,7 @@ def _put_permission(data):
"Effect": "Allow",
"Principal": data.get("Principal", "*"),
"Action": data.get("Action", "events:PutEvents"),
- "Resource": f"arn:aws:events:{REGION}:{ACCOUNT_ID}:event-bus/{bus_name}",
+ "Resource": f"arn:aws:events:{REGION}:{get_account_id()}:event-bus/{bus_name}",
}
condition = data.get("Condition")
if condition:
@@ -913,7 +912,7 @@ def _create_connection(data):
return error_response_json("ResourceAlreadyExistsException",
f"Connection {name} already exists", 400)
- arn = f"arn:aws:events:{REGION}:{ACCOUNT_ID}:connection/{name}"
+ arn = f"arn:aws:events:{REGION}:{get_account_id()}:connection/{name}"
now = _now_ts()
_connections[name] = {
"Name": name,
@@ -1010,7 +1009,7 @@ def _create_api_destination(data):
return error_response_json("ResourceAlreadyExistsException",
f"ApiDestination {name} already exists", 400)
- arn = f"arn:aws:events:{REGION}:{ACCOUNT_ID}:api-destination/{name}"
+ arn = f"arn:aws:events:{REGION}:{get_account_id()}:api-destination/{name}"
now = _now_ts()
_api_destinations[name] = {
"Name": name,
@@ -1106,7 +1105,7 @@ def reset():
_event_buses = {
"default": {
"Name": "default",
- "Arn": f"arn:aws:events:{REGION}:{ACCOUNT_ID}:event-bus/default",
+ "Arn": f"arn:aws:events:{REGION}:{get_account_id()}:event-bus/default",
"CreationTime": _now_ts(),
"LastModifiedTime": _now_ts(),
}
diff --git a/ministack/services/firehose.py b/ministack/services/firehose.py
index f3f53936..964298d0 100644
--- a/ministack/services/firehose.py
+++ b/ministack/services/firehose.py
@@ -25,6 +25,7 @@ import time
from ministack.core.persistence import PERSIST_STATE, load_state
from ministack.core.responses import (
+ get_account_id,
error_response_json,
json_response,
new_uuid,
@@ -33,7 +34,6 @@ from ministack.core.responses import (
logger = logging.getLogger("firehose")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# ─── in-memory state ──────────────────────────────────────────────────────────
@@ -68,7 +68,7 @@ if _restored:
# ─── helpers ─────────────────────────────────────────────────────────────────
def _stream_arn(name: str) -> str:
- return f"arn:aws:firehose:{REGION}:{ACCOUNT_ID}:deliverystream/{name}"
+ return f"arn:aws:firehose:{REGION}:{get_account_id()}:deliverystream/{name}"
def _next_dest_id() -> str:
@@ -81,7 +81,7 @@ def _next_dest_id() -> str:
def _not_found(name: str):
return error_response_json(
"ResourceNotFoundException",
- f"Firehose {name} under account {ACCOUNT_ID} not found.",
+ f"Firehose {name} under account {get_account_id()} not found.",
400,
)
diff --git a/ministack/services/glue.py b/ministack/services/glue.py
index c5e4c2ad..47a391cf 100644
--- a/ministack/services/glue.py
+++ b/ministack/services/glue.py
@@ -19,11 +19,10 @@ import threading
import time
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import error_response_json, json_response, new_uuid
+from ministack.core.responses import get_account_id, error_response_json, json_response, new_uuid
logger = logging.getLogger("glue")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
CRAWLER_RUN_SECONDS = int(os.environ.get("GLUE_CRAWLER_RUN_SECONDS", "5"))
S3_DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/ministack-data/s3")
@@ -77,7 +76,7 @@ if _restored:
def _arn(resource_type, name):
- return f"arn:aws:glue:{REGION}:{ACCOUNT_ID}:{resource_type}/{name}"
+ return f"arn:aws:glue:{REGION}:{get_account_id()}:{resource_type}/{name}"
async def handle_request(method, path, headers, body, query_params):
@@ -190,7 +189,7 @@ def _create_database(data):
"LocationUri": db_input.get("LocationUri", ""),
"Parameters": db_input.get("Parameters", {}),
"CreateTime": time.time(),
- "CatalogId": ACCOUNT_ID,
+ "CatalogId": get_account_id(),
}
return json_response({})
@@ -254,7 +253,7 @@ def _create_table(data):
"TableType": table_input.get("TableType", "EXTERNAL_TABLE"),
"Parameters": table_input.get("Parameters", {}),
"IsRegisteredWithLakeFormation": False,
- "CatalogId": ACCOUNT_ID,
+ "CatalogId": get_account_id(),
}
return json_response({})
@@ -342,7 +341,7 @@ def _create_partition(data):
"TableName": table_name,
"CreationTime": time.time(),
"LastAccessTime": time.time(),
- "CatalogId": ACCOUNT_ID,
+ "CatalogId": get_account_id(),
})
return json_response({})
@@ -395,7 +394,7 @@ def _batch_create_partition(data):
"DatabaseName": db_name,
"TableName": table_name,
"CreationTime": time.time(),
- "CatalogId": ACCOUNT_ID,
+ "CatalogId": get_account_id(),
})
return json_response({"Errors": errors})
diff --git a/ministack/services/iam_sts.py b/ministack/services/iam_sts.py
index 6871c39b..b746d5a1 100644
--- a/ministack/services/iam_sts.py
+++ b/ministack/services/iam_sts.py
@@ -36,11 +36,10 @@ import time
from urllib.parse import parse_qs
from urllib.parse import quote as _url_quote
-from ministack.core.responses import new_uuid
+from ministack.core.responses import get_account_id, json_response, new_uuid
logger = logging.getLogger("iam")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# ---------------------------------------------------------------------------
@@ -117,7 +116,7 @@ def _create_user(p):
path = _p(p, "Path") or "/"
_users[name] = {
"UserName": name,
- "Arn": f"arn:aws:iam::{ACCOUNT_ID}:user{path}{name}" if path != "/" else f"arn:aws:iam::{ACCOUNT_ID}:user/{name}",
+ "Arn": f"arn:aws:iam::{get_account_id()}:user{path}{name}" if path != "/" else f"arn:aws:iam::{get_account_id()}:user/{name}",
"UserId": _gen_id("AIDA"),
"CreateDate": _now(),
"Path": path,
@@ -135,8 +134,8 @@ def _get_user(p):
return _xml(200, "GetUserResponse",
"<GetUserResult><User>"
f"<UserName>root</UserName>"
- f"<UserId>{ACCOUNT_ID}</UserId>"
- f"<Arn>arn:aws:iam::{ACCOUNT_ID}:root</Arn>"
+ f"<UserId>{get_account_id()}</UserId>"
+ f"<Arn>arn:aws:iam::{get_account_id()}:root</Arn>"
"<Path>/</Path>"
f"<CreateDate>{_now()}</CreateDate>"
"</User></GetUserResult>",
@@ -189,7 +188,7 @@ def _create_role(p):
path = _p(p, "Path") or "/"
_roles[name] = {
"RoleName": name,
- "Arn": f"arn:aws:iam::{ACCOUNT_ID}:role{path}{name}" if path != "/" else f"arn:aws:iam::{ACCOUNT_ID}:role/{name}",
+ "Arn": f"arn:aws:iam::{get_account_id()}:role{path}{name}" if path != "/" else f"arn:aws:iam::{get_account_id()}:role/{name}",
"RoleId": _gen_id("AROA"),
"CreateDate": _now(),
"Path": path,
@@ -274,7 +273,7 @@ def _update_assume_role_policy(p):
def _create_policy(p):
name = _p(p, "PolicyName")
path = _p(p, "Path") or "/"
- arn = f"arn:aws:iam::{ACCOUNT_ID}:policy{path}{name}" if path != "/" else f"arn:aws:iam::{ACCOUNT_ID}:policy/{name}"
+ arn = f"arn:aws:iam::{get_account_id()}:policy{path}{name}" if path != "/" else f"arn:aws:iam::{get_account_id()}:policy/{name}"
if arn in _policies:
return _error(409, "EntityAlreadyExists",
f"A policy called {name} already exists.", ns="iam")
@@ -717,9 +716,9 @@ def _create_instance_profile(p):
f"Instance profile {name} already exists.", ns="iam")
path = _p(p, "Path") or "/"
ip_id = _gen_id("AIPA")
- arn = (f"arn:aws:iam::{ACCOUNT_ID}:instance-profile{path}{name}"
+ arn = (f"arn:aws:iam::{get_account_id()}:instance-profile{path}{name}"
if path != "/" else
- f"arn:aws:iam::{ACCOUNT_ID}:instance-profile/{name}")
+ f"arn:aws:iam::{get_account_id()}:instance-profile/{name}")
_instance_profiles[name] = {
"InstanceProfileName": name,
"InstanceProfileId": ip_id,
@@ -966,7 +965,7 @@ def _create_group(p):
_groups[name] = {
"GroupName": name,
"GroupId": _gen_id("AGPA"),
- "Arn": f"arn:aws:iam::{ACCOUNT_ID}:group{path}{name}" if path != "/" else f"arn:aws:iam::{ACCOUNT_ID}:group/{name}",
+ "Arn": f"arn:aws:iam::{get_account_id()}:group{path}{name}" if path != "/" else f"arn:aws:iam::{get_account_id()}:group/{name}",
"Path": path,
"CreateDate": _now(),
"Users": [],
@@ -1153,7 +1152,7 @@ def _create_service_linked_role(p):
_roles[role_name] = {
"RoleName": role_name,
- "Arn": f"arn:aws:iam::{ACCOUNT_ID}:role{path}{role_name}",
+ "Arn": f"arn:aws:iam::{get_account_id()}:role{path}{role_name}",
"RoleId": _gen_id("AROA"),
"CreateDate": _now(),
"Path": path,
@@ -1232,7 +1231,7 @@ def _create_oidc_provider(p):
idx += 1
host = url.replace("https://", "").replace("http://", "").rstrip("/")
- arn = f"arn:aws:iam::{ACCOUNT_ID}:oidc-provider/{host}"
+ arn = f"arn:aws:iam::{get_account_id()}:oidc-provider/{host}"
if arn in _oidc_providers:
return _error(409, "EntityAlreadyExists",
@@ -1334,18 +1333,35 @@ def _list_policy_tags(p):
async def handle_sts_request(method, path, headers, body, query_params):
params = dict(query_params)
- if method == "POST" and body:
+ content_type = headers.get("content-type", "")
+ target = headers.get("x-amz-target", "")
+
+ # JSON protocol (newer SDKs): X-Amz-Target: AWSSecurityTokenServiceV20110615.ActionName
+ if "amz-json" in content_type and target.startswith("AWSSecurityTokenServiceV20110615."):
+ action_name = target.split(".")[-1]
+ params["Action"] = [action_name]
+ if body:
+ try:
+ json_body = json.loads(body)
+ for k, v in json_body.items():
+ params[k] = [str(v)] if not isinstance(v, list) else v
+ except (json.JSONDecodeError, TypeError):
+ pass
+ elif method == "POST" and body:
for k, v in parse_qs(body.decode("utf-8", errors="replace")).items():
params[k] = v
action = _p(params, "Action")
+ use_json = "amz-json" in content_type
if action == "GetCallerIdentity":
+ if use_json:
+ return json_response({"Account": get_account_id(), "Arn": f"arn:aws:iam::{get_account_id()}:root", "UserId": get_account_id()})
return _xml(200, "GetCallerIdentityResponse",
f"<GetCallerIdentityResult>"
- f"<Arn>arn:aws:iam::{ACCOUNT_ID}:root</Arn>"
- f"<UserId>{ACCOUNT_ID}</UserId>"
- f"<Account>{ACCOUNT_ID}</Account>"
+ f"<Arn>arn:aws:iam::{get_account_id()}:root</Arn>"
+ f"<UserId>{get_account_id()}</UserId>"
+ f"<Account>{get_account_id()}</Account>"
f"</GetCallerIdentityResult>",
ns="sts")
@@ -1361,6 +1377,12 @@ async def handle_sts_request(method, path, headers, body, query_params):
assumed_arn = role_arn.replace(":role/", ":assumed-role/", 1)
if not assumed_arn.endswith(f"/{session_name}"):
assumed_arn = f"{assumed_arn}/{session_name}"
+ if use_json:
+ return json_response({
+ "Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": time.time() + duration},
+ "AssumedRoleUser": {"AssumedRoleId": f"{role_id}:{session_name}", "Arn": assumed_arn},
+ "PackedPolicySize": 0,
+ })
return _xml(200, "AssumeRoleResponse",
f"<AssumeRoleResult>"
f"<Credentials>"
@@ -1388,6 +1410,14 @@ async def handle_sts_request(method, path, headers, body, query_params):
if not assumed_arn.endswith(f"/{session}"):
assumed_arn = f"{assumed_arn}/{session}"
role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()
+ if use_json:
+ return json_response({
+ "Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": time.time() + duration},
+ "AssumedRoleUser": {"AssumedRoleId": f"{role_id}:{session}", "Arn": assumed_arn},
+ "SubjectFromWebIdentityToken": "test-subject",
+ "Audience": "sts.amazonaws.com",
+ "Provider": "accounts.google.com",
+ })
return _xml(200, "AssumeRoleWithWebIdentityResponse",
f"<AssumeRoleWithWebIdentityResult>"
f"<Credentials>"
@@ -1412,6 +1442,10 @@ async def handle_sts_request(method, path, headers, body, query_params):
access_key = _gen_session_access_key()
secret_key = _gen_secret()
session_token = _gen_session_token()
+ if use_json:
+ return json_response({
+ "Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": time.time() + duration},
+ })
return _xml(200, "GetSessionTokenResponse",
f"<GetSessionTokenResult>"
f"<Credentials>"
@@ -1424,10 +1458,11 @@ async def handle_sts_request(method, path, headers, body, query_params):
ns="sts")
if action == "GetAccessKeyInfo":
- access_key = _p(params, "AccessKeyId") or ""
+ if use_json:
+ return json_response({"Account": get_account_id()})
return _xml(200, "GetAccessKeyInfoResponse",
f"<GetAccessKeyInfoResult>"
- f"<Account>{ACCOUNT_ID}</Account>"
+ f"<Account>{get_account_id()}</Account>"
f"</GetAccessKeyInfoResult>",
ns="sts")
diff --git a/ministack/services/kinesis.py b/ministack/services/kinesis.py
index 02acc770..dd7c4ced 100644
--- a/ministack/services/kinesis.py
+++ b/ministack/services/kinesis.py
@@ -21,11 +21,10 @@ import logging
import threading
import time
-from ministack.core.responses import error_response_json, json_response, new_uuid
+from ministack.core.responses import get_account_id, error_response_json, json_response, new_uuid
logger = logging.getLogger("kinesis")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
MAX_HASH_KEY = (2**128) - 1
ITERATOR_EXPIRY_SECONDS = 300
@@ -199,7 +198,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}:{ACCOUNT_ID}:stream/{name}"
+ arn = f"arn:aws:kinesis:{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 c4d259bf..45244f62 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 error_response_json, json_response, new_uuid
+from ministack.core.responses import get_account_id, error_response_json, json_response, new_uuid
logger = logging.getLogger("kms")
@@ -31,7 +31,6 @@ except ImportError:
"Install with: pip install cryptography"
)
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
from ministack.core.persistence import load_state, PERSIST_STATE
@@ -97,7 +96,7 @@ if _restored:
def _arn(key_id):
- return f"arn:aws:kms:{REGION}:{ACCOUNT_ID}:key/{key_id}"
+ return f"arn:aws:kms:{REGION}:{get_account_id()}:key/{key_id}"
def _key_metadata(rec):
@@ -163,7 +162,7 @@ def _create_key(data):
"Statement": [{
"Sid": "Enable IAM User Permissions",
"Effect": "Allow",
- "Principal": {"AWS": f"arn:aws:iam::{ACCOUNT_ID}:root"},
+ "Principal": {"AWS": f"arn:aws:iam::{get_account_id()}:root"},
"Action": "kms:*",
"Resource": "*",
}],
@@ -652,7 +651,7 @@ def _list_aliases(data):
continue
items.append({
"AliasName": alias_name,
- "AliasArn": f"arn:aws:kms:{REGION}:{ACCOUNT_ID}:{alias_name}",
+ "AliasArn": f"arn:aws:kms:{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 d0c19162..965528c7 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -43,12 +43,11 @@ from typing import Any
from urllib.parse import unquote
from ministack.core.persistence import load_state, PERSIST_STATE
-from ministack.core.responses import error_response_json, json_response, new_uuid
+from ministack.core.responses import get_account_id, error_response_json, json_response, new_uuid
from ministack.core.lambda_runtime import get_or_create_worker, invalidate_worker
logger = logging.getLogger("lambda")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", os.environ.get("AWS_DEFAULT_REGION", "us-east-1"))
LAMBDA_EXECUTOR = os.environ.get("LAMBDA_EXECUTOR", "local").lower()
LAMBDA_DOCKER_VOLUME_MOUNT = os.environ.get("LAMBDA_REMOTE_DOCKER_VOLUME_MOUNT", "")
@@ -282,11 +281,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}:{ACCOUNT_ID}:function:{name}"
+ return f"arn:aws:lambda:{REGION}:{get_account_id()}:function:{name}"
def _layer_arn(name: str) -> str:
- return f"arn:aws:lambda:{REGION}:{ACCOUNT_ID}:layer:{name}"
+ return f"arn:aws:lambda:{REGION}:{get_account_id()}:layer:{name}"
def _now_iso() -> str:
@@ -340,7 +339,7 @@ def _build_config(name: str, data: dict, code_zip: bytes | None = None) -> dict:
"FunctionName": name,
"FunctionArn": _func_arn(name),
"Runtime": data.get("Runtime", "python3.9"),
- "Role": data.get("Role", f"arn:aws:iam::{ACCOUNT_ID}:role/lambda-role"),
+ "Role": data.get("Role", f"arn:aws:iam::{get_account_id()}:role/lambda-role"),
"Handler": data.get("Handler", "index.handler"),
"CodeSize": code_size,
"CodeSha256": code_sha,
@@ -2526,7 +2525,7 @@ def _poll_sqs():
"attributes": {
"ApproximateReceiveCount": str(msg.get("receive_count", 1)),
"SentTimestamp": str(int(msg["sent_at"] * 1000)),
- "SenderId": ACCOUNT_ID,
+ "SenderId": get_account_id(),
"ApproximateFirstReceiveTimestamp": str(int(first_recv * 1000)),
},
"messageAttributes": msg.get("message_attributes", {}),
@@ -2623,7 +2622,7 @@ def _poll_kinesis():
"eventVersion": "1.0",
"eventID": f"{shard_id}:{r['SequenceNumber']}",
"eventName": "aws:kinesis:record",
- "invokeIdentityArn": f"arn:aws:iam::{ACCOUNT_ID}:role/lambda-role",
+ "invokeIdentityArn": f"arn:aws:iam::{get_account_id()}:role/lambda-role",
"awsRegion": REGION,
"eventSourceARN": source_arn,
})
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index 62693c24..5e1f41d7 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -32,11 +32,10 @@ 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 new_uuid
+from ministack.core.responses import get_account_id, new_uuid
logger = logging.getLogger("rds")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
BASE_PORT = int(os.environ.get("RDS_BASE_PORT", "15432"))
RDS_TMPFS_SIZE = os.environ.get("RDS_TMPFS_SIZE", "256m")
@@ -167,7 +166,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}:{ACCOUNT_ID}:db:{db_id}"
+ arn = f"arn:aws:rds:{REGION}:{get_account_id()}:db:{db_id}"
dbi_resource_id = f"db-{new_uuid().replace('-', '')[:20].upper()}"
endpoint_host = "localhost"
endpoint_port = port
@@ -209,7 +208,7 @@ def _create_db_instance(p):
"SubnetGroupStatus": "Complete",
"Subnets": [],
"VpcId": "vpc-00000000",
- "DBSubnetGroupArn": f"arn:aws:rds:{REGION}:{ACCOUNT_ID}:subgrp:{subnet_group_name}",
+ "DBSubnetGroupArn": f"arn:aws:rds:{REGION}:{get_account_id()}:subgrp:{subnet_group_name}",
})
instance = {
@@ -463,7 +462,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}:{ACCOUNT_ID}:db:{replica_id}"
+ arn = f"arn:aws:rds:{REGION}:{get_account_id()}:db:{replica_id}"
replica = dict(source)
replica.update({
"DBInstanceIdentifier": replica_id,
@@ -508,7 +507,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}:{ACCOUNT_ID}:db:{db_id}"
+ arn = f"arn:aws:rds:{REGION}:{get_account_id()}:db:{db_id}"
instance = {
"DBInstanceIdentifier": db_id,
"DBInstanceClass": _p(p, "DBInstanceClass") or snap.get("DBInstanceClass", "db.t3.micro"),
@@ -581,7 +580,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}:{ACCOUNT_ID}:cluster:{cluster_id}"
+ arn = f"arn:aws:rds:{REGION}:{get_account_id()}:cluster:{cluster_id}"
unique_suffix = new_uuid()[:8]
now_ts = time.time()
@@ -728,7 +727,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}:{ACCOUNT_ID}:snapshot:{snap_id}"
+ arn = f"arn:aws:rds:{REGION}:{get_account_id()}:snapshot:{snap_id}"
now_ts = time.time()
snap = {
"DBSnapshotIdentifier": snap_id,
@@ -830,7 +829,7 @@ 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}:{ACCOUNT_ID}:subgrp:{name}"
+ arn = f"arn:aws:rds:{REGION}:{get_account_id()}:subgrp:{name}"
subnets = [{"SubnetIdentifier": sid, "SubnetAvailabilityZone": {"Name": f"{REGION}a"},
"SubnetOutpost": {}, "SubnetStatus": "Active"} for sid in subnet_ids]
@@ -890,7 +889,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}:{ACCOUNT_ID}:pg:{name}"
+ arn = f"arn:aws:rds:{REGION}:{get_account_id()}:pg:{name}"
_param_groups[name] = {
"DBParameterGroupName": name,
@@ -1004,7 +1003,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}:{ACCOUNT_ID}:cluster-pg:{name}"
+ arn = f"arn:aws:rds:{REGION}:{get_account_id()}:cluster-pg:{name}"
_db_cluster_param_groups[name] = {
"DBClusterParameterGroupName": name,
@@ -1104,7 +1103,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}:{ACCOUNT_ID}:cluster-snapshot:{snap_id}"
+ arn = f"arn:aws:rds:{REGION}:{get_account_id()}:cluster-snapshot:{snap_id}"
now_ts = time.time()
snap = {
"DBClusterSnapshotIdentifier": snap_id,
@@ -1239,7 +1238,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}:{ACCOUNT_ID}:og:{name}"
+ arn = f"arn:aws:rds:{REGION}:{get_account_id()}:og:{name}"
_option_groups[name] = {
"OptionGroupName": name,
@@ -1391,7 +1390,7 @@ def _create_global_cluster(p):
storage_encrypted = _p(p, "StorageEncrypted") == "true"
deletion_protection = _p(p, "DeletionProtection") == "true"
- arn = f"arn:aws:rds::{ACCOUNT_ID}:global-cluster:{gc_id}"
+ arn = f"arn:aws:rds::{get_account_id()}:global-cluster:{gc_id}"
resource_id = f"cluster-{new_uuid().replace('-', '')[:20].lower()}"
members = []
@@ -1501,7 +1500,7 @@ def _modify_global_cluster(p):
return _error("GlobalClusterAlreadyExistsFault",
f"Global cluster {new_id} already exists.", 400)
gc["GlobalClusterIdentifier"] = new_id
- gc["GlobalClusterArn"] = f"arn:aws:rds::{ACCOUNT_ID}:global-cluster:{new_id}"
+ gc["GlobalClusterArn"] = f"arn:aws:rds::{get_account_id()}:global-cluster:{new_id}"
_global_clusters[new_id] = gc
del _global_clusters[gc_id]
diff --git a/ministack/services/rds_data.py b/ministack/services/rds_data.py
index e87f1243..7c7d2fe7 100644
--- a/ministack/services/rds_data.py
+++ b/ministack/services/rds_data.py
@@ -10,11 +10,10 @@ import os
import threading
import uuid
-from ministack.core.responses import error_response_json, json_response
+from ministack.core.responses import get_account_id, error_response_json, json_response
logger = logging.getLogger("rds-data")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# Active transactions: txn_id -> {conn, engine, resourceArn, database}
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 1bb68a8e..01ae11d3 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -38,6 +38,7 @@ from xml.etree.ElementTree import Element, SubElement, tostring
from ministack.core.persistence import load_state, PERSIST_STATE
from ministack.core.responses import (
+ get_account_id,
md5_hash,
sha256_hash,
now_iso,
@@ -47,7 +48,6 @@ from ministack.core.responses import (
logger = logging.getLogger("s3")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
S3_NS = "http://s3.amazonaws.com/doc/2006-03-01/"
XML_DECL = b'<?xml version="1.0" encoding="UTF-8"?>'
@@ -1241,14 +1241,14 @@ def _fire_s3_event(
"bucket": {"name": bucket_name},
"object": {"key": key, "size": size, "etag": clean_etag, "sequencer": "0"},
"request-id": request_id,
- "requester": ACCOUNT_ID,
+ "requester": get_account_id(),
"source-ip-address": "127.0.0.1",
"reason": "PutObject",
}),
"EventBusName": "default",
"Time": event_time,
"Resources": [f"arn:aws:s3:::{bucket_name}"],
- "Account": ACCOUNT_ID,
+ "Account": get_account_id(),
"Region": os.environ.get("MINISTACK_REGION", "us-east-1"),
}
_eb._dispatch_event(eb_event)
diff --git a/ministack/services/s3files.py b/ministack/services/s3files.py
index 9033e613..8e1078f5 100644
--- a/ministack/services/s3files.py
+++ b/ministack/services/s3files.py
@@ -19,11 +19,10 @@ import os
import time
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import error_response_json, json_response, new_uuid
+from ministack.core.responses import get_account_id, error_response_json, json_response, new_uuid
logger = logging.getLogger("s3files")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
_file_systems: dict = {}
@@ -71,7 +70,7 @@ def reset():
def _arn(resource_type, resource_id):
- return f"arn:aws:s3files:{REGION}:{ACCOUNT_ID}:{resource_type}/{resource_id}"
+ return f"arn:aws:s3files:{REGION}:{get_account_id()}:{resource_type}/{resource_id}"
def _now_iso():
@@ -197,7 +196,7 @@ def _create_file_system(data):
"BucketName": bucket_name,
"LifeCycleState": "available",
"CreationTime": _now_iso(),
- "OwnerId": ACCOUNT_ID,
+ "OwnerId": get_account_id(),
}
_file_systems[fs_id] = fs
logger.info("Created S3 file system %s for bucket %s", fs_id, bucket_name)
diff --git a/ministack/services/secretsmanager.py b/ministack/services/secretsmanager.py
index d8664713..9affc67e 100644
--- a/ministack/services/secretsmanager.py
+++ b/ministack/services/secretsmanager.py
@@ -19,11 +19,10 @@ import secrets as stdlib_secrets
import string
import time
-from ministack.core.responses import error_response_json, json_response, new_uuid
+from ministack.core.responses import get_account_id, error_response_json, json_response, new_uuid
logger = logging.getLogger("secretsmanager")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
from ministack.core.persistence import load_state, PERSIST_STATE
@@ -200,7 +199,7 @@ def _create_secret(data):
f"The operation failed because the secret {name} already exists.", 400,
)
- arn = f"arn:aws:secretsmanager:{REGION}:{ACCOUNT_ID}:secret:{name}-{new_uuid()[:6]}"
+ arn = f"arn:aws:secretsmanager:{REGION}:{get_account_id()}:secret:{name}-{new_uuid()[:6]}"
vid = new_uuid()
now = time.time()
diff --git a/ministack/services/servicediscovery.py b/ministack/services/servicediscovery.py
index dc66ecbf..11ffcef4 100644
--- a/ministack/services/servicediscovery.py
+++ b/ministack/services/servicediscovery.py
@@ -10,12 +10,11 @@ import os
import time
import xml.etree.ElementTree as ET
-from ministack.core.responses import error_response_json, json_response, new_uuid
+from ministack.core.responses import get_account_id, error_response_json, json_response, new_uuid
from ministack.services import route53
logger = logging.getLogger("servicediscovery")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# In-memory state
@@ -124,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}:{ACCOUNT_ID}:namespace/{ns_id}"
+ return f"arn:aws:servicediscovery:{REGION}:{get_account_id()}:namespace/{ns_id}"
def _service_arn(svc_id: str) -> str:
- return f"arn:aws:servicediscovery:{REGION}:{ACCOUNT_ID}:service/{svc_id}"
+ return f"arn:aws:servicediscovery:{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 64e7ca00..db5f2c65 100644
--- a/ministack/services/ses.py
+++ b/ministack/services/ses.py
@@ -39,11 +39,10 @@ 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 new_uuid
+from ministack.core.responses import get_account_id, new_uuid
logger = logging.getLogger("ses")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
_identities: dict = {}
diff --git a/ministack/services/ses_v2.py b/ministack/services/ses_v2.py
index 99e94dac..4b7e2f86 100644
--- a/ministack/services/ses_v2.py
+++ b/ministack/services/ses_v2.py
@@ -15,12 +15,11 @@ import os
import re
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import json_response, new_uuid, now_iso
+from ministack.core.responses import get_account_id, json_response, new_uuid, now_iso
from ministack.services.ses import _build_mime_message, _smtp_relay
logger = logging.getLogger("ses-v2")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
_identities: dict = {} # identity -> dict
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index 66c702c5..89be586e 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -24,12 +24,11 @@ _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 new_uuid
+from ministack.core.responses import get_account_id, new_uuid
from ministack.services import sqs as _sqs
logger = logging.getLogger("sns")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
from ministack.core.persistence import load_state, PERSIST_STATE
@@ -102,7 +101,7 @@ def _create_topic(params):
if not name:
return _error("InvalidParameterException", "Name is required", 400)
- arn = f"arn:aws:sns:{REGION}:{ACCOUNT_ID}:{name}"
+ arn = f"arn:aws:sns:{REGION}:{get_account_id()}:{name}"
if arn not in _topics:
default_policy = json.dumps({
"Version": "2008-10-17",
@@ -113,7 +112,7 @@ def _create_topic(params):
"Principal": {"AWS": "*"},
"Action": ["SNS:Publish", "SNS:Subscribe", "SNS:Receive"],
"Resource": arn,
- "Condition": {"StringEquals": {"AWS:SourceOwner": ACCOUNT_ID}},
+ "Condition": {"StringEquals": {"AWS:SourceOwner": get_account_id()}},
}],
})
_topics[arn] = {
@@ -122,7 +121,7 @@ def _create_topic(params):
"attributes": {
"TopicArn": arn,
"DisplayName": name,
- "Owner": ACCOUNT_ID,
+ "Owner": get_account_id(),
"Policy": default_policy,
"SubscriptionsConfirmed": "0",
"SubscriptionsPending": "0",
@@ -238,14 +237,14 @@ def _subscribe(params):
"endpoint": endpoint,
"confirmed": not needs_confirmation,
"topic_arn": topic_arn,
- "owner": ACCOUNT_ID,
+ "owner": get_account_id(),
"token": new_uuid() if needs_confirmation else None,
"attributes": {
"SubscriptionArn": sub_arn,
"TopicArn": topic_arn,
"Protocol": protocol,
"Endpoint": endpoint,
- "Owner": ACCOUNT_ID,
+ "Owner": get_account_id(),
"ConfirmationWasAuthenticated": "true" if not needs_confirmation else "false",
"PendingConfirmation": "true" if needs_confirmation else "false",
"RawMessageDelivery": "false",
@@ -327,7 +326,7 @@ def _list_subscriptions(params):
members += (
"<member>"
f"<SubscriptionArn>{sub['arn']}</SubscriptionArn>"
- f"<Owner>{sub.get('owner', ACCOUNT_ID)}</Owner>"
+ f"<Owner>{sub.get('owner', get_account_id())}</Owner>"
f"<TopicArn>{sub['topic_arn']}</TopicArn>"
f"<Protocol>{sub['protocol']}</Protocol>"
f"<Endpoint>{sub['endpoint']}</Endpoint>"
@@ -350,7 +349,7 @@ def _list_subscriptions_by_topic(params):
members += (
"<member>"
f"<SubscriptionArn>{sub['arn']}</SubscriptionArn>"
- f"<Owner>{sub.get('owner', ACCOUNT_ID)}</Owner>"
+ f"<Owner>{sub.get('owner', get_account_id())}</Owner>"
f"<TopicArn>{topic_arn}</TopicArn>"
f"<Protocol>{sub['protocol']}</Protocol>"
f"<Endpoint>{sub['endpoint']}</Endpoint>"
@@ -720,7 +719,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}:{ACCOUNT_ID}:app/{platform}/{name}"
+ arn = f"arn:aws:sns:{REGION}:{get_account_id()}:app/{platform}/{name}"
attrs = {}
i = 1
while _p(params, f"Attributes.entry.{i}.key"):
@@ -996,7 +995,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}:{ACCOUNT_ID}:example",
+ "UnsubscribeURL": f"http://{_HOST}:{_PORT}/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:{REGION}:{get_account_id()}:example",
}
if message_attributes:
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index fd2638fd..6ed9ac5e 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 md5_hash, new_uuid, now_iso
+from ministack.core.responses import get_account_id, md5_hash, new_uuid, now_iso
logger = logging.getLogger("sqs")
@@ -62,7 +62,6 @@ _restored = load_state("sqs")
if _restored:
restore_state(_restored)
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
DEFAULT_HOST = os.environ.get("MINISTACK_HOST", "localhost")
DEFAULT_PORT = os.environ.get("GATEWAY_PORT", "4566")
@@ -82,7 +81,7 @@ class _Err(Exception):
# ── Queue URL ───────────────────────────────────────────────
def _queue_url(name: str) -> str:
- return f"http://{DEFAULT_HOST}:{DEFAULT_PORT}/{ACCOUNT_ID}/{name}"
+ return f"http://{DEFAULT_HOST}:{DEFAULT_PORT}/{get_account_id()}/{name}"
# ────────────────────────────────────────────────────────────
@@ -182,7 +181,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}:{ACCOUNT_ID}:{name}",
+ "QueueArn": f"arn:aws:sqs:{REGION}:{get_account_id()}:{name}",
"CreatedTimestamp": ts,
"LastModifiedTimestamp": ts,
"VisibilityTimeout": "30",
@@ -296,7 +295,7 @@ def _act_send_message(data: dict, qurl: str) -> dict:
"first_receive_at": None,
"message_attributes": msg_attrs,
"sys": {
- "SenderId": ACCOUNT_ID,
+ "SenderId": get_account_id(),
"SentTimestamp": str(int(now * 1000)),
},
"group_id": group_id,
@@ -619,7 +618,7 @@ def _ensure_msg_fields(m: dict) -> None:
if "sys" not in m:
sent = m["sent_at"]
m["sys"] = {
- "SenderId": ACCOUNT_ID,
+ "SenderId": get_account_id(),
"SentTimestamp": str(int(sent * 1000)),
}
m.setdefault("group_id", None)
@@ -747,7 +746,7 @@ def _build_sys_attrs(msg: dict, names: list) -> dict:
want_all = "All" in names
r: dict = {}
if want_all or "SenderId" in names:
- r["SenderId"] = msg["sys"].get("SenderId", ACCOUNT_ID)
+ r["SenderId"] = msg["sys"].get("SenderId", get_account_id())
if want_all or "SentTimestamp" in names:
r["SentTimestamp"] = msg["sys"].get("SentTimestamp", "0")
if want_all or "ApproximateReceiveCount" in names:
diff --git a/ministack/services/ssm.py b/ministack/services/ssm.py
index 6ad3a641..7fd99066 100644
--- a/ministack/services/ssm.py
+++ b/ministack/services/ssm.py
@@ -15,11 +15,10 @@ import logging
import time
from datetime import datetime, timezone
-from ministack.core.responses import error_response_json, json_response, new_uuid
+from ministack.core.responses import get_account_id, error_response_json, json_response, new_uuid
logger = logging.getLogger("ssm")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
DEFAULT_PAGE_SIZE = 10
@@ -55,7 +54,7 @@ def _now_epoch() -> float:
def _param_arn(name: str) -> str:
- return f"arn:aws:ssm:{REGION}:{ACCOUNT_ID}:parameter{name}"
+ return f"arn:aws:ssm:{REGION}:{get_account_id()}:parameter{name}"
def _encode_next_token(index: int) -> str:
@@ -153,7 +152,7 @@ def _put_parameter(data):
"KeyId": key_id,
"Version": version,
"LastModifiedDate": now,
- "LastModifiedUser": f"arn:aws:iam::{ACCOUNT_ID}:root",
+ "LastModifiedUser": f"arn:aws:iam::{get_account_id()}:root",
"Description": record["Description"],
"AllowedPattern": record["AllowedPattern"],
"Tier": record["Tier"],
@@ -296,7 +295,7 @@ def _describe_parameters(data):
"Type": param["Type"],
"Version": param["Version"],
"LastModifiedDate": param["LastModifiedDate"],
- "LastModifiedUser": f"arn:aws:iam::{ACCOUNT_ID}:root",
+ "LastModifiedUser": f"arn:aws:iam::{get_account_id()}:root",
"ARN": param["ARN"],
"DataType": param["DataType"],
"Description": param.get("Description", ""),
@@ -370,7 +369,7 @@ def _get_parameter_history(data):
"Type": entry["Type"],
"Version": entry["Version"],
"LastModifiedDate": entry["LastModifiedDate"],
- "LastModifiedUser": entry.get("LastModifiedUser", f"arn:aws:iam::{ACCOUNT_ID}:root"),
+ "LastModifiedUser": entry.get("LastModifiedUser", f"arn:aws:iam::{get_account_id()}:root"),
"Description": entry.get("Description", ""),
"DataType": entry.get("DataType", "text"),
"Tier": entry.get("Tier", "Standard"),
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index af09de45..e505518f 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -32,6 +32,7 @@ from datetime import datetime, timezone
from ministack.core.persistence import PERSIST_STATE, load_state
from ministack.core.responses import (
+ get_account_id,
error_response_json,
json_response,
new_uuid,
@@ -40,7 +41,6 @@ from ministack.core.responses import (
logger = logging.getLogger("states")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# SFN mock config — compatible with LocalStack's SFN_MOCK_CONFIG / LOCALSTACK_SFN_MOCK_CONFIG
@@ -237,7 +237,7 @@ def _create_state_machine(data):
if not name:
return error_response_json("ValidationException", "name is required", 400)
- arn = f"arn:aws:states:{REGION}:{ACCOUNT_ID}:stateMachine:{name}"
+ arn = f"arn:aws:states:{REGION}:{get_account_id()}:stateMachine:{name}"
if arn in _state_machines:
return error_response_json(
"StateMachineAlreadyExists",
@@ -249,7 +249,7 @@ def _create_state_machine(data):
"name": name,
"definition": data.get("definition", "{}"),
"roleArn": data.get("roleArn",
- f"arn:aws:iam::{ACCOUNT_ID}:role/StepFunctionsRole"),
+ f"arn:aws:iam::{get_account_id()}:role/StepFunctionsRole"),
"type": data.get("type", "STANDARD"),
"creationDate": ts,
"status": "ACTIVE",
@@ -346,7 +346,7 @@ def _start_execution(data):
sm = _state_machines[sm_arn]
name = data.get("name") or new_uuid()
- exec_arn = (f"arn:aws:states:{REGION}:{ACCOUNT_ID}"
+ exec_arn = (f"arn:aws:states:{REGION}:{get_account_id()}"
f":execution:{sm['name']}:{name}")
start_date = now_iso()
@@ -484,7 +484,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}:{ACCOUNT_ID}"
+ exec_arn = (f"arn:aws:states:{REGION}:{get_account_id()}"
f":execution:{sm['name']}:{name}")
start_date = now_iso()
@@ -611,7 +611,7 @@ def _create_activity(data):
if not name:
return error_response_json("ValidationException", "name is required", 400)
- arn = f"arn:aws:states:{REGION}:{ACCOUNT_ID}:activity:{name}"
+ arn = f"arn:aws:states:{REGION}:{get_account_id()}:activity:{name}"
if arn in _activities:
return error_response_json(
"ActivityAlreadyExists", f"Activity already exists: {arn}", 400)
@@ -780,7 +780,7 @@ def _test_state(data):
ctx = {}
else:
ctx = {}
- ctx.setdefault("Execution", {"Id": f"arn:aws:states:{REGION}:{ACCOUNT_ID}:execution:test:{new_uuid()}", "Name": "test", "StartTime": now_iso()})
+ ctx.setdefault("Execution", {"Id": f"arn:aws:states:{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()}
diff --git a/ministack/services/waf.py b/ministack/services/waf.py
index 2cc0a0d1..4c9d224f 100644
--- a/ministack/services/waf.py
+++ b/ministack/services/waf.py
@@ -15,11 +15,10 @@ import os
import logging
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import error_response_json, json_response, new_uuid, now_iso
+from ministack.core.responses import get_account_id, error_response_json, json_response, new_uuid, now_iso
logger = logging.getLogger("wafv2")
-ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
_web_acls: dict = {} # id -> webacl
@@ -57,15 +56,15 @@ def _waf_err(code, message):
def _acl_arn(name, uid):
- return f"arn:aws:wafv2:{REGION}:{ACCOUNT_ID}:regional/webacl/{name}/{uid}"
+ return f"arn:aws:wafv2:{REGION}:{get_account_id()}:regional/webacl/{name}/{uid}"
def _ipset_arn(name, uid):
- return f"arn:aws:wafv2:{REGION}:{ACCOUNT_ID}:regional/ipset/{name}/{uid}"
+ return f"arn:aws:wafv2:{REGION}:{get_account_id()}:regional/ipset/{name}/{uid}"
def _rg_arn(name, uid):
- return f"arn:aws:wafv2:{REGION}:{ACCOUNT_ID}:regional/rulegroup/{name}/{uid}"
+ return f"arn:aws:wafv2:{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 4c1699c0..c2ed06f2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.1.53"
+version = "1.1.54"
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 70c9f758..2ebc2b63 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -1061,3 +1061,39 @@ def test_cfn_ec2_launch_template(cfn, ec2):
desc2 = ec2.describe_launch_templates(LaunchTemplateIds=[lt_id])
assert len(desc2["LaunchTemplates"]) == 0
+
+
+def test_cfn_ssm_parameter_timestamp_is_epoch(cfn, ssm):
+ """SSM parameters created via CloudFormation must store LastModifiedDate
+ as an epoch float, not an ISO string. The JS SDK v3 deserializes SSM
+ timestamps with parseEpochTimestamp() which throws 'Expected real number,
+ got implicit NaN' when the value is an ISO string. This broke cdk deploy."""
+ template = json.dumps({
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Param": {
+ "Type": "AWS::SSM::Parameter",
+ "Properties": {
+ "Name": "/cfn-test/epoch-check",
+ "Type": "String",
+ "Value": "42",
+ },
+ },
+ },
+ })
+ cfn.create_stack(StackName="cfn-ssm-epoch", TemplateBody=template)
+ _wait_stack(cfn, "cfn-ssm-epoch")
+
+ try:
+ resp = ssm.get_parameter(Name="/cfn-test/epoch-check")
+ last_mod = resp["Parameter"]["LastModifiedDate"]
+ # boto3 converts epoch floats to datetime objects automatically.
+ # If it were an ISO string, boto3 would leave it as a string or error.
+ import datetime
+ assert isinstance(last_mod, datetime.datetime), (
+ f"LastModifiedDate should be datetime (from epoch float), "
+ f"got {type(last_mod).__name__}: {last_mod}"
+ )
+ finally:
+ cfn.delete_stack(StackName="cfn-ssm-epoch")
+ _wait_stack(cfn, "cfn-ssm-epoch")
diff --git a/tests/test_multitenancy.py b/tests/test_multitenancy.py
new file mode 100644
index 00000000..0be6a9a4
--- /dev/null
+++ b/tests/test_multitenancy.py
@@ -0,0 +1,140 @@
+"""
+Tests for multi-tenancy: dynamic Account ID derived from AWS_ACCESS_KEY_ID.
+
+When the access key is a 12-digit number, MiniStack uses it as the Account ID
+in all ARN generation. Non-numeric keys (like "test") fall back to the default
+000000000000.
+"""
+
+import os
+
+import boto3
+import pytest
+from botocore.config import Config
+
+ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+REGION = "us-east-1"
+
+
+def _client(service, access_key="test"):
+ """Create a boto3 client with a specific access key."""
+ return boto3.client(
+ service,
+ endpoint_url=ENDPOINT,
+ aws_access_key_id=access_key,
+ aws_secret_access_key="test",
+ region_name=REGION,
+ config=Config(region_name=REGION, retries={"max_attempts": 0}),
+ )
+
+
+# ── STS GetCallerIdentity ─────────────────────────────────
+
+def test_default_account_id():
+ """Non-numeric access key falls back to 000000000000."""
+ sts = _client("sts", access_key="test")
+ resp = sts.get_caller_identity()
+ assert resp["Account"] == "000000000000"
+
+
+def test_12_digit_access_key_becomes_account_id():
+ """A 12-digit numeric access key is used as the Account ID."""
+ sts = _client("sts", access_key="123456789012")
+ resp = sts.get_caller_identity()
+ assert resp["Account"] == "123456789012"
+
+
+def test_different_12_digit_keys_get_different_accounts():
+ """Two different 12-digit keys produce different account IDs."""
+ sts_a = _client("sts", access_key="111111111111")
+ sts_b = _client("sts", access_key="222222222222")
+ assert sts_a.get_caller_identity()["Account"] == "111111111111"
+ assert sts_b.get_caller_identity()["Account"] == "222222222222"
+
+
+def test_non_12_digit_numeric_falls_back():
+ """A numeric key that isn't exactly 12 digits uses the default."""
+ sts = _client("sts", access_key="12345")
+ resp = sts.get_caller_identity()
+ assert resp["Account"] == "000000000000"
+
+
+# ── S3: ARN isolation ─────────────────────────────────────
+
+def test_sqs_queue_arn_uses_dynamic_account():
+ """SQS queue ARN reflects the 12-digit access key as account ID."""
+ sqs = _client("sqs", access_key="048408301323")
+ q = sqs.create_queue(QueueName="mt-test-queue")
+ try:
+ attrs = sqs.get_queue_attributes(
+ QueueUrl=q["QueueUrl"], AttributeNames=["QueueArn"]
+ )
+ arn = attrs["Attributes"]["QueueArn"]
+ assert "048408301323" in arn, f"Expected account 048408301323 in ARN: {arn}"
+ finally:
+ sqs.delete_queue(QueueUrl=q["QueueUrl"])
+
+
+def test_sqs_queues_isolated_by_account():
+ """Queues created with different account keys are separate namespaces."""
+ sqs_a = _client("sqs", access_key="111111111111")
+ sqs_b = _client("sqs", access_key="222222222222")
+
+ q_a = sqs_a.create_queue(QueueName="isolation-test")
+ try:
+ q_b = sqs_b.create_queue(QueueName="isolation-test")
+ try:
+ # Both should get their own queue with their own account in the ARN
+ attrs_a = sqs_a.get_queue_attributes(
+ QueueUrl=q_a["QueueUrl"], AttributeNames=["QueueArn"]
+ )
+ attrs_b = sqs_b.get_queue_attributes(
+ QueueUrl=q_b["QueueUrl"], AttributeNames=["QueueArn"]
+ )
+ assert "111111111111" in attrs_a["Attributes"]["QueueArn"]
+ assert "222222222222" in attrs_b["Attributes"]["QueueArn"]
+ finally:
+ sqs_b.delete_queue(QueueUrl=q_b["QueueUrl"])
+ finally:
+ sqs_a.delete_queue(QueueUrl=q_a["QueueUrl"])
+
+
+# ── Lambda: ARN uses dynamic account ──────────────────────
+
+def test_lambda_function_arn_uses_dynamic_account():
+ """Lambda function ARN reflects the 12-digit access key."""
+ lam = _client("lambda", access_key="999888777666")
+ try:
+ lam.create_function(
+ FunctionName="mt-func",
+ Runtime="python3.12",
+ Role="arn:aws:iam::999888777666:role/test",
+ Handler="index.handler",
+ Code={"ZipFile": b"fake"},
+ )
+ resp = lam.get_function(FunctionName="mt-func")
+ arn = resp["Configuration"]["FunctionArn"]
+ assert "999888777666" in arn, f"Expected account in ARN: {arn}"
+ finally:
+ try:
+ lam.delete_function(FunctionName="mt-func")
+ except Exception:
+ pass
+
+
+# ── SSM: ARN uses dynamic account ────────────────────────
+
+def test_ssm_parameter_arn_uses_dynamic_account():
+ """SSM parameter ARN reflects the 12-digit access key."""
+ ssm = _client("ssm", access_key="048408301323")
+ ssm.put_parameter(
+ Name="/mt-test/param1",
+ Value="hello",
+ Type="String",
+ )
+ try:
+ resp = ssm.get_parameter(Name="/mt-test/param1")
+ arn = resp["Parameter"]["ARN"]
+ assert "048408301323" in arn, f"Expected account in ARN: {arn}"
+ finally:
+ ssm.delete_parameter(Name="/mt-test/param1")
diff --git a/tests/test_rds_data.py b/tests/test_rds_data.py
index 6195c09e..a0d56fd2 100644
--- a/tests/test_rds_data.py
+++ b/tests/test_rds_data.py
@@ -193,3 +193,55 @@ def test_execute_invalid_json():
body = json.loads(e.read())
assert status == 400
assert "Invalid JSON" in body.get("message", body.get("Message", ""))
+
+
+# ── Parameter conversion (unit tests) ─────────────────────
+
+def test_convert_parameters_all_types():
+ """_convert_parameters handles all RDS Data API value types."""
+ from ministack.services.rds_data import _convert_parameters
+
+ params = [
+ {"name": "s", "value": {"stringValue": "hello"}},
+ {"name": "n", "value": {"longValue": 42}},
+ {"name": "d", "value": {"doubleValue": 3.14}},
+ {"name": "b", "value": {"booleanValue": True}},
+ {"name": "null_val", "value": {"isNull": True}},
+ {"name": "blob", "value": {"blobValue": "AQID"}}, # base64 of b'\x01\x02\x03'
+ ]
+ result = _convert_parameters(params)
+ assert result["s"] == "hello"
+ assert result["n"] == 42
+ assert result["d"] == 3.14
+ assert result["b"] is True
+ assert result["null_val"] is None
+ assert result["blob"] == b"\x01\x02\x03"
+
+
+def test_convert_parameters_empty():
+ """_convert_parameters returns empty dict for empty/None input."""
+ from ministack.services.rds_data import _convert_parameters
+
+ assert _convert_parameters([]) == {}
+ assert _convert_parameters(None) == {}
+
+
+def test_convert_parameters_missing_name_skipped():
+ """Parameters without a name are skipped."""
+ from ministack.services.rds_data import _convert_parameters
+
+ params = [
+ {"value": {"stringValue": "no-name"}},
+ {"name": "valid", "value": {"stringValue": "ok"}},
+ ]
+ result = _convert_parameters(params)
+ assert len(result) == 1
+ assert result["valid"] == "ok"
+
+
+def test_convert_parameters_empty_value():
+ """Parameter with empty value object returns None."""
+ from ministack.services.rds_data import _convert_parameters
+
+ result = _convert_parameters([{"name": "x", "value": {}}])
+ assert result["x"] is None