Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(tests): flaky tests + mrap S3 + bypass sam cli + autopublish false (#1633)
Nahuel Nucera176612be6641
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a86c2bbe..02630c1d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,7 +11,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **CloudFormation — unrecognized resource types are rejected up front, `Fn::GetAtt` to a missing attribute fails the stack** — a template with a resource type the emulator does not know provisioned every resource ahead of it, failed on that one and rolled the stack back; `CreateStack`, `UpdateStack`, `CreateChangeSet` and `ValidateTemplate` now refuse it synchronously with CloudFormation's own `Template format error: Unrecognized resource types: [...]` and leave no stack (or `REVIEW_IN_PROGRESS` placeholder) behind. Dynamic references (`{{resolve:ssm:...}}`, `{{resolve:secretsmanager:...}}`), which the emulator does not resolve, are refused the same way instead of reaching the service as literal strings. `Fn::GetAtt` to an attribute a resource does not expose answered with the physical id, a silently wrong value; it now fails the operation with `Requested attribute X does not exist in schema for T` and the stack rolls back, matching what a real account does. Outputs are resolved before the success path commits, so a failing output rolls back too and registers no export. Contributed by @iot-rocket.### Added- **CloudFront — the policy, OAC and function types provision from CloudFormation** — `AWS::CloudFront::CachePolicy`, `OriginRequestPolicy`, `ResponseHeadersPolicy`, `OriginAccessControl` and `Function` had complete APIs and no CloudFormation provisioner, so a CDK app declaring any of them rolled the stack back with `Unsupported resource type` while the same objects were creatable over the API. Each type now provisions by converting its CFN properties to the element the service's own config parser accepts, so validation, defaults and the stored record are identical to the API path, and `Ref`/`Fn::GetAtt` return the documented values (policy `Id`, OAC `Id`, function `FunctionARN`). Deletes are wired; an update replaces rather than mutating in place. Contributed by @mm-salesqueze.-- **S3 — Multi-Region Access Points deploy and serve** — `AWS::S3::MultiRegionAccessPoint` rolled the stack back with `Unsupported resource type` and the MRAP hostname resolved nowhere, so a CDK app fronting regional buckets with one could not deploy. The type now provisions (minting the 13-character alias and remembering its member buckets) and `<alias>.mrap.accesspoint.s3-global.amazonaws.com` resolves onto the existing virtual-hosted S3 path, so path-style rewriting, IAM enforcement and the handler apply unchanged. The member carrying the request region is served, else the first. State is account-scoped, cleared by `/_ministack/reset` and persisted. SigV4A, which S3 requires for an MRAP, is not verified — consistent with the documented no-SigV4 stance: such a request has its presign parameters dropped and is served rather than refused for a signature that could never have matched, and because a SigV4A credential scope carries no region it falls back to the first member. The s3control control plane (`CreateMultiRegionAccessPoint` and the async request token, Get/List/Delete, policies) is not included. Contributed by @mm-salesqueze.+- **S3 — Multi-Region Access Points deploy and serve** — `AWS::S3::MultiRegionAccessPoint` rolled the stack back with `Unsupported resource type` and the MRAP hostname resolved nowhere, so a CDK app fronting regional buckets with one could not deploy. The type now provisions (minting the `.mrap`-suffixed alias, the shape S3 uses, and remembering its member buckets) and `<alias>.accesspoint.s3-global.amazonaws.com` resolves onto the existing virtual-hosted S3 path, so path-style rewriting, IAM enforcement and the handler apply unchanged. The member whose bucket region matches the request region is served, else the first. State is account-scoped, cleared by `/_ministack/reset` and persisted. SigV4A, which S3 requires for an MRAP, is not verified — consistent with the documented no-SigV4 stance: such a request has its presign parameters dropped and is served rather than refused for a signature that could never have matched, and because a SigV4A credential scope carries no region it falls back to the first member. The s3control control plane (`CreateMultiRegionAccessPoint` and the async request token, Get/List/Delete, policies) is not included. Contributed by @mm-salesqueze.- **CloudFormation — the Cognito resources update in place** — a stack update that changed an `AWS::Cognito::UserPool`, `UserPoolClient`, `IdentityPool` or `UserPoolGroup` fell through to the type's create handler, and for the three with a generated id that meant a second resource under a new id: `Ref` flipped to the new one, the old one was orphaned together with its data (the users in a pool, the role mapping of an identity pool) and nothing in the stack events said so. The four now update the existing record through the service's own path (`UpdateUserPool`, `UpdateUserPoolClient`, `UpdateIdentityPool`, `AddCustomAttributes` for a grown `Schema`; a group's `Description`, `Precedence` and `RoleArn` directly, since the service has no `UpdateGroup`), keeping the physical id and everything stored behind it, and a property the new template drops reverts to the default `CreateUserPool` / `CreateUserPoolClient` fills in, as the resource reference says Cognito does. The pool and the app client are also created through those two calls now, so the record carries every property the update can change (`DeletionProtection`, `EmailConfiguration`, `AccountRecoverySetting`, token validity, `PreventUserExistenceErrors`, …) instead of the handful the create handler copied, and a replaced client carries its whole template over. The properties the resource references mark *Replacement* replace: a `UserPoolClient` whose `UserPoolId` or `GenerateSecret` changed, and a renamed or moved group, are created before the old one is removed and `Ref` follows the new id, while a move to another pool under an unchanged `GroupName` gets CloudFormation's own refusal for a custom-named resource. `AliasAttributes`, `UsernameAttributes` and `UsernameConfiguration` are marked *No interruption* on the reference, but the first two are fixed at `CreateUserPool` and the reference itself calls the third immutable once set, so a change fails the update with a message naming the property rather than altering the record. A group declared without `Precedence` gets none, the null the reference documents as the default, instead of 0; `Fn::GetAtt` gains `UserPoolId` on the pool, `ClientId` on the client and `Name` on the identity pool. Contributed by @iot-rocket.- **CloudFormation — `EnabledMfas` applies on an `AWS::Cognito::UserPool` update** — the property is *No interruption* on the resource reference and creating a pool with `SOFTWARE_TOKEN_MFA` in it already switched the software-token block on, but an update that added or removed the entry left `GetUserPoolMfaConfig` where it was, so a CDK `mfaSecondFactor` change never reached the emulated pool. The update now goes through `SetUserPoolMfaConfig`: the entry arriving switches the block on, its removal or the property being dropped switches it off, and a pool that never listed it is left without the block. Contributed by @iot-rocket.- **CloudFormation — `AWS::SecretsManager::Secret` updates in place** — a stack update that changed a secret fell through to the create handler, which minted a second secret under a new ARN: `Ref` and `GetAtt Arn` flipped to it, the original was orphaned together with its versions, and nothing in the stack events said so. The secret now updates through `UpdateSecret` under the same ARN: a changed `SecretString` or `GenerateSecretString` publishes a new `AWSCURRENT` version and the previous one stays behind as `AWSPREVIOUS`; `Description` and `KmsKeyId` are sent only when the template declares or drops them, so a value set outside the stack on a property the template never declared is left alone; `ReplicaRegions` is applied on create and update through `ReplicateSecretToRegions`, and deleting the stack purges the replicas with the secret. `Name` requires replacement and follows the convention already in place: the renamed secret is created before the old one is deleted. Known limits: `Ref` still returns the secret name where AWS returns the ARN (set by the create handler, unchanged here; `GetAtt Arn` carries the ARN, which the reference documents as `Id`), `Type` is not stored by the Secrets Manager service and is ignored, and a region dropped from `ReplicaRegions` keeps its replica because the service has no `RemoveRegionsFromReplication`. Contributed by @iot-rocket.diff --git a/ministack/app.py b/ministack/app.pyindex 69ed9db5..c65213d6 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -1663,7 +1663,7 @@ async def _handle_alb_request(host: str, path: str, method: str, headers: dict,_MRAP_HOST_RE = re.compile(- r"^([a-z0-9]+)\.mrap\.accesspoint\.s3-global\.amazonaws\.com$", re.IGNORECASE+ r"^([a-z0-9]+\.mrap)\.accesspoint\.s3-global\.amazonaws\.com$", re.IGNORECASE)diff --git a/ministack/services/cloudformation/engine.py b/ministack/services/cloudformation/engine.pyindex 2f2b2d92..97e4d43e 100644--- a/ministack/services/cloudformation/engine.py+++ b/ministack/services/cloudformation/engine.py@@ -143,24 +143,33 @@ def validate_template_support(template: dict, conditions: dict) -> None:Raises ``ValueError`` with the message the caller wraps as a``ValidationError``.++ A template that still declares a ``Transform`` is exempt from the type+ check: a macro can rewrite any resource, so real CloudFormation cannot+ (and does not) pre-validate types through one — ``sam validate`` sends+ SAM templates with ``AWS::Serverless::*`` resources to ValidateTemplate+ and they pass. CreateStack, UpdateStack and CreateChangeSet apply the SAM+ transform before calling this, so their expanded templates are validated+ as usual."""from .provisioners import _RESOURCE_HANDLERSunrecognized: set[str] = set()- for res in (template.get("Resources") or {}).values():- if not isinstance(res, dict):- continue- cond = res.get("Condition")- if cond and not conditions.get(cond, True):- continue- rtype = res.get("Type", "AWS::CloudFormation::CustomResource")- if (- rtype in _RESOURCE_HANDLERS- or rtype.startswith("Custom::")- or rtype.startswith("AWS::CloudFormation::")- ):- continue- unrecognized.add(rtype)+ if not template.get("Transform"):+ for res in (template.get("Resources") or {}).values():+ if not isinstance(res, dict):+ continue+ cond = res.get("Condition")+ if cond and not conditions.get(cond, True):+ continue+ rtype = res.get("Type", "AWS::CloudFormation::CustomResource")+ if (+ rtype in _RESOURCE_HANDLERS+ or rtype.startswith("Custom::")+ or rtype.startswith("AWS::CloudFormation::")+ ):+ continue+ unrecognized.add(rtype)if unrecognized:raise ValueError("Template format error: Unrecognized resource types: ["diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex b34ae943..e9fb0158 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -284,10 +284,10 @@ def _cf_function_create(logical_id, props, stack_name):now = now_iso()dev_etag = new_uuid()- # AutoPublish defaults to true in the CFN spec, and CDK relies on it: a- # distribution associates the LIVE stage, so an unpublished function would- # never run.- auto_publish = props.get("AutoPublish", True)+ # "By default, when you create a function, it's in the DEVELOPMENT stage"+ # (AWS::CloudFront::Function reference) — publishing to LIVE happens only+ # when the template sets AutoPublish to true, which CDK emits explicitly.+ auto_publish = props.get("AutoPublish", False)if isinstance(auto_publish, str):auto_publish = auto_publish.lower() == "true"@@ -304,9 +304,10 @@ def _cf_function_create(logical_id, props, stack_name):"dev_etag": dev_etag,"live_etag": new_uuid() if auto_publish else None,}+ # The reference lists only FunctionARN and FunctionMetadata.FunctionARN as+ # GetAtt attributes — no Stage.arn = _cf._func_arn(name)- return name, {"FunctionARN": arn, "FunctionMetadata.FunctionARN": arn,- "Stage": "LIVE" if auto_publish else "DEVELOPMENT"}+ return name, {"FunctionARN": arn, "FunctionMetadata.FunctionARN": arn}def _cf_function_delete(physical_id, props):diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex ed2b64dc..45c8e421 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -83,18 +83,21 @@ _mraps = AccountScopedDict() # Alias -> {Name, Alias, Regions: [bucket, ...], Cdef new_mrap_alias() -> str:- """A 13-character alias, the shape S3 mints for a Multi-Region Access Point."""- return new_uuid().replace("-", "")[:13].lower()+ """The alias S3 mints for a Multi-Region Access Point: a 13-character+ string suffixed with ``.mrap`` (e.g. ``mfzwi23gnjvgw.mrap``). The suffix is+ part of the alias itself — GetAtt/GetMultiRegionAccessPoint return it, and+ the hostname is ``<alias>.accesspoint.s3-global.amazonaws.com``."""+ return new_uuid().replace("-", "")[:13].lower() + ".mrap"def resolve_mrap_bucket(alias: str):"""The bucket an MRAP alias serves, or None.A real MRAP routes to whichever member bucket is nearest the caller. Nearest- has no meaning in a single-process emulator, so the member whose name carries- the request region wins and the first member is the fallback — deterministic,- and it makes a single-region MRAP (the common case in a local stack) resolve- to the only bucket it has.+ has no meaning in a single-process emulator, so the member whose *stored*+ region (recorded at CreateBucket) matches the request region wins and the+ first member is the fallback — deterministic, and it makes a single-region+ MRAP (the common case in a local stack) resolve to the only bucket it has."""record = _mraps.get(alias)if not record:@@ -103,9 +106,11 @@ def resolve_mrap_bucket(alias: str):if not buckets:return Noneregion = get_region()- for bucket in buckets:- if region and region in bucket:- return bucket+ if region:+ for bucket in buckets:+ meta = _buckets.get(bucket)+ if meta is not None and meta.get("region") == region:+ return bucketreturn buckets[0]_bucket_acl = AccountScopedDict()_bucket_websites = AccountScopedDict()diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 124189d7..b1a99978 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -1087,31 +1087,6 @@ def test_cfn_iot_ca_certificate_pem_change_refused(cfn, iot_client):_wait_stack(cfn, "cfn-iot-ca-pem")-def test_cfn_lambda_layer_version_permission(cfn, lam):- """AWS::Lambda::LayerVersionPermission attaches a statement to the real- layer version's policy, readable via GetLayerVersionPolicy. (#1345, item 5)"""- buf = io.BytesIO()- with zipfile.ZipFile(buf, "w") as zf:- zf.writestr("lib.txt", "x")- layer = lam.publish_layer_version(- LayerName="cfn-perm-layer", Content={"ZipFile": buf.getvalue()})- arn = layer["LayerVersionArn"]-- template = {"Resources": {"Perm": {- "Type": "AWS::Lambda::LayerVersionPermission", "Properties": {- "LayerVersionArn": arn, "Action": "lambda:GetLayerVersion",- "Principal": "123456789012", "StatementId": "cfn-sid"}}}}- cfn.create_stack(StackName="cfn-layer-perm", TemplateBody=json.dumps(template))- assert _wait_stack(cfn, "cfn-layer-perm")["StackStatus"] == "CREATE_COMPLETE"-- pol = json.loads(lam.get_layer_version_policy(- LayerName="cfn-perm-layer", VersionNumber=1)["Policy"])- assert any(s["Sid"] == "cfn-sid" for s in pol["Statement"])-- cfn.delete_stack(StackName="cfn-layer-perm")- _wait_stack(cfn, "cfn-layer-perm")--def test_cfn_deleted_stack_name_is_reusable(cfn):"""A DELETE_COMPLETE stack is addressable only by stack ID; its name is freeto re-create, and an UpdateStack against the deleted name is "does not@@ -6402,8 +6377,9 @@ def test_cfn_cloudfront_policy_oac_and_function_provision(cfn, cloudfront):assert oac_cfg["SigningBehavior"] == "always"assert oac_cfg["OriginAccessControlOriginType"] == "s3"- # AutoPublish defaults to true and CDK relies on it: a distribution- # associates the LIVE stage, so an unpublished function would never run.+ # The template sets AutoPublish: true explicitly (as CDK emits it), so the+ # function is published to LIVE; a created function defaults to the+ # DEVELOPMENT stage per the resource reference.summary = cloudfront.describe_function(Name=f"cfn-fn-{suffix}", Stage="LIVE")["FunctionSummary"]assert summary["FunctionMetadata"]["Stage"] == "LIVE"@@ -6415,6 +6391,30 @@ def test_cfn_cloudfront_policy_oac_and_function_provision(cfn, cloudfront):cloudfront.get_cache_policy(Id=out["CachePolicyRef"])+def test_cfn_cloudfront_function_without_autopublish_stays_in_development(cfn, cloudfront):+ """"By default, when you create a function, it's in the DEVELOPMENT stage"+ (AWS::CloudFront::Function reference): a template that omits AutoPublish+ gets an unpublished function — DESCRIBE at LIVE fails, DEVELOPMENT works."""+ name = "cfn-fn-devstage"+ template = json.dumps({"Resources": {"Fn": {+ "Type": "AWS::CloudFront::Function",+ "Properties": {"Name": name, "FunctionCode": _FUNCTION_CODE,+ "FunctionConfig": {"Comment": "unpublished",+ "Runtime": "cloudfront-js-2.0"}},+ }}})+ cfn.create_stack(StackName="cfn-cf-fn-dev", TemplateBody=template)+ try:+ stack = _wait_stack(cfn, "cfn-cf-fn-dev")+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ dev = cloudfront.describe_function(Name=name, Stage="DEVELOPMENT")["FunctionSummary"]+ assert dev["FunctionMetadata"]["Stage"] == "DEVELOPMENT"+ with pytest.raises(ClientError):+ cloudfront.describe_function(Name=name, Stage="LIVE")+ finally:+ cfn.delete_stack(StackName="cfn-cf-fn-dev")+ _wait_stack(cfn, "cfn-cf-fn-dev")++def test_cfn_cloudfront_distribution_consumes_provisioned_policies(cfn, cloudfront):"""The payoff: a distribution in the same stack references the policies andthe function by Ref/GetAtt. This is what a CDK app emits, and it only works@@ -6484,7 +6484,8 @@ def _mrap_get(alias, key, region=None):import urllib.requestendpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")req = urllib.request.Request(f"{endpoint}/{key}")- req.add_header("Host", f"{alias}.mrap.accesspoint.s3-global.amazonaws.com")+ # The alias itself ends in ".mrap"; the hostname appends only the suffix.+ req.add_header("Host", f"{alias}.accesspoint.s3-global.amazonaws.com")if region:req.add_header("Authorization","AWS4-HMAC-SHA256 "@@ -6506,7 +6507,10 @@ def test_cfn_s3_multi_region_access_point(cfn, s3):assert stack["StackStatus"] == "CREATE_COMPLETE"alias = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}["Alias"]- assert len(alias) == 13 and alias.islower()+ # The alias S3 mints ends in ".mrap" (e.g. mfzwi23gnjvgw.mrap); templates+ # build "<alias>.accesspoint.s3-global.amazonaws.com" from it.+ base, _, suffix = alias.rpartition(".")+ assert suffix == "mrap" and len(base) == 13 and base.islower()cfn.delete_stack(StackName="cfn-s3-mrap")_wait_stack(cfn, "cfn-s3-mrap")@@ -11238,6 +11242,20 @@ def test_cfn_unrecognized_type_behind_false_condition_is_fine(cfn):_wait_stack(cfn, name)+def test_cfn_validate_template_accepts_a_sam_template(cfn):+ """A template that declares a Transform is exempt from the unrecognized+ type check: a macro can rewrite any resource, so real CloudFormation does+ not pre-validate types through one — `sam validate` sends templates with+ AWS::Serverless::* resources to ValidateTemplate and they pass."""+ tpl = json.dumps({+ "Transform": "AWS::Serverless-2016-10-31",+ "Resources": {"Fn": {"Type": "AWS::Serverless::Function", "Properties": {+ "Handler": "index.handler", "Runtime": "python3.12",+ "InlineCode": "def handler(e, c): return {}"}}},+ })+ cfn.validate_template(TemplateBody=tpl)++def test_cfn_getatt_unknown_attribute_fails_the_stack(cfn, sqs):"""Fn::GetAtt to an attribute the resource does not expose is no longeranswered with the physical id: the stack fails and rolls back with thediff --git a/tests/test_eventbridge.py b/tests/test_eventbridge.pyindex 5540544d..d011596d 100644--- a/tests/test_eventbridge.py+++ b/tests/test_eventbridge.py@@ -2082,36 +2082,47 @@ def test_eventbridge_replay_dispatch_uses_replay_region(eb, sqs):def test_eventbridge_archive_event_count_unchanged_after_replay(eb):- """Replay reads archived events non-destructively; EventCount stays the same."""- arch_name = f"postcnt-arch-{_uuid_mod.uuid4().hex[:8]}"- bus_arn = "arn:aws:events:us-east-1:000000000000:event-bus/default"+ """Replay reads archived events non-destructively; EventCount stays the same.++ The archive lives on a dedicated bus: an unfiltered archive on the shared+ default bus captures every event other xdist workers put there during the+ replay window, so the count assertion would blame the replay for growth it+ did not cause (that exact flake hit CI)."""+ uid = _uuid_mod.uuid4().hex[:8]+ bus_name = f"postcnt-bus-{uid}"+ arch_name = f"postcnt-arch-{uid}"+ bus_arn = eb.create_event_bus(Name=bus_name)["EventBusArn"]eb.create_archive(ArchiveName=arch_name, EventSourceArn=bus_arn)- eb.put_events(- Entries=[- {- "Source": "postcnt.src",- "DetailType": "CountCheck",- "Detail": json.dumps({}),- "EventBusName": "default",- }- ]- )- count_before = eb.describe_archive(ArchiveName=arch_name)["EventCount"]- archive_arn = eb.describe_archive(ArchiveName=arch_name)["ArchiveArn"]- rep_name = f"rep-postcnt-{_uuid_mod.uuid4().hex[:8]}"- eb.start_replay(- ReplayName=rep_name,- EventSourceArn=archive_arn,- EventStartTime=0,- EventEndTime=time.time() + 3600,- Destination={"Arn": bus_arn},- )- time.sleep(0.3)- count_after = eb.describe_archive(ArchiveName=arch_name)["EventCount"]- assert count_after == count_before, (- "Replay must not consume or modify archived events"- )- eb.delete_archive(ArchiveName=arch_name)+ try:+ eb.put_events(+ Entries=[+ {+ "Source": "postcnt.src",+ "DetailType": "CountCheck",+ "Detail": json.dumps({}),+ "EventBusName": bus_name,+ }+ ]+ )+ count_before = eb.describe_archive(ArchiveName=arch_name)["EventCount"]+ assert count_before == 1+ archive_arn = eb.describe_archive(ArchiveName=arch_name)["ArchiveArn"]+ rep_name = f"rep-postcnt-{uid}"+ eb.start_replay(+ ReplayName=rep_name,+ EventSourceArn=archive_arn,+ EventStartTime=0,+ EventEndTime=time.time() + 3600,+ Destination={"Arn": bus_arn},+ )+ time.sleep(0.3)+ count_after = eb.describe_archive(ArchiveName=arch_name)["EventCount"]+ assert count_after == count_before, (+ "Replay must not consume or modify archived events"+ )+ finally:+ eb.delete_archive(ArchiveName=arch_name)+ eb.delete_event_bus(Name=bus_name)def test_eventbridge_duplicate_replay_name_fails(eb):diff --git a/tests/test_persistence.py b/tests/test_persistence.pyindex 7d6dd024..30aa67f0 100644--- a/tests/test_persistence.py+++ b/tests/test_persistence.py@@ -650,15 +650,15 @@ def test_s3_mrap_round_trip():client configuration, so member buckets coming back without the aliasfronting them fails where a missing bucket would not."""def populate(mod):- mod._mraps["ea0672af90364"] = {+ mod._mraps["ea0672af90364.mrap"] = {"Name": "app-release",- "Alias": "ea0672af90364",+ "Alias": "ea0672af90364.mrap","Regions": ["app-us-east-1-release", "app-eu-west-1-release"],"CreatedAt": "2026-01-01T00:00:00Z",}def observe(mod):- mrap = mod._mraps["ea0672af90364"]+ mrap = mod._mraps["ea0672af90364.mrap"]assert mrap["Name"] == "app-release"assert mrap["Regions"] == ["app-us-east-1-release", "app-eu-west-1-release"]diff --git a/tests/test_rds.py b/tests/test_rds.pyindex 291546a1..6e158d1d 100644--- a/tests/test_rds.py+++ b/tests/test_rds.py@@ -5346,6 +5346,21 @@ def test_rds_restore_state_respawns_one_container_per_cluster(},},}++ # Track the background provisioning threads restore_state starts so the+ # assertions below can join them: the runner marks members available+ # before it reaps the superseded legacy volumes, so a status-only wait+ # can observe "settled" while the reap has not run yet (#1629).+ started_threads = []+ _RealThread = threading.Thread++ class TrackedThread(_RealThread):+ def start(self):+ started_threads.append(self)+ super().start()++ monkeypatch.setattr(m.threading, "Thread", TrackedThread)+m.restore_state({"instances": instances,"clusters": clusters,@@ -5419,6 +5434,17 @@ def test_rds_restore_state_respawns_one_container_per_cluster(f"would report a timeout as a behaviour change")+ # "Settled" means the members' statuses landed; the legacy-volume reap+ # runs after that write, in the same runner thread. Join the threads so+ # the assertions observe the runner's full effect, not a snapshot taken+ # inside its final window (#1629).+ for thread in started_threads:+ thread.join(timeout=10)+ assert not any(t.is_alive() for t in started_threads), (+ f"{scenario}: restore_state background threads still running "+ f"after the settle wait"+ )+if not writer_removal_succeeds or not reader_removal_succeeds or (scenario == "ownership-mismatch"):diff --git a/tests/test_s3.py b/tests/test_s3.pyindex 15ccf25a..91ebcf78 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -6189,7 +6189,8 @@ def _mrap_get(alias, key, region=None):import urllib.requestendpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")req = urllib.request.Request(f"{endpoint}/{key}")- req.add_header("Host", f"{alias}.mrap.accesspoint.s3-global.amazonaws.com")+ # The alias itself ends in ".mrap"; the hostname appends only the suffix.+ req.add_header("Host", f"{alias}.accesspoint.s3-global.amazonaws.com")if region:req.add_header("Authorization","AWS4-HMAC-SHA256 "@@ -6201,29 +6202,47 @@ def _mrap_get(alias, key, region=None):def test_s3_mrap_alias_serves_the_region_member(cfn, s3):"""The MRAP hostname resolved nowhere — it is not a bucket name and matched- no virtual-host rule. It now lands on the existing vhost path, and the member- carrying the request region is served rather than whichever is listed first."""- buckets = ["mrap-serve-us-east-1-app", "mrap-serve-eu-west-1-app"]- cfn.create_stack(StackName="cfn-s3-mrap-serve",- TemplateBody=_mrap_template("serve-mrap-app", buckets))- stack = _wait_stack(cfn, "cfn-s3-mrap-serve")- assert stack["StackStatus"] == "CREATE_COMPLETE"- alias = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}["Alias"]-- s3.put_object(Bucket=buckets[0], Key="who.txt", Body=b"US BUCKET")- s3.put_object(Bucket=buckets[1], Key="who.txt", Body=b"EU BUCKET")-- # us-east-1 is listed first, so serving the eu-west-1 member proves the- # member is chosen by region rather than taken off the front of the list.- assert _mrap_get(alias, "who.txt", region="eu-west-1") == (200, "EU BUCKET")- assert _mrap_get(alias, "who.txt", region="us-east-1") == (200, "US BUCKET")-- # A request that carries no region at all (SigV4A's credential scope has- # none) falls back to the first member rather than failing.- assert _mrap_get(alias, "who.txt") == (200, "US BUCKET")-- cfn.delete_stack(StackName="cfn-s3-mrap-serve")- _wait_stack(cfn, "cfn-s3-mrap-serve")+ no virtual-host rule. It now lands on the existing vhost path, and the+ member whose *stored* bucket region matches the request region is served+ rather than whichever is listed first. The buckets are created through the+ S3 API (one per region, like a real MRAP's members) and only the access+ point comes from the stack."""+ us_bucket, eu_bucket = "mrap-serve-us-app", "mrap-serve-eu-app"+ s3.create_bucket(Bucket=us_bucket) # the client's own region, us-east-1+ s3.create_bucket(Bucket=eu_bucket, CreateBucketConfiguration={+ "LocationConstraint": "eu-west-1"})+ template = json.dumps({+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {"Mrap": {"Type": "AWS::S3::MultiRegionAccessPoint",+ "Properties": {"Name": "serve-mrap-app",+ "Regions": [{"Bucket": us_bucket},+ {"Bucket": eu_bucket}]}}},+ "Outputs": {"Alias": {"Value": {"Fn::GetAtt": ["Mrap", "Alias"]}}},+ })+ cfn.create_stack(StackName="cfn-s3-mrap-serve", TemplateBody=template)+ try:+ stack = _wait_stack(cfn, "cfn-s3-mrap-serve")+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ alias = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}["Alias"]++ s3.put_object(Bucket=us_bucket, Key="who.txt", Body=b"US BUCKET")+ s3.put_object(Bucket=eu_bucket, Key="who.txt", Body=b"EU BUCKET")++ # us-east-1 is listed first, so serving the eu-west-1 member proves the+ # member is chosen by its stored region rather than taken off the front.+ assert _mrap_get(alias, "who.txt", region="eu-west-1") == (200, "EU BUCKET")+ assert _mrap_get(alias, "who.txt", region="us-east-1") == (200, "US BUCKET")++ # A request whose credential scope names a region with no member falls+ # back to the first member rather than failing (SigV4A carries no+ # region at all and lands the same way).+ assert _mrap_get(alias, "who.txt", region="ap-south-1") == (200, "US BUCKET")+ finally:+ cfn.delete_stack(StackName="cfn-s3-mrap-serve")+ _wait_stack(cfn, "cfn-s3-mrap-serve")+ for bucket in (us_bucket, eu_bucket):+ s3.delete_object(Bucket=bucket, Key="who.txt")+ s3.delete_bucket(Bucket=bucket)def _reset():