Skip to content

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

fix(cfn): nested stacks (#696)

Nahuel Nuceraf22283383bed
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f9a468a3..ed980a58 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,9 +9,15 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [1.3.47] — 2026-05-22
+### Added
+- **CloudFormation nested stacks** — `AWS::CloudFormation::Stack` resources now provision their child template (fetched from `TemplateURL`), pass `Parameters` through, expose child `Outputs` via `Fn::GetAtt: [Nested, Outputs.<Name>]`, and cascade delete/update with the parent. `Ref` of the nested resource resolves to the child stack ARN, matching real AWS. Reported by @jayalfredprufrock.
+
### Fixed
-- **CloudFront invalidations** — repeated `CreateInvalidation` calls with the same `CallerReference` now return the existing invalidation for that distribution.
-- **S3 `DeleteObjects`** — Objects deleted in a batch will now be deleted from disk, much like `DeleteObject`.
+- **CloudFront invalidations** — repeated `CreateInvalidation` calls with the same `CallerReference` now return the existing invalidation for that distribution; path comparison is set-based so re-submitting the same paths in a different order is treated as idempotent rather than as a divergent batch. Contributed by @CoffeeRaptor.
+- **S3 `DeleteObjects`** — objects deleted in a batch are now removed from disk, mirroring `DeleteObject`. Contributed by @parafoxia.
+- **RDS persistence-restore** — backing Docker containers are now respawned for persisted DB instances at restart, with status flowing `creating → available/failed` based on container liveness instead of staying frozen as zombie metadata. Per-instance threads now carry the original account context so multi-tenant restores land writes on the correct account. Reported by @doodaz.
+- **Cognito `/oauth2/idpresponse` and `/saml2/idpresponse`** — distinct error messages and a server-side WARNING log when the OIDC `state` / SAML `RelayState` doesn't match any pending authorize flow, so configuration drift (expired or unknown state) is diagnosable without staring at an opaque `InvalidParameterException`. Reported by @ocr-lasagna.
+- **Cognito `/{poolId}/.well-known/jwks.json` and `/{poolId}/.well-known/openid-configuration`** no longer shadow S3 — these endpoints now fall through to the S3 handler when the pool prefix doesn't match a registered user pool, so apps storing their own `.well-known/*` documents in an S3 bucket get the actual object back instead of a fake Cognito JWKS. Real AWS only serves these for actual pools.
---
diff --git a/ministack/app.py b/ministack/app.py
index cde6f013..66964daf 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -598,16 +598,24 @@ def _handle_lambda_download_request(path: str, method: str):
async def _handle_cognito_get_request(method: str, path: str, headers: dict, query_params: dict):
"""Handle Cognito GET endpoints that do not require request body parsing."""
if "/.well-known/" in path and method == "GET":
+ # Real AWS serves /<poolId>/.well-known/jwks.json only for actual user
+ # pools — any other pool prefix errors. Fall through to S3 when the
+ # pool isn't registered so an S3 object stored under a .well-known/
+ # key isn't shadowed by a fake Cognito JWKS body.
if path.endswith("/.well-known/jwks.json"):
pool_id = path.rsplit("/.well-known/jwks.json", 1)[0].lstrip("/")
if pool_id:
- return _get_module("cognito").well_known_jwks(pool_id)
+ cognito = _get_module("cognito")
+ if cognito._get_pool_unscoped(pool_id) is not None:
+ return cognito.well_known_jwks(pool_id)
elif path.endswith("/.well-known/openid-configuration"):
pool_id = path.rsplit("/.well-known/openid-configuration", 1)[0].lstrip("/")
if pool_id:
- region = extract_region(headers) or "us-east-1"
- host = headers.get("host") or headers.get("Host")
- return _get_module("cognito").well_known_openid_configuration(pool_id, region, host)
+ cognito = _get_module("cognito")
+ if cognito._get_pool_unscoped(pool_id) is not None:
+ region = extract_region(headers) or "us-east-1"
+ host = headers.get("host") or headers.get("Host")
+ return cognito.well_known_openid_configuration(pool_id, region, host)
if path == "/oauth2/authorize" and method == "GET":
return _get_module("cognito").handle_oauth2_authorize(method, path, headers, query_params)
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index bda26d17..8fd7f229 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -1049,6 +1049,292 @@ def _cfn_wait_condition_handle_create(logical_id, props, stack_name):
return pid, {"Ref": url}
+# --- CloudFormation Nested Stack (AWS::CloudFormation::Stack) ---
+
+def _cfn_nested_stack_deploy(logical_id, props, parent_stack_name, *,
+ previous_physical_id=None, previous_props=None):
+ """Provision an `AWS::CloudFormation::Stack` nested-stack resource.
+
+ Mirrors the synchronous core of `stacks._deploy_stack_async` but runs
+ inline so the parent's deploy loop can read the child's Outputs (exposed
+ as `Outputs.<Name>` keys on the returned attrs dict so `Fn::GetAtt:
+ [Nested, Outputs.X]` resolves natively).
+
+ Returns ``(child_stack_id, attrs)`` where ``attrs["Outputs.<Name>"]``
+ carries each output value. ``Outputs.<Name>`` keys match the dotted
+ sub-attribute form CDK and console-built templates emit.
+ """
+ import copy
+ from ministack.core.responses import get_account_id, get_region, new_uuid
+ from ministack.services.cloudformation import (
+ _stack_events, _stacks,
+ )
+ from ministack.services.cloudformation.engine import (
+ _evaluate_conditions, _parse_template, _resolve_parameters,
+ _resolve_refs, _topological_sort,
+ )
+ from ministack.services.cloudformation.helpers import _resolve_template
+ from ministack.services.cloudformation.stacks import _add_event
+
+ template_url = props.get("TemplateURL")
+ if not template_url:
+ raise ValueError(
+ "AWS::CloudFormation::Stack requires TemplateURL "
+ "(inline TemplateBody is not supported by real AWS either)"
+ )
+
+ template_body, err = _resolve_template({"TemplateURL": [template_url]})
+ if err is not None:
+ raise ValueError(f"Failed to fetch nested-stack template: {template_url}")
+ if not template_body:
+ raise ValueError(f"Nested-stack template empty at {template_url}")
+
+ template = _parse_template(template_body)
+
+ raw_param_props = props.get("Parameters") or {}
+ if isinstance(raw_param_props, dict):
+ provided_params = [
+ {"Key": k, "Value": "" if v is None else str(v)}
+ for k, v in raw_param_props.items()
+ ]
+ else:
+ provided_params = []
+ param_values = _resolve_parameters(template, provided_params)
+
+ is_update = previous_physical_id is not None
+ if is_update and previous_physical_id in _stacks:
+ child_name = previous_physical_id
+ previous_stack_snapshot = copy.deepcopy(_stacks[child_name])
+ else:
+ child_name = f"{parent_stack_name}-{logical_id}-{new_uuid()[:12]}"
+ previous_stack_snapshot = None
+
+ child_stack_id = (
+ f"arn:aws:cloudformation:{get_region()}:{get_account_id()}:"
+ f"stack/{child_name}/{new_uuid()}"
+ )
+ if previous_stack_snapshot:
+ child_stack_id = previous_stack_snapshot.get("StackId", child_stack_id)
+
+ status_prefix = "UPDATE" if is_update else "CREATE"
+ child_stack = {
+ "StackName": child_name,
+ "StackId": child_stack_id,
+ "StackStatus": f"{status_prefix}_IN_PROGRESS",
+ "StackStatusReason": "",
+ "CreationTime": now_iso(),
+ "LastUpdatedTime": now_iso(),
+ "Description": template.get("Description", ""),
+ "Parameters": [
+ {"ParameterKey": k, "ParameterValue": v["Value"], "NoEcho": v["NoEcho"]}
+ for k, v in param_values.items()
+ ],
+ "Tags": [],
+ "Outputs": [],
+ "DisableRollback": True,
+ "_resources": (previous_stack_snapshot.get("_resources", {})
+ if previous_stack_snapshot else {}),
+ "_template": template,
+ "_template_body": template_body,
+ "_resolved_params": param_values,
+ "_conditions": _evaluate_conditions(template, param_values),
+ "_parent_stack_name": parent_stack_name,
+ "RootId": _cr_stack_id(parent_stack_name),
+ "ParentId": _cr_stack_id(parent_stack_name),
+ }
+ _stacks[child_name] = child_stack
+ _stack_events.setdefault(child_stack_id, [])
+
+ _add_event(child_stack_id, child_name, child_name,
+ "AWS::CloudFormation::Stack", f"{status_prefix}_IN_PROGRESS",
+ physical_id=child_stack_id)
+
+ mappings = template.get("Mappings", {})
+ conditions = child_stack["_conditions"]
+ resources_defs = template.get("Resources", {})
+ outputs_defs = template.get("Outputs", {})
+
+ try:
+ ordered = _topological_sort(resources_defs, conditions)
+ except ValueError as exc:
+ child_stack["StackStatus"] = f"{status_prefix}_FAILED"
+ child_stack["StackStatusReason"] = str(exc)
+ _add_event(child_stack_id, child_name, child_name,
+ "AWS::CloudFormation::Stack", f"{status_prefix}_FAILED",
+ str(exc), child_stack_id)
+ raise
+
+ provisioned: dict = child_stack["_resources"]
+ prev_resources = (previous_stack_snapshot.get("_resources", {})
+ if previous_stack_snapshot else {})
+
+ for child_logical_id in ordered:
+ res_def = resources_defs[child_logical_id]
+ cond = res_def.get("Condition")
+ if cond and not conditions.get(cond, True):
+ continue
+ resource_type = res_def.get("Type", "AWS::CloudFormation::CustomResource")
+ raw_props = res_def.get("Properties", {})
+ resolved_props = _resolve_refs(
+ copy.deepcopy(raw_props), provisioned, param_values,
+ conditions, mappings, child_name, child_stack_id,
+ )
+ if isinstance(resolved_props, dict):
+ resolved_props = {k: v for k, v in resolved_props.items()
+ if v is not _NO_VALUE_SENTINEL()}
+
+ _add_event(child_stack_id, child_name, child_logical_id, resource_type,
+ f"{status_prefix}_IN_PROGRESS")
+ try:
+ prev = prev_resources.get(child_logical_id)
+ if prev:
+ physical_id, attrs = _update_resource(
+ resource_type, prev.get("PhysicalResourceId", child_logical_id),
+ prev.get("Properties", {}), resolved_props, child_name,
+ child_logical_id,
+ )
+ else:
+ physical_id, attrs = _provision_resource(
+ resource_type, child_logical_id, resolved_props, child_name,
+ )
+ except Exception as exc:
+ child_stack["StackStatus"] = f"{status_prefix}_FAILED"
+ child_stack["StackStatusReason"] = (
+ f"Resource {child_logical_id} failed: {exc}"
+ )
+ _add_event(child_stack_id, child_name, child_logical_id, resource_type,
+ f"{status_prefix}_FAILED", str(exc))
+ raise
+
+ provisioned[child_logical_id] = {
+ "PhysicalResourceId": physical_id,
+ "ResourceType": resource_type,
+ "ResourceStatus": f"{status_prefix}_COMPLETE",
+ "LogicalResourceId": child_logical_id,
+ "Properties": resolved_props,
+ "Attributes": attrs,
+ "Timestamp": now_iso(),
+ }
+ _add_event(child_stack_id, child_name, child_logical_id, resource_type,
+ f"{status_prefix}_COMPLETE", physical_id=physical_id)
+
+ if is_update:
+ for stale_id in set(prev_resources) - set(provisioned):
+ old = prev_resources[stale_id]
+ try:
+ _delete_resource(old.get("ResourceType", ""),
+ old.get("PhysicalResourceId", ""),
+ old.get("Properties", {}),
+ child_name, stale_id)
+ except Exception as exc:
+ logger.warning("Nested-stack %s: failed to delete pruned %s: %s",
+ child_name, stale_id, exc)
+
+ resolved_outputs = []
+ output_attrs: dict[str, str] = {}
+ for out_name, out_def in outputs_defs.items():
+ cond = out_def.get("Condition")
+ if cond and not conditions.get(cond, True):
+ continue
+ out_value = _resolve_refs(
+ copy.deepcopy(out_def.get("Value", "")),
+ provisioned, param_values, conditions,
+ mappings, child_name, child_stack_id,
+ )
+ resolved_outputs.append({
+ "OutputKey": out_name,
+ "OutputValue": str(out_value),
+ "Description": out_def.get("Description", ""),
+ })
+ output_attrs[f"Outputs.{out_name}"] = str(out_value)
+
+ child_stack["Outputs"] = resolved_outputs
+ child_stack["StackStatus"] = f"{status_prefix}_COMPLETE"
+ _add_event(child_stack_id, child_name, child_name,
+ "AWS::CloudFormation::Stack", f"{status_prefix}_COMPLETE",
+ physical_id=child_stack_id)
+
+ # Real AWS: Ref of AWS::CloudFormation::Stack returns the child StackId
+ # (ARN), not the stack name. DescribeStacks/_delete handlers below accept
+ # either form for lookup so callers using Ref->DescribeStacks keep working.
+ return child_stack_id, output_attrs
+
+
+def _NO_VALUE_SENTINEL():
+ from ministack.services.cloudformation.engine import _NO_VALUE
+ return _NO_VALUE
+
+
+def _cfn_nested_stack_create(logical_id, props, stack_name):
+ return _cfn_nested_stack_deploy(logical_id, props, stack_name)
+
+
+def _cfn_nested_stack_update(physical_id, old_props, new_props, stack_name):
+ return _cfn_nested_stack_deploy(
+ physical_id, new_props, stack_name,
+ previous_physical_id=_nested_stack_lookup_name(physical_id),
+ previous_props=old_props,
+ )
+
+
+def _nested_stack_lookup_name(physical_id_or_arn):
+ """Resolve a nested-stack physical id (StackId ARN or stack name) to its
+ `_stacks` dict key. Returns the input if no ARN match is found."""
+ from ministack.services.cloudformation import _stacks
+ if physical_id_or_arn in _stacks:
+ return physical_id_or_arn
+ for name, stk in _stacks.items():
+ if stk.get("StackId") == physical_id_or_arn:
+ return name
+ return physical_id_or_arn
+
+
+def _cfn_nested_stack_delete(physical_id, props):
+ from ministack.services.cloudformation import _exports, _stacks
+ child_name = _nested_stack_lookup_name(physical_id)
+ child_stack = _stacks.get(child_name)
+ if not child_stack:
+ return
+
+ child_stack_id = child_stack.get("StackId", physical_id)
+ resources = child_stack.get("_resources", {})
+ template = child_stack.get("_template", {})
+ res_defs = template.get("Resources", {}) if template else {}
+ conditions = child_stack.get("_conditions", {})
+ try:
+ from ministack.services.cloudformation.engine import _topological_sort
+ ordered = (_topological_sort(res_defs, conditions)
+ if res_defs else list(resources.keys()))
+ except Exception:
+ ordered = list(resources.keys())
+
+ for child_logical_id in reversed(ordered):
+ res = resources.get(child_logical_id)
+ if not res:
+ continue
+ try:
+ _delete_resource(
+ res.get("ResourceType", ""),
+ res.get("PhysicalResourceId", ""),
+ res.get("Properties", {}),
+ child_name, child_logical_id,
+ )
+ except Exception as exc:
+ logger.warning("Nested-stack %s: delete of %s failed: %s",
+ child_name, child_logical_id, exc)
+
+ for out in child_stack.get("Outputs", []):
+ export_name = out.get("ExportName")
+ if export_name:
+ _exports.pop(export_name, None)
+
+ child_stack["StackStatus"] = "DELETE_COMPLETE"
+ child_stack["_resources"] = {}
+ # Leave the stack entry in _stacks so DescribeStacks on the child id still
+ # returns DELETE_COMPLETE, matching real AWS behaviour for nested stacks
+ # whose parents are torn down.
+
+
# --- CloudFormation Custom Resource ---
def _cr_stack_id(stack_name: str) -> str:
@@ -3589,6 +3875,11 @@ _RESOURCE_HANDLERS = {
"AWS::Lambda::Version": {"create": _lambda_version_create},
"AWS::CloudFormation::WaitCondition": {"create": _cfn_wait_condition_create},
"AWS::CloudFormation::WaitConditionHandle": {"create": _cfn_wait_condition_handle_create},
+ "AWS::CloudFormation::Stack": {
+ "create": _cfn_nested_stack_create,
+ "update": _cfn_nested_stack_update,
+ "delete": _cfn_nested_stack_delete,
+ },
# The "create" entry is load-bearing: without it, _provision_resource would
# hit the generic "AWS::CloudFormation::*" no-op branch. Update and delete
# are intentionally absent — they route through the explicit if-branches in
diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.py
index a258ea51..c8e4f58f 100644
--- a/ministack/services/cloudfront.py
+++ b/ministack/services/cloudfront.py
@@ -931,7 +931,7 @@ def _create_invalidation(dist_id, body):
for existing in invs:
if existing["InvalidationBatch"]["CallerReference"] == caller_ref:
existing_paths = existing["InvalidationBatch"]["Paths"]["Items"]
- if existing_paths != path_items:
+ if set(existing_paths) != set(path_items):
return _error(
"InvalidationBatchAlreadyExists",
"An invalidation batch with this CallerReference already exists.",
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 8cdb7f3f..aa00d9ea 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -2896,12 +2896,25 @@ def _saml2_idp_response(body: bytes, query_params):
relay_state = form.get("RelayState", "")
if not saml_response_b64:
- return error_response_json("InvalidParameterException", "SAMLResponse is required.", 400)
+ logger.warning("Cognito SAML callback: missing `SAMLResponse` form field")
+ return error_response_json("InvalidParameterException",
+ "SAML callback missing `SAMLResponse` form field.", 400)
# Look up relay context
relay = _auth_codes.pop(relay_state, None)
if not relay or relay.get("type") != "relay":
- return error_response_json("InvalidParameterException", "Invalid or expired RelayState.", 400)
+ logger.warning(
+ "Cognito SAML callback: no matching relay for RelayState=%s (expired after %ds, "
+ "already consumed, or never issued by /oauth2/authorize). "
+ "Re-start the federated login flow from /oauth2/authorize.",
+ relay_state, _AUTH_CODE_TTL,
+ )
+ return error_response_json(
+ "InvalidParameterException",
+ "SAML callback `RelayState` does not match any pending authorize flow "
+ "(expired, already consumed, or unknown).",
+ 400,
+ )
pool_id = relay["pool_id"]
client_id = relay["client_id"]
@@ -3041,13 +3054,28 @@ def _oauth2_idp_response(method, body, query_params):
pass
if not code:
- return error_response_json("InvalidParameterException", "code is required.", 400)
+ logger.warning("Cognito OIDC callback: missing `code` query param")
+ return error_response_json("InvalidParameterException",
+ "OIDC callback missing `code` query parameter.", 400)
if not state:
- return error_response_json("InvalidParameterException", "state is required.", 400)
+ logger.warning("Cognito OIDC callback: missing `state` query param")
+ return error_response_json("InvalidParameterException",
+ "OIDC callback missing `state` query parameter.", 400)
relay = _auth_codes.pop(state, None)
if not relay or relay.get("type") != "relay":
- return error_response_json("InvalidParameterException", "Invalid or expired state.", 400)
+ logger.warning(
+ "Cognito OIDC callback: no matching relay for state=%s (expired after %ds, "
+ "already consumed, or never issued by /oauth2/authorize). "
+ "Re-start the federated login flow from /oauth2/authorize.",
+ state, _AUTH_CODE_TTL,
+ )
+ return error_response_json(
+ "InvalidParameterException",
+ "OIDC callback `state` does not match any pending authorize flow "
+ "(expired, already consumed, or unknown).",
+ 400,
+ )
pool_id = relay["pool_id"]
client_id = relay["client_id"]
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index 98508838..8014e0af 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -114,14 +114,14 @@ def restore_state(data):
inst["_docker_container_id"] = None
inst["DBInstanceStatus"] = "creating"
_instances._data[key] = inst
- to_respawn.append((inst.get("DBInstanceIdentifier") or key[1], inst))
+ to_respawn.append((key[0], inst.get("DBInstanceIdentifier") or key[1], inst))
else:
# Legacy format: plain dict keyed by instance name
for name, inst in instances_data.items():
inst["_docker_container_id"] = None
inst["DBInstanceStatus"] = "creating"
_instances[name] = inst
- to_respawn.append((name, inst))
+ to_respawn.append((None, name, inst))
# Re-spin backing containers for persisted instances. Mirrors the MWAA
# restore pattern: persistence saves the instance metadata but the Docker
@@ -129,12 +129,16 @@ def restore_state(data):
# to bring it back. Without this, restored instances stay marked
# "available" with no running container, and StartDBInstance is
# metadata-only so it can't recover them either.
- for db_id, inst in to_respawn:
- threading.Thread(
- target=_start_rds_container_for_instance,
- args=(db_id, inst),
- daemon=True,
- ).start()
+ from ministack.core.responses import _request_account_id
+ for account_id, db_id, inst in to_respawn:
+ ctx = contextvars.copy_context()
+
+ def _runner(account_id=account_id, db_id=db_id, inst=inst):
+ if account_id is not None:
+ _request_account_id.set(account_id)
+ _start_rds_container_for_instance(db_id, inst)
+
+ threading.Thread(target=ctx.run, args=(_runner,), daemon=True).start()
def _start_rds_container_for_instance(db_id, instance):
diff --git a/tests/conftest.py b/tests/conftest.py
index 1b2c7ea5..81498e99 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -53,6 +53,7 @@ def make_client(service, additional_config_kwargs=None):
_SERIAL_TESTS = {
"tests/test_athena.py::test_athena_engine_mock_via_config",
+ "tests/test_athena.py::test_athena_mixed_glue_and_s3_uri",
"tests/test_ec2.py::test_ec2_create_default_vpc",
"tests/test_eks.py::test_eks_cfn_cluster",
"tests/test_eks.py::test_eks_create_describe_delete_cluster",
diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.py
index 5751fb52..7066d6d6 100644
--- a/tests/test_apigatewayv2.py
+++ b/tests/test_apigatewayv2.py
@@ -840,12 +840,14 @@ def test_apigw_integration_without_request_parameters_optional_map(apigw):
apigw.delete_api(ApiId=api_id)
-def test_apigw_jwt_authorizer_enforced_in_data_plane(apigw):
+def test_apigw_jwt_authorizer_enforced_in_data_plane(apigw, cognito_idp):
import urllib.error as _urlerr
import urllib.request as _urlreq
from ministack.services import cognito as _cognito
+ pool_id = cognito_idp.create_user_pool(PoolName=f"jwt-enforce-{_uuid_mod.uuid4().hex[:8]}")["UserPool"]["Id"]
+ issuer = f"https://cognito-idp.us-east-1.amazonaws.com/{pool_id}"
api_id = apigw.create_api(Name=f"jwt-enforce-{_uuid_mod.uuid4().hex[:8]}", ProtocolType="HTTP")["ApiId"]
server, _thread, _captured = _start_echo_server()
try:
@@ -860,7 +862,7 @@ def test_apigw_jwt_authorizer_enforced_in_data_plane(apigw):
AuthorizerType="JWT",
Name="jwt-auth",
IdentitySource=["$request.header.Authorization"],
- JwtConfiguration={"Audience": ["ms-client"], "Issuer": "https://cognito-idp.us-east-1.amazonaws.com/test-pool"},
+ JwtConfiguration={"Audience": ["ms-client"], "Issuer": issuer},
)["AuthorizerId"]
apigw.create_route(
ApiId=api_id,
@@ -878,7 +880,7 @@ def test_apigw_jwt_authorizer_enforced_in_data_plane(apigw):
_urlreq.urlopen(req_missing)
assert exc.value.code == 401
- token = _cognito._fake_token("user-1", "test-pool", "ms-client", token_type="access")
+ token = _cognito._fake_token("user-1", pool_id, "ms-client", token_type="access")
req_ok = _urlreq.Request(url, method="GET")
req_ok.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
req_ok.add_header("Authorization", f"Bearer {token}")
@@ -888,11 +890,14 @@ def test_apigw_jwt_authorizer_enforced_in_data_plane(apigw):
server.shutdown()
server.server_close()
apigw.delete_api(ApiId=api_id)
+ cognito_idp.delete_user_pool(UserPoolId=pool_id)
-def test_apigw_request_mapping_claims_to_headers(apigw):
+def test_apigw_request_mapping_claims_to_headers(apigw, cognito_idp):
import urllib.request as _urlreq
+ pool_id = cognito_idp.create_user_pool(PoolName=f"jwt-map-{_uuid_mod.uuid4().hex[:8]}")["UserPool"]["Id"]
+ issuer = f"https://cognito-idp.us-east-1.amazonaws.com/{pool_id}"
api_id = apigw.create_api(Name=f"jwt-map-{_uuid_mod.uuid4().hex[:8]}", ProtocolType="HTTP")["ApiId"]
server, _thread, _captured = _start_echo_server()
try:
@@ -913,7 +918,7 @@ def test_apigw_request_mapping_claims_to_headers(apigw):
AuthorizerType="JWT",
Name="jwt-map-auth",
IdentitySource=["$request.header.Authorization"],
- JwtConfiguration={"Audience": ["ms-client"], "Issuer": "https://cognito-idp.us-east-1.amazonaws.com/test-pool"},
+ JwtConfiguration={"Audience": ["ms-client"], "Issuer": issuer},
)["AuthorizerId"]
apigw.create_route(
ApiId=api_id,
@@ -928,7 +933,7 @@ def test_apigw_request_mapping_claims_to_headers(apigw):
token = _make_signed_token(
{
"sub": "auth0|abc123",
- "iss": "https://cognito-idp.us-east-1.amazonaws.com/test-pool",
+ "iss": issuer,
"aud": "ms-client",
"iat": now,
"nbf": now - 1,
@@ -953,6 +958,7 @@ def test_apigw_request_mapping_claims_to_headers(apigw):
server.shutdown()
server.server_close()
apigw.delete_api(ApiId=api_id)
+ cognito_idp.delete_user_pool(UserPoolId=pool_id)
def test_apigw_http_proxy_does_not_block_parallel_ddb(monkeypatch):
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index d43b39af..d8047b7f 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -3085,3 +3085,86 @@ def test_cfn_apigateway_account_provisions(cfn, apigw_v1):
cfn.delete_stack(StackName=stack_name)
_wait_stack(cfn, stack_name)
+
+
+# ============================================================================
+# Nested Stacks (AWS::CloudFormation::Stack)
+# ============================================================================
+
+def test_cfn_nested_stack_basic(cfn, s3):
+ """Parent stack provisions a nested stack via TemplateURL. The nested
+ stack creates an S3 bucket and exposes its name as an Output, which the
+ parent reads back via Fn::GetAtt: [Nested, Outputs.BucketName]."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ templates_bucket = f"cfn-nested-templates-{suffix}"
+ s3.create_bucket(Bucket=templates_bucket)
+
+ child_template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Parameters": {
+ "BucketSuffix": {"Type": "String"},
+ },
+ "Resources": {
+ "ChildBucket": {
+ "Type": "AWS::S3::Bucket",
+ "Properties": {
+ "BucketName": {"Fn::Sub": "cfn-nested-child-${BucketSuffix}"},
+ },
+ },
+ },
+ "Outputs": {
+ "BucketName": {"Value": {"Ref": "ChildBucket"}},
+ },
+ }
+ s3.put_object(Bucket=templates_bucket, Key="child.json",
+ Body=json.dumps(child_template).encode())
+
+ parent_template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Nested": {
+ "Type": "AWS::CloudFormation::Stack",
+ "Properties": {
+ "TemplateURL": f"http://localhost:4566/{templates_bucket}/child.json",
+ "Parameters": {"BucketSuffix": suffix},
+ },
+ },
+ "ParentParam": {
+ "Type": "AWS::SSM::Parameter",
+ "Properties": {
+ "Name": f"/cfn-nested-parent-{suffix}/child-bucket",
+ "Type": "String",
+ "Value": {"Fn::GetAtt": ["Nested", "Outputs.BucketName"]},
+ },
+ },
+ },
+ "Outputs": {
+ "NestedBucketName": {
+ "Value": {"Fn::GetAtt": ["Nested", "Outputs.BucketName"]},
+ },
+ },
+ }
+
+ parent_name = f"cfn-nested-parent-{suffix}"
+ cfn.create_stack(StackName=parent_name,
+ TemplateBody=json.dumps(parent_template))
+ stack = _wait_stack(cfn, parent_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}
+ expected_bucket = f"cfn-nested-child-{suffix}"
+ assert outputs.get("NestedBucketName") == expected_bucket
+
+ # The nested-created bucket really exists
+ buckets = [b["Name"] for b in s3.list_buckets()["Buckets"]]
+ assert expected_bucket in buckets
+
+ # Delete the parent — child resources are cleaned up too
+ cfn.delete_stack(StackName=parent_name)
+ _wait_stack(cfn, parent_name)
+ buckets_after = [b["Name"] for b in s3.list_buckets()["Buckets"]]
+ assert expected_bucket not in buckets_after, \
+ "Nested stack delete did not propagate to child resources"
+
+ s3.delete_object(Bucket=templates_bucket, Key="child.json")
+ s3.delete_bucket(Bucket=templates_bucket)