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(s3): enforce bucket home region, cross-region replication and MRAP routing (#2204)
Fábio André Ramos Rodriguesdc708c1b962b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6c5e0683..8e08ed9e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,7 +7,21 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added+- **S3 Control — Multi-Region Access Points** — `CreateMultiRegionAccessPoint`, `DeleteMultiRegionAccessPoint`, `PutMultiRegionAccessPointPolicy`, `DescribeMultiRegionAccessPointOperation`, `GetMultiRegionAccessPoint`, `GetMultiRegionAccessPointPolicy`, `ListMultiRegionAccessPoints`, `GetMultiRegionAccessPointRoutes` and `SubmitMultiRegionAccessPointRoutes`. The async operations apply at once and `Describe` reports `SUCCEEDED`, or `FAILED` with AWS's `ErrorDetails` for a missing bucket, two buckets in one region or a name already in use. Management is served from `us-west-2` and route operations from `us-east-1`, `us-west-2`, `eu-west-1`, `ap-northeast-1` and `ap-southeast-2`, as on AWS; other regions get `301 PermanentRedirect`. `DeleteBucket` on a member returns `BucketHasAccessPointsAttached`. Under `AUTH=true` each operation needs its `s3:` IAM action. Access points from `AWS::S3::MultiRegionAccessPoint` appear in the API.+- **S3 — Multi-Region Access Point failover** — a request through the MRAP host goes to the member with a traffic dial of 100 that is homed in `MINISTACK_REGION`, else the first active member. Setting a dial to 0 moves traffic to the other member, and an update that leaves every dial at 0 is refused.+- **CloudFormation — `DescribeEvents`** — returns the validation errors of a create that fails pre-deployment validation, which the stack's `CREATE_FAILED` event tells the caller to look up.+- **CloudFormation — `CFN_S3_ADOPT_EXISTING_BUCKET`** — `AWS::S3::Bucket` adopts an own bucket that already exists by default, so S3 data that outlives the stack store stays usable. `CFN_S3_ADOPT_EXISTING_BUCKET=0` fails the create the way AWS does, and auto-named buckets get a new name for each stack instance.+### Fixed+- **S3 — bucket home region is enforced** — a request signed for a region other than the bucket's now returns `301 PermanentRedirect` with `x-amz-bucket-region`, which SDKs follow; at the bucket's own regional endpoint it returns `400 AuthorizationHeaderMalformed` or, presigned, `AuthorizationQueryParametersError`, with `<Region>`. HEAD gets the bodiless forms. `GetBucketLocation`, `ListBuckets`, `CreateBucket`, unsigned, SigV2 and SigV4a requests, MRAP requests and internal callers are exempt, and `CopyObject` from a source in another region still works.+- **S3 — `CreateBucket` location constraint (breaking)** — a request signed for a region other than `us-east-1` must name that region as `LocationConstraint`, or gets `IllegalLocationConstraintException`; `LocationConstraint=us-east-1` returns `InvalidLocationConstraint`. Clients that created buckets in another region without a constraint now need one. `BucketAlreadyOwnedByYou` and `BucketAlreadyExists` carry AWS's message and `<BucketName>`.+- **S3 — `ListBuckets` `bucket-region` filter** — `BucketRegion` lists only that region's buckets, with pagination inside the filter; a filter for another region than the endpoint's returns `InvalidArgument`.+- **S3 — replication** — delete markers replicate for V2 rules with `DeleteMarkerReplication` enabled and no tag filter, from `DeleteObject` and `DeleteObjects`; version-id deletes don't. Rules with `Filter.Tag` or `Filter.And.Tags` replicate only objects carrying those tags.+- **SigV4a requests no longer land in region `s3`** — the region was read from a credential scope that SigV4a doesn't have; a single-region `X-Amz-Region-Set` is used, else the default region.+- **Lambda — S3 code from another region** — `CreateFunction`, `UpdateFunctionCode`, `PublishLayerVersion` and CloudFormation return AWS's `InvalidParameterValueException` when the code bucket is homed elsewhere.+- **Resource Groups Tagging — S3 buckets by region** — `GetResources`, `GetTagKeys` and `GetTagValues` list only buckets homed in the region they are called in.+- **CloudFormation — `AWS::S3::Bucket` and existing names** — a `BucketName` another account owns used to become a second bucket of that name; it now fails pre-deployment validation with `NAME_CONFLICT_VALIDATION`, as on AWS. With rollback disabled, a failed validation emits AWS's second `CREATE_FAILED` event.- **CloudFront — function status follows publish and association** — `DescribeFunction` and `ListFunctions` reported the `DEVELOPMENT` stage as `UNPUBLISHED` even after `PublishFunction`, so Terraform's `aws_cloudfront_function.status`, which reads that stage, never left `UNPUBLISHED`; once the current development version is published it now reports `UNASSOCIATED`, or `ASSOCIATED` while a distribution's cache behavior references the function, and an `UpdateFunction` makes it `UNPUBLISHED` again until the next publish. Contributed by @fabio-andre-rodrigues.- **Step Functions — JSONata Fail and Wait fields are evaluated** — a JSONata Fail state raised its `Error` and `Cause` expressions as literal text, a JSONata Wait failed on a `Seconds` expression, ignored a `Timestamp` expression and dropped its `Output` and `Assign`, and JSONPath `ErrorPath`/`CausePath` were ignored; they are now evaluated, with AWS's `States.QueryEvaluationError` or `States.Runtime` for a result of the wrong type, a `Seconds` that is not a non-negative integer and an unparsable `Timestamp`.- **S3 — presigned URLs keep AWS's time limits under `AUTH=true`** — an `X-Amz-Expires` over 604800 seconds or not a number, or a malformed `X-Amz-Date`, answers 400 `AuthorizationQueryParametersError`, and a URL dated more than 15 minutes ahead answers 403 `AccessDenied` `Request is not yet valid`, where they were served. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex b07d87a7..1e67e786 100644--- a/README.md+++ b/README.md@@ -402,7 +402,7 @@ subnet = ec2.create_subnet(| Service | Operations | Notes ||---------|-----------|-------|-| **S3** | CreateBucket, DeleteBucket, ListBuckets, HeadBucket, PutObject, GetObject, DeleteObject, HeadObject, CopyObject, ListObjects v1/v2, DeleteObjects, GetBucketVersioning, PutBucketVersioning, GetBucketEncryption, PutBucketEncryption, DeleteBucketEncryption, GetBucketLifecycleConfiguration, PutBucketLifecycleConfiguration, DeleteBucketLifecycle, GetBucketCors, PutBucketCors, DeleteBucketCors, GetBucketAcl, PutBucketAcl, GetBucketTagging, PutBucketTagging, DeleteBucketTagging, GetBucketPolicy, PutBucketPolicy, DeleteBucketPolicy, GetBucketNotificationConfiguration, PutBucketNotificationConfiguration, GetBucketLogging, PutBucketLogging, ListObjectVersions, CreateMultipartUpload, UploadPart, CompleteMultipartUpload, AbortMultipartUpload, PutObjectLockConfiguration, GetObjectLockConfiguration, PutObjectRetention, GetObjectRetention, PutObjectLegalHold, GetObjectLegalHold, PutBucketReplication, GetBucketReplication, DeleteBucketReplication, GetObjectTagging, PutObjectTagging, DeleteObjectTagging, PutObjectAnnotation, GetObjectAnnotation, ListObjectAnnotations, DeleteObjectAnnotation | Optional disk persistence via `S3_PERSIST=1`; Object Lock with retention & legal hold enforcement on delete, and on annotation writes under `AUTH=true` (governance mode yields to `x-amz-bypass-governance-retention`); object annotations are per version (up to 1,000, 1 byte–1 MiB each), carried by `CopyObject` and removed with their version; object tags are versioned (`?tagging&versionId=…` reads, writes, and deletes the per-version tag set); Multi-Region Access Points provision from CloudFormation (`AWS::S3::MultiRegionAccessPoint`) and `<alias>.accesspoint.s3-global.amazonaws.com` serves the member buckets through the regular S3 path |+| **S3** | CreateBucket, DeleteBucket, ListBuckets, HeadBucket, PutObject, GetObject, DeleteObject, HeadObject, CopyObject, ListObjects v1/v2, DeleteObjects, GetBucketVersioning, PutBucketVersioning, GetBucketEncryption, PutBucketEncryption, DeleteBucketEncryption, GetBucketLifecycleConfiguration, PutBucketLifecycleConfiguration, DeleteBucketLifecycle, GetBucketCors, PutBucketCors, DeleteBucketCors, GetBucketAcl, PutBucketAcl, GetBucketTagging, PutBucketTagging, DeleteBucketTagging, GetBucketPolicy, PutBucketPolicy, DeleteBucketPolicy, GetBucketNotificationConfiguration, PutBucketNotificationConfiguration, GetBucketLogging, PutBucketLogging, ListObjectVersions, CreateMultipartUpload, UploadPart, CompleteMultipartUpload, AbortMultipartUpload, PutObjectLockConfiguration, GetObjectLockConfiguration, PutObjectRetention, GetObjectRetention, PutObjectLegalHold, GetObjectLegalHold, PutBucketReplication, GetBucketReplication, DeleteBucketReplication, GetObjectTagging, PutObjectTagging, DeleteObjectTagging, PutObjectAnnotation, GetObjectAnnotation, ListObjectAnnotations, DeleteObjectAnnotation | Optional disk persistence via `S3_PERSIST=1`; Object Lock with retention & legal hold enforcement on delete, and on annotation writes under `AUTH=true` (governance mode yields to `x-amz-bypass-governance-retention`); object annotations are per version (up to 1,000, 1 byte–1 MiB each), carried by `CopyObject` and removed with their version; object tags are versioned (`?tagging&versionId=…` reads, writes, and deletes the per-version tag set); requests signed for another region than the bucket's home get `301 PermanentRedirect` with `x-amz-bucket-region`, and `CreateBucket` applies the location-constraint rules; Multi-Region Access Points are managed through S3 Control (create, delete, get, list, policy, routes) or CloudFormation (`AWS::S3::MultiRegionAccessPoint`), and `<alias>.accesspoint.s3-global.amazonaws.com` serves the active member homed in `MINISTACK_REGION` (traffic dials fail over) through the regular S3 path || **SQS** | CreateQueue, DeleteQueue, ListQueues, GetQueueUrl, GetQueueAttributes, SetQueueAttributes, PurgeQueue, SendMessage, ReceiveMessage, DeleteMessage, ChangeMessageVisibility, ChangeMessageVisibilityBatch, SendMessageBatch, DeleteMessageBatch, TagQueue, UntagQueue, ListQueueTags | Both Query API and JSON protocol; FIFO queues with deduplication; DLQ support, with moved messages carrying `DeadLetterQueueSourceArn`; messages expire after `MessageRetentionPeriod`; the batch actions apply AWS's request-level validation (empty batch, more than ten entries, repeated or malformed entry ids) before any entry is processed || **SNS** | CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes, AddPermission, RemovePermission, Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, GetSubscriptionAttributes, SetSubscriptionAttributes, ConfirmSubscription, Publish, PublishBatch, TagResource, UntagResource, ListTagsForResource, CreatePlatformApplication, ListPlatformApplications, GetPlatformApplicationAttributes, SetPlatformApplicationAttributes, CreatePlatformEndpoint, GetEndpointAttributes, SetEndpointAttributes, DeleteEndpoint, DeletePlatformApplication | SNS→SQS fanout delivery; SNS→Lambda fanout (asynchronous delivery); subscription filter policies on message attributes or, with `FilterPolicyScope` `MessageBody`, the message body (`prefix`, `suffix`, `equals-ignore-case`, `wildcard`, `anything-but`, `numeric`, `cidr`, `exists`); FIFO topics with 5-minute deduplication, sequence numbers, content-based deduplication, and subscription validation; mobile-push endpoint lifecycle with device-token dedup and `Publish` to platform-endpoint `TargetArn` || **DynamoDB** | CreateTable, UpdateTable, DeleteTable, DescribeTable, ListTables, PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem, TransactWriteItems, TransactGetItems, DescribeTimeToLive, UpdateTimeToLive, DescribeContinuousBackups, UpdateContinuousBackups, DescribeEndpoints, TagResource, UntagResource, ListTagsOfResource, EnableKinesisStreamingDestination, DisableKinesisStreamingDestination, DescribeKinesisStreamingDestination, UpdateKinesisStreamingDestination | TTL enforced via thread-safe background reaper (60s cadence); DynamoDB Streams — `StreamSpecification` emits INSERT/MODIFY/REMOVE records on every write that changes an item, respects `StreamViewType`; `Query` and `Scan` pages stop at 1 MB of data read; GSIs accept multi-attribute keys (up to four `HASH` and four `RANGE` attributes); Kinesis streaming destinations (`aws_dynamodb_kinesis_streaming_destination`) fan item mutations out into any Kinesis stream by ARN while the destination is ACTIVE; global tables (version 2019.11.21) through `UpdateTable` `ReplicaUpdates`: a replica is a copy of the table in the other region, and writes replicate between them |diff --git a/ministack/app.py b/ministack/app.pyindex c495dcc3..fbc595ef 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -1555,11 +1555,45 @@ async def _handle_post_body_shortcuts(# ----------------------------------------------------------------------------async def _handle_s3_control_request(path: str, method: str, body: bytes, query_params: dict, request_id: str):+_S3_CONTROL_MRAP_PREFIXES = ("/v20180820/mrap/", "/v20180820/async-requests/mrap/")+++def _s3control_mrap_arn(s3, path: str) -> str:+ """IAM resource for an MRAP request: ``arn:aws:s3::<account>:accesspoint/<alias>``+ for an existing MRAP named in the path, else the account's wildcard."""+ from ministack.core.responses import get_account_id++ account = get_account_id()+ ref = unquote(path).rstrip("/").removeprefix("/v20180820/mrap/instances").strip("/")+ ref = ref.removesuffix("/routes").removesuffix("/policy")+ record = s3.find_mrap(ref) if ref and not path.startswith("/v20180820/async-requests/") else None+ return f"arn:aws:s3::{account}:accesspoint/{record['Alias'] if record else '*'}"+++async def _handle_s3_control_request(path: str, method: str, body: bytes, query_params: dict, request_id: str,+ headers: dict | None = None):"""Handle S3 Control operations addressed via the /v20180820 path prefix."""if not path.startswith(_S3_CONTROL_PREFIX):return None+ if path.startswith(_S3_CONTROL_MRAP_PREFIXES) or path.rstrip("/") == "/v20180820/mrap/instances":+ s3 = _get_module("s3")+ headers = headers or {}+ if AUTH:+ from ministack.core.iam_actions import s3control_action++ action = s3control_action(method, path)+ if action:+ denied = _enforce_data_plane("s3", action, headers, query_params, request_id,+ resource_arn=_s3control_mrap_arn(s3, path))+ if denied:+ return denied+ status, resp_headers, resp_body = (+ s3.s3control_account_error(headers)+ or s3.handle_mrap_control(method, path, headers, body, query_params)+ )+ return status, {**resp_headers, "x-amzn-requestid": request_id}, resp_body+if path.startswith("/v20180820/tags/"):raw_arn = path[len("/v20180820/tags/") :]arn = unquote(raw_arn)@@ -2112,7 +2146,8 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: d}mrap_path = "/" + mrap_bucket + (path if path != "/" else "/")return await _get_module("s3").handle_request(- method, mrap_path, headers, body, query_params, signed_path=path+ method, mrap_path, headers, body, query_params, signed_path=path,+ enforce_bucket_region=False,)bucket = _extract_s3_vhost_bucket(host)@@ -2298,7 +2333,7 @@ async def _handle_special_data_plane_request(except Exception as e:logger.exception("Error in Iceberg REST catalog: %s", e)return 500, {"Content-Type": "application/json"}, json.dumps({"error": str(e)}).encode()- if response := await _handle_s3_control_request(path, method, body, query_params, request_id):+ if response := await _handle_s3_control_request(path, method, body, query_params, request_id, headers):return responseif response := await _handle_rds_data_request(method, path, headers, body, query_params):return responsediff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex acbe4c5c..d7b63598 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -266,6 +266,37 @@ _S3_VERSIONED_ACTIONS: dict[str, str] = {}+_S3CONTROL_MRAP_ASYNC_ACTIONS = {+ "create": "s3:CreateMultiRegionAccessPoint",+ "delete": "s3:DeleteMultiRegionAccessPoint",+ "put-policy": "s3:PutMultiRegionAccessPointPolicy",+}+++def s3control_action(method: str, path: str) -> str | None:+ """IAM action for an S3 Control Multi-Region Access Point request, or None."""+ from urllib.parse import unquote++ path = unquote(path).rstrip("/")+ async_prefix = "/v20180820/async-requests/mrap/"+ instances = "/v20180820/mrap/instances"+ if path.startswith(async_prefix):+ tail = path[len(async_prefix):]+ if method == "POST":+ return _S3CONTROL_MRAP_ASYNC_ACTIONS.get(tail)+ return "s3:DescribeMultiRegionAccessPointOperation" if method == "GET" else None+ if path == instances:+ return "s3:ListMultiRegionAccessPoints" if method == "GET" else None+ if path.startswith(instances + "/"):+ if path.endswith("/routes"):+ return {"GET": "s3:GetMultiRegionAccessPointRoutes",+ "PATCH": "s3:SubmitMultiRegionAccessPointRoutes"}.get(method)+ if path.endswith("/policy"):+ return "s3:GetMultiRegionAccessPointPolicy" if method == "GET" else None+ return "s3:GetMultiRegionAccessPoint" if method == "GET" else None+ return None++def _s3_action(method: str, path: str, query_params: dict) -> str | None:parts = [p for p in path.split("/") if p]depth = min(len(parts), 2)diff --git a/ministack/core/router.py b/ministack/core/router.pyindex 4d39db11..5a57563c 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -1388,19 +1388,53 @@ def _credential_from_query(query_params) -> str:return cred or ""-def extract_region(headers: dict, query_params=None) -> str:- """Extract AWS region from the request (Authorization header, then SigV4- presigned ``X-Amz-Credential`` query param)."""+def _query_value(query_params, name: str) -> str:+ if not query_params:+ return ""+ value = query_params.get(name) or query_params.get(name.lower())+ if isinstance(value, (list, tuple)):+ value = value[0] if value else ""+ return value or ""+++def _single_region(region_set: str) -> str | None:+ """A SigV4a ``X-Amz-Region-Set`` names one region only when it holds no+ wildcard and no list."""+ region_set = region_set.strip()+ if not region_set or "*" in region_set or "," in region_set:+ return None+ return region_set+++def extract_signed_region(headers: dict, query_params=None) -> str | None:+ """Region the request was signed for, or None when it carries none.++ SigV4 scopes are ``AKID/date/region/service/aws4_request``. SigV4a scopes+ drop the region (``AKID/date/service/aws4_request``) and sign an+ ``X-Amz-Region-Set`` instead, which only counts when it names one region.+ Unsigned, SigV2 and malformed requests have no signed region."""auth = headers.get("authorization", "")- match = re.search(r"Credential=[^/]+/[^/]+/([^/]+)/", auth)- if match:- return match.group(1)- cred = _credential_from_query(query_params)- if cred:- parts = cred.split("/")- if len(parts) >= 3 and parts[2]:+ if auth.startswith("AWS4-HMAC-SHA256"):+ match = re.search(r"Credential=[^/]+/\d{8}/([^/]+)/[^/]+/aws4_request", auth)+ return match.group(1) if match else None+ if auth.startswith("AWS4-ECDSA-P256-SHA256"):+ return _single_region(headers.get("x-amz-region-set", ""))+ algorithm = _query_value(query_params, "X-Amz-Algorithm")+ if algorithm == "AWS4-ECDSA-P256-SHA256":+ return _single_region(_query_value(query_params, "X-Amz-Region-Set"))+ # A bare X-Amz-Credential (no algorithm) still names its region, as+ # IoT WebSocket and AppSync clients send it.+ if algorithm in ("", "AWS4-HMAC-SHA256"):+ parts = _credential_from_query(query_params).split("/")+ if len(parts) == 5 and parts[2] and parts[4] == "aws4_request":return parts[2]- return os.environ.get("MINISTACK_REGION", "us-east-1")+ return None+++def extract_region(headers: dict, query_params=None) -> str:+ """Extract AWS region from the request (Authorization header, then SigV4+ presigned ``X-Amz-Credential`` query param), else the default region."""+ return extract_signed_region(headers, query_params) or os.environ.get("MINISTACK_REGION", "us-east-1")def extract_access_key_id(headers: dict, query_params=None) -> str:diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.pyindex a1b551bf..1e413106 100644--- a/ministack/services/cloudformation/handlers.py+++ b/ministack/services/cloudformation/handlers.py@@ -600,6 +600,45 @@ def _describe_stack_events(params):f"{next_token_xml}</DescribeStackEventsResult>")+# --- DescribeEvents ---++_OPERATION_EVENT_FIELDS = (+ "EventId", "StackId", "OperationId", "OperationType", "OperationStatus", "EventType",+ "LogicalResourceId", "PhysicalResourceId", "ResourceType", "Timestamp", "ResourceStatus",+ "ResourceStatusReason", "DetailedStatus", "ValidationFailureMode", "ValidationName",+ "ValidationStatus", "ValidationStatusReason", "ValidationPath",+)+++def _describe_events(params):+ """The operation events of a stack. MiniStack records them for a create+ that fails pre-deployment validation, the case the stack event tells the+ caller to call DescribeEvents for; change-set events are not recorded."""+ stack_name = _p(params, "StackName")+ if not stack_name:+ return _error("ValidationError", "StackName is required")+ stack = _resolve_stack(stack_name)+ if not stack:+ return _error("ValidationError", f"Stack [{stack_name}] does not exist")+ events = list(stack.get("_operation_events") or [])+ operation_id = _p(params, "OperationId")+ if operation_id:+ events = [e for e in events if e.get("OperationId") == operation_id]+ if _p(params, "Filters.FailedEvents").lower() == "true":+ events = [e for e in events if e.get("OperationStatus") == "FAILED"]+ events, next_token_xml, err = _page(events, params, "DescribeEvents")+ if err:+ return err+ members = "".join(+ "<member>" + "".join(f"<{f}>{_esc(str(e[f]))}</{f}>" for f in _OPERATION_EVENT_FIELDS if e.get(f))+ + "</member>"+ for e in events+ )+ return _xml(200, "DescribeEventsResponse",+ f"<DescribeEventsResult><OperationEvents>{members}</OperationEvents>"+ f"{next_token_xml}</DescribeEventsResult>")++# --- DescribeStackResource ---def _resource_status_reason_xml(res):@@ -1709,6 +1748,7 @@ _ACTION_HANDLERS = {"DeleteStack": _delete_stack,"UpdateStack": _update_stack,"DescribeStackEvents": _describe_stack_events,+ "DescribeEvents": _describe_events,"DescribeStackResource": _describe_stack_resource,"DescribeStackResources": _describe_stack_resources,"ListStackResources": _list_stack_resources,diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex f8c4e89f..215ebade 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -1416,31 +1416,22 @@ def _s3_mrap_create(logical_id, props, stack_name):if isinstance(r, dict) and r.get("Bucket")]- for existing in _s3._mraps.values():- if existing.get("Name") == name:- return existing["Alias"], {"Alias": existing["Alias"],- "CreatedAt": existing["CreatedAt"]}+ existing = _s3.find_mrap(name)+ if existing is not None and existing.get("Name") == name:+ return existing["Alias"], {"Alias": existing["Alias"],+ "CreatedAt": existing["CreatedAt"]}- alias = _s3.new_mrap_alias()- created_at = now_iso()- _s3._mraps[alias] = {- "Name": name,- "Alias": alias,- "Regions": buckets,- "CreatedAt": created_at,- "PublicAccessBlockConfiguration": props.get("PublicAccessBlockConfiguration") or {},- }+ # strict=False: the provisioner has never applied the S3 Control bucket checks.+ record = _s3.create_mrap(name, buckets, props.get("PublicAccessBlockConfiguration") or {}, strict=False)logger.info("Created MultiRegionAccessPoint %s alias=%s over %d bucket(s)",- name, alias, len(buckets))+ name, record["Alias"], len(buckets))# The physical id is the NAME (what DeleteMultiRegionAccessPoint takes);# `Alias` is the attribute a distribution origin is built from.- return name, {"Alias": alias, "CreatedAt": created_at}+ return name, {"Alias": record["Alias"], "CreatedAt": record["CreatedAt"]}def _s3_mrap_delete(physical_id, props):- for alias, record in list(_s3._mraps.items()):- if record.get("Name") == physical_id:- _s3._mraps.pop(alias, None)+ _s3.delete_mrap(physical_id)def _s3_attrs(name):@@ -1452,8 +1443,32 @@ def _s3_attrs(name):}+# AWS fails CreateStack when an AWS::S3::Bucket names a bucket that already+# exists. MiniStack adopts an own existing bucket by default, which keeps S3+# data usable when it outlives the CloudFormation state (S3 persistence with a+# fresh stack store); 0 gives AWS's behaviour.+CFN_S3_ADOPT_EXISTING_BUCKET = os.environ.get("CFN_S3_ADOPT_EXISTING_BUCKET", "1") == "1"+++def s3_bucket_name_conflict(name: str) -> str | None:+ """The NAME_CONFLICT_VALIDATION message for a bucket name the stack can't+ take, or None. Another account's bucket is never taken; an own bucket only+ when CFN_S3_ADOPT_EXISTING_BUCKET is off."""+ owner = _s3._bucket_owner_account(name)+ if owner is None or (owner == get_account_id() and CFN_S3_ADOPT_EXISTING_BUCKET):+ return None+ return f"Resource of type 'AWS::S3::Bucket' with identifier '{name}' already exists."++def _s3_create(logical_id, props, stack_name):+ if not props.get("BucketName") and not CFN_S3_ADOPT_EXISTING_BUCKET and not _NAME_SEED.get():+ # AWS draws a new auto-name for each stack instance; the seed travels+ # on the resource record, so updates keep the name.+ _NAME_SEED.set(new_uuid()[:8])name = props.get("BucketName") or _physical_name(stack_name, logical_id, lowercase=True, max_len=63)+ conflict = s3_bucket_name_conflict(name)+ if conflict:+ raise ValueError(conflict)_s3._buckets.setdefault(name, {"created": now_iso(),"objects": {},@@ -2159,6 +2174,9 @@ def _lambda_create(logical_id, props, stack_name):# fetch fails.code_zip = _zip_inline(code.get("ZipFile"), handler, runtime)if code_zip is None and code.get("S3Bucket") and code.get("S3Key"):+ region_error = _lambda_svc.s3_code_region_message(code["S3Bucket"])+ if region_error:+ raise ValueError(region_error)code_zip = _lambda_svc._fetch_code_from_s3(code["S3Bucket"],code["S3Key"],@@ -8761,6 +8779,10 @@ def _lambda_layer_create(logical_id, props, stack_name):content = props.get("Content", {})s3_bucket = content.get("S3Bucket", "")s3_key = content.get("S3Key", "")+ if s3_bucket and s3_key:+ region_error = _lambda_svc.s3_code_region_message(s3_bucket, layer=True)+ if region_error:+ raise ValueError(region_error)if layer_name not in _lambda_svc._layers:_lambda_svc._layers[layer_name] = {"versions": [], "next_version": 1}diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.pyindex 3bdac75a..6550a68f 100644--- a/ministack/services/cloudformation/stacks.py+++ b/ministack/services/cloudformation/stacks.py@@ -97,6 +97,16 @@ def _update_keeping_seed(*args):return _update_resource(*args), _NAME_SEED.get()+def _provision_keeping_seed(*args):+ """_provision_resource's result and the name seed a create drew (an+ AWS::S3::Bucket auto-name), starting from none."""+ token = _NAME_SEED.set("")+ try:+ return _provision_resource(*args), _NAME_SEED.get()+ finally:+ _NAME_SEED.reset(token)++# ===========================================================================# Stack Events helper# ===========================================================================@@ -598,9 +608,20 @@ _VALIDATION_FAILED = (_VALIDATION_ROLLBACK = "Validation failure detected. See the operation's FAILED event for details."-def _fail_property_validation(stack, stack_id, stack_name, resources_defs, ordered,- param_values, conditions, mappings, disable_rollback):- """Fail a create with a property outside its schema enum before provisioning anything."""+def _static_property(raw, resources_defs, param_values, conditions, mappings, stack_name, stack_id):+ """A property value resolved before deployment, or None when it references+ another resource and so only resolves at deploy time."""+ if any(name in resources_defs for name, _ in _intrinsic_references(raw)):+ return None+ return _resolve_refs(copy.deepcopy(raw), {}, param_values, conditions, mappings, stack_name, stack_id)+++def _validation_errors(resources_defs, ordered, param_values, conditions, mappings, stack_name, stack_id):+ """Pre-deployment validation errors as ``(logical_id, type, validation name,+ path, reason)``: properties outside their schema enum, and AWS::S3::Bucket+ names the stack can't take (NAME_CONFLICT_VALIDATION, observed on AWS)."""+ from ministack.services.cloudformation.provisioners import s3_bucket_name_conflict+errors = []for logical_id in ordered:res_def = resources_defs[logical_id]@@ -608,31 +629,66 @@ def _fail_property_validation(stack, stack_id, stack_name, resources_defs, orderif cond and not conditions.get(cond, True):continuertype = res_def.get("Type", "")+ raw_props = res_def.get("Properties") or {}props = {}for prop in _PROPERTY_ENUMS.get(rtype, {}):- raw = (res_def.get("Properties") or {}).get(prop)- if any(name in resources_defs for name, _ in _intrinsic_references(raw)):+ if any(name in resources_defs for name, _ in _intrinsic_references(raw_props.get(prop))):continue- props[prop] = _resolve_refs(copy.deepcopy(raw), {}, param_values, conditions,- mappings, stack_name, stack_id)- errors += [(logical_id, prop, reason)+ props[prop] = _static_property(raw_props.get(prop), resources_defs, param_values, conditions,+ mappings, stack_name, stack_id)+ # The enum check's validation name is not observed; PROPERTY_VALIDATION is inferred.+ errors += [(logical_id, rtype, "PROPERTY_VALIDATION", f"/Resources/{logical_id}/Properties/{prop}", reason)for prop, reason in _property_enum_errors(rtype, props)]+ if rtype == "AWS::S3::Bucket" and raw_props.get("BucketName"):+ name = _static_property(raw_props["BucketName"], resources_defs, param_values, conditions,+ mappings, stack_name, stack_id)+ conflict = s3_bucket_name_conflict(name) if isinstance(name, str) else None+ if conflict:+ errors.append((logical_id, rtype, "NAME_CONFLICT_VALIDATION", f"/Resources/{logical_id}", conflict))+ return errors+++def _operation_event(stack_id, operation_id, event_type, **fields):+ return {"EventId": new_uuid(), "StackId": stack_id, "OperationId": operation_id,+ "OperationType": "CREATE_STACK", "OperationStatus": "FAILED", "EventType": event_type,+ "Timestamp": now_iso(), **fields}+++def _fail_property_validation(stack, stack_id, stack_name, resources_defs, ordered,+ param_values, conditions, mappings, disable_rollback):+ """Fail a create that doesn't pass pre-deployment validation before+ provisioning anything. The errors themselves are kept on the stack for+ DescribeEvents, which the stack event points the caller to."""+ errors = _validation_errors(resources_defs, ordered, param_values, conditions, mappings,+ stack_name, stack_id)if not errors:return False- for logical_id, prop, reason in errors:- logger.warning("Stack %s validation: /Resources/%s/Properties/%s: %s",- stack_name, logical_id, prop, reason)- _add_event(stack_id, stack_name, stack_name, "AWS::CloudFormation::Stack",- "CREATE_FAILED", _VALIDATION_FAILED.format(count=len(errors)), stack_id,- detailed_status="VALIDATION_FAILED")+ operation_id = new_uuid()+ operation_events = []+ for logical_id, rtype, validation_name, path, reason in errors:+ logger.warning("Stack %s validation: %s: %s", stack_name, path, reason)+ operation_events.append(_operation_event(+ stack_id, operation_id, "VALIDATION_ERROR", LogicalResourceId=logical_id, ResourceType=rtype,+ ValidationFailureMode="FAIL", ValidationName=validation_name, ValidationStatus="FAILED",+ ValidationStatusReason=reason, ValidationPath=path))++ def stack_event(status, reason, detailed_status=""):+ _add_event(stack_id, stack_name, stack_name, "AWS::CloudFormation::Stack", status, reason, stack_id,+ detailed_status=detailed_status)+ operation_events.append(_operation_event(+ stack_id, operation_id, "PROVISIONING_ERROR", LogicalResourceId=stack_name,+ PhysicalResourceId=stack_id, ResourceType="AWS::CloudFormation::Stack", ResourceStatus=status,+ ResourceStatusReason=reason, **({"DetailedStatus": detailed_status} if detailed_status else {})))++ stack_event("CREATE_FAILED", _VALIDATION_FAILED.format(count=len(errors)), "VALIDATION_FAILED")if disable_rollback:+ stack_event("CREATE_FAILED", _VALIDATION_ROLLBACK)stack["StackStatus"] = "CREATE_FAILED"- return True- _add_event(stack_id, stack_name, stack_name, "AWS::CloudFormation::Stack",- "ROLLBACK_IN_PROGRESS", _VALIDATION_ROLLBACK, stack_id)- _add_event(stack_id, stack_name, stack_name, "AWS::CloudFormation::Stack",- "ROLLBACK_COMPLETE", "", stack_id)- stack["StackStatus"] = "ROLLBACK_COMPLETE"+ else:+ stack_event("ROLLBACK_IN_PROGRESS", _VALIDATION_ROLLBACK)+ stack_event("ROLLBACK_COMPLETE", "")+ stack["StackStatus"] = "ROLLBACK_COMPLETE"+ stack["_operation_events"] = operation_eventsreturn True@@ -832,11 +888,11 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,physical_id, attrs = _adopt_resource(stack_id, stack_name, logical_id, resource_type, imports[logical_id])elif _runs_on_worker_thread(resource_type):- physical_id, attrs = await run_reentrant(- _provision_resource, resource_type, logical_id, new_tagged, stack_name+ (physical_id, attrs), name_seed = await run_reentrant(+ _provision_keeping_seed, resource_type, logical_id, new_tagged, stack_name)else:- physical_id, attrs = _provision_resource(+ (physical_id, attrs), name_seed = _provision_keeping_seed(resource_type, logical_id, new_tagged, stack_name)except Exception as exc:diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 5a3496a8..09da5345 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -1244,6 +1244,26 @@ def _rewrite_host_for_container(url: str) -> str:return url+def s3_code_region_message(bucket: str, layer: bool = False) -> str | None:+ """Lambda reads S3 code from the function's own region. For a bucket homed+ elsewhere, the message AWS returns (observed 2026-10-12); layers word the+ S3 part differently from functions. None when the bucket is local or absent."""+ from ministack.services import s3 as s3_svc++ home = s3_svc.bucket_region(bucket)+ if home is None or home == get_region():+ return None+ s3_message = (f"The bucket is in this region: {home}. Please use this region to retry the request" if layer+ else "The bucket you are attempting to access must be addressed using the specified endpoint. "+ "Please send all future requests to this endpoint.")+ return f"Error occurred while GetObject. S3 Error Code: PermanentRedirect. S3 Error Message: {s3_message}"+++def _s3_code_region_error(bucket: str, layer: bool = False):+ message = s3_code_region_message(bucket, layer)+ return error_response_json("InvalidParameterValueException", message, 400) if message else None++def _fetch_code_from_s3(bucket: str, key: str, version_id: str | None = None) -> bytes | None:"""Fetch Lambda code zip from the in-memory S3 service.@@ -2306,6 +2326,9 @@ def _create_function(data: dict):elif "ZipFile" in code_data:code_zip = base64.b64decode(code_data["ZipFile"])elif "S3Bucket" in code_data and "S3Key" in code_data:+ err = _s3_code_region_error(code_data["S3Bucket"])+ if err is not None:+ return errcode_zip = _fetch_code_from_s3(code_data["S3Bucket"],code_data["S3Key"],@@ -2763,6 +2786,9 @@ def _update_code(name: str, data: dict):elif "ZipFile" in data:code_zip = base64.b64decode(data["ZipFile"])elif "S3Bucket" in data and "S3Key" in data:+ err = _s3_code_region_error(data["S3Bucket"])+ if err is not None:+ return errcode_zip = _fetch_code_from_s3(data["S3Bucket"],data["S3Key"],@@ -6302,6 +6328,11 @@ def _publish_layer_version(layer_name: str, data: dict):"CompatibleArchitectures list length exceeds maximum allowed length of 2.",400,)+ content = data.get("Content", {})+ if "S3Bucket" in content and "S3Key" in content:+ err = _s3_code_region_error(content["S3Bucket"], layer=True)+ if err is not None:+ return errif layer_name not in _layers:_layers[layer_name] = {"versions": [], "next_version": 1}diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex 718ef6a4..86359bc2 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -73,7 +73,7 @@ from ministack.core.responses import (set_request_account_id,set_request_region,)-from ministack.core.router import extract_access_key_id+from ministack.core.router import extract_access_key_id, extract_signed_regionfrom ministack.core.sigv4 import (build_canonical_request,build_string_to_sign,@@ -101,7 +101,11 @@ _bucket_lifecycle = AccountScopedDict()_bucket_cors = AccountScopedDict()# Multi-Region Access Points. Keyed by ALIAS rather than name, because the alias# is what the data plane is addressed by: `<alias>.mrap.accesspoint.s3-global.amazonaws.com`.-_mraps = AccountScopedDict() # Alias -> {Name, Alias, Regions: [bucket, ...], CreatedAt}+# Alias -> {Name, Alias, Regions: [bucket, ...], CreatedAt, PublicAccessBlockConfiguration,+# Routes: {bucket: dial}, Policy}+_mraps = AccountScopedDict()+# S3 Control async request token -> the AsyncOperation DescribeMultiRegionAccessPointOperation reports.+_mrap_operations = AccountScopedDict()def new_mrap_alias() -> str:@@ -116,28 +120,106 @@ def new_mrap_alias() -> str:return base + ".mrap"+class MrapError(Exception):+ """A Multi-Region Access Point request S3 refuses: ``code`` and ``message``+ as AWS reports them."""++ def __init__(self, code: str, message: str):+ super().__init__(message)+ self.code = code+ self.message = message+++def mrap_routes(record: dict) -> dict[str, int]:+ """Traffic dial per member bucket. Records persisted before routes existed+ have none, and every member then receives traffic (dial 100)."""+ routes = record.get("Routes") or {}+ return {bucket: int(routes.get(bucket, 100)) for bucket in record.get("Regions") or []}+++def find_mrap(ref: str) -> dict | None:+ """The MRAP in the current account named by alias, name or ARN+ (``arn:aws:s3::<account>:accesspoint/<alias>``)."""+ if ref.startswith("arn:"):+ ref = ref.rsplit("/", 1)[-1]+ record = _mraps.get(ref)+ if record is not None:+ return record+ return next((r for r in _mraps.values() if r.get("Name") == ref), None)+++def create_mrap(name: str, buckets: list[str], public_access_block: dict | None = None,+ strict: bool = True) -> dict:+ """Create a Multi-Region Access Point over ``buckets`` and return its record.++ ``strict`` applies the S3 Control checks AWS makes (observed 2026-10-12):+ a unique name in the account, every bucket existing in it, and one bucket+ per region. The CloudFormation provisioner predates them and passes False,+ getting back an existing record of the same name instead of an error."""+ existing = find_mrap(name)+ if existing is not None and existing.get("Name") == name:+ if not strict:+ return existing+ raise MrapError(+ "MultiRegionAccessPointAlreadyOwnedByYou",+ "You must provide a unique name for each Multi-Region Access Point in your account. "+ "A MRAP with this name already exists.",+ )+ if strict:+ seen: set[str] = set()+ for bucket in buckets:+ region = bucket_region(bucket)+ if region is None:+ raise MrapError("NoSuchBucket", "The specified bucket does not exist.")+ if region in seen:+ raise MrapError("MultiRegionAccessPointSameBucketRegion",+ "The buckets specified must be part of different Regions.")+ seen.add(region)+ alias = new_mrap_alias()+ record = {+ "Name": name,+ "Alias": alias,+ "Regions": list(buckets),+ "CreatedAt": now_iso(),+ "PublicAccessBlockConfiguration": public_access_block or {},+ "Routes": {bucket: 100 for bucket in buckets},+ "Policy": None,+ }+ _mraps[alias] = record+ return record+++def delete_mrap(name: str) -> bool:+ record = find_mrap(name)+ if record is None:+ return False+ _mraps.pop(record["Alias"], None)+ return True+++def mrap_member(bucket: str) -> bool:+ """Whether a bucket in the current account fronts any MRAP."""+ return any(bucket in (r.get("Regions") or []) for r in _mraps.values())++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 *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.+ AWS routes a request to the closest active member by network proximity,+ not by the region the client signs for (observed: boto3 signs MRAP requests+ with SigV4a and region set ``*``). MiniStack stands in for proximity with+ its own location: among members with a traffic dial of 100, the one homed+ in MINISTACK_REGION wins, otherwise the first in the MRAP's region order."""record = _mraps.get(alias)if not record:return None- buckets = record.get("Regions") or []- if not buckets:+ routes = mrap_routes(record)+ candidates = [bucket for bucket, dial in routes.items() if dial] or list(routes)+ if not candidates:return None- region = get_region()- if region:- for bucket in buckets:- meta = _buckets.get(bucket)- if meta is not None and meta.get("region") == region:- return bucket- return buckets[0]+ local = os.environ.get("MINISTACK_REGION", "us-east-1")+ return next((b for b in candidates if bucket_region(b) == local), candidates[0])_bucket_acl = AccountScopedDict()_bucket_websites = AccountScopedDict()_bucket_logging_config = AccountScopedDict()@@ -189,6 +271,7 @@ _PERSISTED_BUCKET_DICTS = {# baked into client configuration, so member buckets coming back without the# alias fronting them fails where a missing bucket would not."mraps": _mraps,+ "mrap_operations": _mrap_operations,}@@ -737,13 +820,19 @@ def _xml_body(root: Element) -> bytes:return XML_DECL + b"\n" + tostring(root, encoding="unicode").encode("utf-8")-def _error(code: str, message: str, status: int, resource: str = "") -> tuple:+def _error(code: str, message: str, status: int, resource: str = "",+ extra: dict[str, str] | None = None, headers: dict | None = None) -> tuple:+ """S3 error document. ``extra`` adds error-specific elements after+ ``<Resource>`` (``<Region>``, ``<Endpoint>``, ``<BucketName>``…) and+ ``headers`` adds response headers such as ``x-amz-bucket-region``."""root = Element("Error")SubElement(root, "Code").text = codeSubElement(root, "Message").text = messageSubElement(root, "Resource").text = resource+ for tag, text in (extra or {}).items():+ SubElement(root, tag).text = textSubElement(root, "RequestId").text = new_uuid()- return status, {"Content-Type": "application/xml"}, _xml_body(root)+ return status, {"Content-Type": "application/xml", **(headers or {})}, _xml_body(root)def _get_object_data(bucket_name: str, key: str, version_id: str | None = None) -> bytes | None:@@ -919,6 +1008,108 @@ def _request_access_key(method: str, key: str, headers: dict, query_params: dictreturn access_key+_SIGV4_SCOPE_SERVICE_RE = re.compile(r"Credential=[^/]+/\d{8}/[^/]+/([^/]+)/aws4_request")+++def _signed_region(headers: dict, query_params: dict) -> str | None:+ """The region a SigV4 request was signed for with service ``s3``, or None.++ Unsigned, SigV2 and SigV4a requests carry no single signing region an S3+ endpoint can be matched against, so they never fall back to a default."""+ auth = headers.get("authorization", "")+ if auth.startswith("AWS4-HMAC-SHA256"):+ m = _SIGV4_SCOPE_SERVICE_RE.search(auth)+ service = m.group(1) if m else ""+ elif (_qp(query_params, "X-Amz-Algorithm", "") or _qp(query_params, "x-amz-algorithm", "")) == "AWS4-HMAC-SHA256":+ parts = (_qp(query_params, "X-Amz-Credential", "") or _qp(query_params, "x-amz-credential", "")).split("/")+ service = parts[3] if len(parts) == 5 else ""+ else:+ return None+ if service != "s3":+ return None+ return extract_signed_region(headers, query_params)+++def bucket_region(name: str) -> str | None:+ """Home region of a bucket in the current scope, or None if it doesn't exist."""+ record = _buckets.get(name)+ if record is None:+ return None+ return record.get("region") or os.environ.get("MINISTACK_REGION", "us-east-1")+++_REGION_LABEL_RE = re.compile(r"^[a-z]{2}(?:-[a-z]+)+-\d+$")+++def _host_region(headers: dict) -> str | None:+ """Region named by a regional S3 host (``s3.<region>.…`` or+ ``<bucket>.s3.<region>.…``), or None for a global or custom host."""+ labels = headers.get("host", "").lower().rsplit(":", 1)[0].split(".")+ for i, label in enumerate(labels[:-1]):+ if label == "s3" and _REGION_LABEL_RE.match(labels[i + 1]):+ return labels[i + 1]+ return None+++_PERMANENT_REDIRECT_MSG = (+ "The bucket you are attempting to access must be addressed using the specified "+ "endpoint. Please send all future requests to this endpoint."+)+++def _check_bucket_region(method: str, bucket: str, key: str, headers: dict, query_params: dict,+ home: str | None = None):+ """Refuse a request signed for another region than the bucket's home.++ A client configured for the signing region calls that region's endpoint,+ and AWS answers it with ``301 PermanentRedirect`` plus+ ``x-amz-bucket-region``, which SDKs follow. Only a request that reached the+ bucket's own regional endpoint with a signature for another region gets the+ ``400`` authorization errors carrying ``<Region>``. ``home`` overrides the+ bucket's region (an access point's region)."""+ if not bucket:+ return None+ signed = _signed_region(headers, query_params)+ if signed is None:+ return None+ if method == "GET" and not key and "location" in query_params:+ return None+ if method == "PUT" and not key and not query_params:+ return None # CreateBucket has its own location-constraint rules+ home = home or bucket_region(bucket)+ if home is None or home == signed:+ return None++ resource = f"/{bucket}/{key}" if key else f"/{bucket}"+ presigned = bool(_qp(query_params, "X-Amz-Algorithm", "") or _qp(query_params, "x-amz-algorithm", ""))+ if _host_region(headers) == home:+ if method == "HEAD":+ hdrs = {} if key else {"x-amz-bucket-region": home}+ return 400, {"Content-Type": "application/xml", **hdrs}, b""+ if presigned:+ return _error(+ "AuthorizationQueryParametersError",+ f"Error parsing the X-Amz-Credential parameter; the region '{signed}' is wrong; "+ f"expecting '{home}'",+ 400, resource, extra={"Region": home},+ )+ return _error(+ "AuthorizationHeaderMalformed",+ f"The authorization header is malformed; the region '{signed}' is wrong; expecting '{home}'",+ 400, resource, extra={"Region": home},+ )++ region_header = {"x-amz-bucket-region": home}+ if method == "HEAD":+ return 301, {"Content-Type": "application/xml", **region_header}, b""+ if signed == "us-east-1" and _host_region(headers) is None:+ endpoint = f"{bucket}.s3.amazonaws.com"+ else:+ endpoint = f"{bucket}.s3-{home}.amazonaws.com"+ return _error("PermanentRedirect", _PERMANENT_REDIRECT_MSG, 301, resource,+ extra={"Endpoint": endpoint, "Bucket": bucket}, headers=region_header)++def _apply_bucket_scope(method: str, bucket: str, key: str, headers: dict,query_params: dict, body: bytes = b""):"""Resolve the request's bucket in the global namespace and gate it.@@ -1899,6 +2090,7 @@ async def handle_request(body: bytes,query_params: dict,signed_path: str | None = None,+ enforce_bucket_region: bool = True,) -> tuple:bucket, key = _parse_bucket_key(path, headers)@@ -1920,6 +2112,9 @@ async def handle_request(headers = _merge_hoisted_amz_headers(headers, query_params)denied = _apply_bucket_scope(method, bucket, key, headers, query_params, body)+ if denied is None and enforce_bucket_region:+ # After the scope is pinned, so the owner's record names the home region.+ denied = _check_bucket_region(method, bucket, key, headers, query_params)if denied is not None:status, resp_headers, resp_body = deniedresp_headers.setdefault("x-amz-request-id", new_uuid())@@ -1941,7 +2136,7 @@ async def handle_request(def _dispatch(method: str, bucket: str, key: str, headers: dict, body: bytes, query_params: dict) -> tuple:if method == "GET" and not bucket:- return _list_buckets(query_params)+ return _list_buckets(query_params, _signed_region(headers, query_params))# ---- Routes with key ----if key:@@ -2099,7 +2294,7 @@ def _dispatch(method: str, bucket: str, key: str, headers: dict, body: bytes, qureturn _put_bucket_ownership_controls(bucket, body)if "publicAccessBlock" in query_params:return _put_public_access_block(bucket, body)- return _create_bucket(bucket, body, headers)+ return _create_bucket(bucket, body, headers, endpoint_region=_signed_region(headers, query_params))if method == "DELETE":if "policy" in query_params:@@ -2158,13 +2353,24 @@ def _canonical_owner_id(account_id: str = "") -> str:return hashlib.sha256((account_id or get_account_id()).encode()).hexdigest()-def _list_buckets(query_params=None):+def _list_buckets(query_params=None, signed_region: str | None = None):query_params = query_params or {}prefix = _qp(query_params, "prefix", "")max_buckets = int(_qp(query_params, "max-buckets", "0") or "0")continuation = _qp(query_params, "continuation-token", "")+ region_filter = _qp(query_params, "bucket-region", "")+ if region_filter and signed_region and region_filter != signed_region:+ return _error(+ "InvalidArgument",+ "Requests with bucket-region specified must be made to the corresponding regional endpoint",+ 400,+ extra={"ArgumentName": "bucket-region"},+ )- all_names = sorted(n for n in _buckets if n.startswith(prefix))+ all_names = sorted(+ n for n in _buckets+ if n.startswith(prefix) and (not region_filter or bucket_region(n) == region_filter)+ )if continuation:idx = next((i for i, n in enumerate(all_names) if n > continuation), len(all_names))all_names = all_names[idx:]@@ -2186,7 +2392,7 @@ def _list_buckets(query_params=None):b = SubElement(buckets_el, "Bucket")SubElement(b, "Name").text = nameSubElement(b, "CreationDate").text = data["created"]- SubElement(b, "BucketRegion").text = data.get("region") or os.environ.get("MINISTACK_REGION", "us-east-1")+ SubElement(b, "BucketRegion").text = bucket_region(name)SubElement(b, "BucketArn").text = f"arn:aws:s3:::{name}"if prefix:SubElement(root, "Prefix").text = prefix@@ -2197,7 +2403,37 @@ def _list_buckets(query_params=None):return 200, {"Content-Type": "application/xml"}, _xml_body(root)-def _create_bucket(name: str, body: bytes, headers: dict = None):+def _location_constraint(body: bytes) -> str | None:+ if not body:+ return None+ try:+ loc_el = _find_xml_tag(fromstring(body), "LocationConstraint")+ except Exception:+ return None+ return loc_el.text if loc_el is not None and loc_el.text else None+++def _location_constraint_error(name: str, constraint: str | None, endpoint_region: str):+ """CreateBucket's location-constraint rules for a request signed for+ ``endpoint_region`` (observed on AWS 2026-10-12): us-east-1 is never a+ valid constraint, and any other regional endpoint only creates buckets in+ its own region, named explicitly."""+ if constraint == "us-east-1":+ return _error("InvalidLocationConstraint", "The specified location-constraint is not valid",+ 400, f"/{name}", extra={"LocationConstraint": constraint})+ if endpoint_region != "us-east-1" and constraint != endpoint_region:+ return _error(+ "IllegalLocationConstraintException",+ f"The {constraint or 'unspecified'} location constraint is incompatible for the region "+ "specific endpoint this request was sent to.",+ 400, f"/{name}",+ )+ return None+++def _create_bucket(name: str, body: bytes, headers: dict = None, endpoint_region: str | None = None):+ """``endpoint_region`` is the region a signed request was sent to; internal+ callers leave it None and keep the lax ``constraint or get_region()`` rule."""headers = headers or {}if not _validate_bucket_name(name):return _error("InvalidBucketName", "The specified bucket is not valid.", 400, f"/{name}")@@ -2206,13 +2442,17 @@ def _create_bucket(name: str, body: bytes, headers: dict = None):canned_acl = headers.get("x-amz-acl")if canned_acl and canned_acl not in _CANNED_BUCKET_ACLS:return _error("InvalidArgument", f"Invalid x-amz-acl value: {canned_acl}", 400)+ if endpoint_region:+ err = _location_constraint_error(name, _location_constraint(body), endpoint_region)+ if err is not None:+ return errif name in _buckets:# Outside us-east-1 AWS returns BucketAlreadyOwnedByYou; in us-east-1,# "returns 200 OK and resets the bucket access control lists (ACLs)".if _buckets[name].get("region", "us-east-1") != "us-east-1":return _error("BucketAlreadyOwnedByYou",- "The bucket you tried to create already exists, and you own it.",- 409, f"/{name}")+ "Your previous request to create the named bucket succeeded and you already own it.",+ 409, f"/{name}", extra={"BucketName": name})_bucket_acl.pop(name, None)if canned_acl:_bucket_acl[name] = _canned_acl_policy_xml(canned_acl, _canonical_owner_id())@@ -2228,6 +2468,7 @@ def _create_bucket(name: str, body: bytes, headers: dict = None):"name and try again.",409,f"/{name}",+ extra={"BucketName": name},)region = None@@ -2286,6 +2527,9 @@ def _delete_bucket(name: str):bucket = _ensure_bucket(name)if bucket is None:return _no_such_bucket(name)+ if mrap_member(name):+ return _error("BucketHasAccessPointsAttached",+ "Bucket has access points attached and cannot be deleted.", 400, f"/{name}")if bucket["objects"] or _bucket_has_versions(name):return _error("BucketNotEmpty",@@ -2330,7 +2574,7 @@ def _head_bucket(name: str):200,{"Content-Type": "application/xml",- "x-amz-bucket-region": _buckets[name].get("region") or os.environ.get("MINISTACK_REGION", "us-east-1"),+ "x-amz-bucket-region": bucket_region(name),},b"",)@@ -2340,7 +2584,7 @@ def _get_bucket_location(name: str):if name not in _buckets:return _no_such_bucket(name)root = Element("LocationConstraint", xmlns=S3_NS)- region = _buckets[name].get("region") or os.environ.get("MINISTACK_REGION", "us-east-1")+ region = bucket_region(name)# AWS returns an empty LocationConstraint only for us-east-1 buckets;# every other region is echoed back verbatim.if region != "us-east-1":@@ -3889,7 +4133,7 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):resp_headers = {"ETag": obj["etag"], "Content-Length": "0"}resp_headers.update(sse_headers)- _maybe_replicate(bucket_name, key, obj, body)+ _maybe_replicate(bucket_name, key, obj, body, pending_tags)version_id = _record_object_version(bucket_name, key, prior_obj, obj, body)if version_id:resp_headers["x-amz-version-id"] = version_id@@ -4135,7 +4379,7 @@ def _post_object(bucket_name: str, body: bytes, headers: dict):if len(parsed) <= 10:pending_tags = parsed- _maybe_replicate(bucket_name, key, obj, file_value)+ _maybe_replicate(bucket_name, key, obj, file_value, pending_tags)version_id = _record_object_version(bucket_name, key, prior_obj, obj, file_value)_fire_s3_event_async(bucket_name, key, "s3:ObjectCreated:Post", size=obj["size"], etag=etag, version_id=version_id)@@ -4661,25 +4905,41 @@ def _preserve_null_version(bucket_name: str, key: str, versions: list, prior_objversions.append(_version_entry_from_record(prior_obj, "null", _read_body(bucket_name, key, prior_obj)))-def _replication_rule_for(bucket_name: str, key: str) -> tuple[dict | None, str]:- """The first Enabled rule whose filter covers `key`, plus the config Role.+def _replication_rule_prefix(rule: dict) -> str:+ """Legacy V1 rules carry ``Prefix`` directly, V2 rules inside ``Filter``."""+ prefix = rule.get("Prefix")+ if prefix is None:+ rule_filter = rule.get("Filter") or {}+ prefix = rule_filter.get("Prefix") or (rule_filter.get("And") or {}).get("Prefix") or ""+ return prefix+++def _replication_rule_tags(rule: dict) -> dict[str, str]:+ """Tags a V2 rule's ``Filter.Tag`` or ``Filter.And.Tags`` requires."""+ rule_filter = rule.get("Filter") or {}+ tags = [rule_filter["Tag"]] if rule_filter.get("Tag") else (rule_filter.get("And") or {}).get("Tags", [])+ return {t.get("Key", ""): t.get("Value", "") for t in tags}+- A rule matches when the key falls under its prefix — legacy V1 rules carry- ``Prefix`` directly, V2 rules carry it inside ``Filter``. Replication runs- only while the source bucket's versioning is Enabled, as on AWS (a- Suspended bucket stops replicating; the stored config stays).+def _replication_rule_for(bucket_name: str, key: str, tags: dict | None) -> tuple[dict | None, str]:+ """The first Enabled rule whose filter covers `key` and `tags`, plus the+ config Role.++ A rule matches when the key falls under its prefix and the object carries+ every tag the rule's filter names. ``tags`` are the tags the write stores.+ Replication runs only while the source bucket's versioning is Enabled, as+ on AWS (a Suspended bucket stops replicating; the stored config stays)."""config = _bucket_replication.get(bucket_name)if not config or _bucket_versioning.get(bucket_name) != "Enabled":return None, ""+ tags = tags or {}for rule in config.get("Rules", []):if rule.get("Status") != "Enabled":continue- prefix = rule.get("Prefix")- if prefix is None:- rule_filter = rule.get("Filter") or {}- prefix = rule_filter.get("Prefix") or (rule_filter.get("And") or {}).get("Prefix") or ""- if key.startswith(prefix):+ if not key.startswith(_replication_rule_prefix(rule)):+ continue+ if all(tags.get(k) == v for k, v in _replication_rule_tags(rule).items()):return rule, config.get("Role", "")return None, ""@@ -4752,7 +5012,50 @@ def _replication_destination_allows(dest_account: str, dest_name: str, key: str,return True-def _maybe_replicate(bucket_name: str, key: str, obj: dict, data) -> None:+def _replication_destination(bucket_name: str, key: str, rule: dict, role: str):+ """``(dest_name, dest_account, dest_bucket)`` for a rule's destination, or+ None when the replica can't be written: the destination is gone, is the+ source, isn't versioned, or (cross-account) its policy doesn't grant the+ replication role."""+ dest = rule.get("Destination") or {}+ dest_ref = dest.get("Bucket") or ""+ dest_name = dest_ref.split(":::")[-1] if ":::" in dest_ref else dest_ref+ # The name identifies the bucket; Destination.Account only names the owner for AccessControlTranslation.+ dest_account = _bucket_owner_account(dest_name)+ dest_bucket = _buckets.get_scoped(dest_account, None, dest_name) if dest_account else None+ if (dest_bucket is None or dest_name == bucket_name+ or _bucket_versioning.get_scoped(dest_account, None, dest_name) != "Enabled"):+ return None+ if (dest_account != get_account_id() and not _replication_destination_allows(+ dest_account, dest_name, key, role, dest, dest_bucket)):+ return None+ return dest_name, dest_account, dest_bucket+++def _maybe_replicate_delete_marker(bucket_name: str, key: str) -> None:+ """Replicate a delete marker the way AWS does: only for a V2 rule (one with+ ``Filter``) that has ``DeleteMarkerReplication`` Enabled and no tag filter.+ Called only for deletes without a version id; version-id deletes never+ replicate. Replica markers are not re-replicated, so two-way setups don't+ loop."""+ config = _bucket_replication.get(bucket_name)+ if not config or _bucket_versioning.get(bucket_name) != "Enabled":+ return+ rule = next((r for r in config.get("Rules", [])+ if r.get("Status") == "Enabled" and key.startswith(_replication_rule_prefix(r))), None)+ if (rule is None or "Filter" not in rule or _replication_rule_tags(rule)+ or (rule.get("DeleteMarkerReplication") or {}).get("Status") != "Enabled"):+ return+ target = _replication_destination(bucket_name, key, rule, config.get("Role", ""))+ if target is None:+ return+ dest_name, dest_account, dest_bucket = target+ with _in_account(dest_account):+ _record_delete_marker(dest_name, key, dest_bucket["objects"].get(key))+ dest_bucket["objects"].pop(key, None)+++def _maybe_replicate(bucket_name: str, key: str, obj: dict, data, tags: dict | None = None) -> None:"""Write the replica a matching replication rule asks for, and stamp thesource's x-amz-replication-status.@@ -4765,26 +5068,18 @@ def _maybe_replicate(bucket_name: str, key: str, obj: dict, data) -> None:source FAILED, which is how AWS reports a replica it could not write.A destination owned by another account also requires the destination'sbucket policy to grant the replication role; otherwise AWS fails the- replica the same way.+ replica the same way. ``tags`` are the tags the write stores, matched+ against tag-filtered rules."""- rule, role = _replication_rule_for(bucket_name, key)+ rule, role = _replication_rule_for(bucket_name, key, tags)if rule is None:return- dest = rule.get("Destination") or {}- dest_ref = dest.get("Bucket") or ""- dest_name = dest_ref.split(":::")[-1] if ":::" in dest_ref else dest_ref- source_account = get_account_id()- # The name identifies the bucket; Destination.Account only names the owner for AccessControlTranslation.- dest_account = _bucket_owner_account(dest_name)- dest_bucket = _buckets.get_scoped(dest_account, None, dest_name) if dest_account else None- if (dest_bucket is None or dest_name == bucket_name- or _bucket_versioning.get_scoped(dest_account, None, dest_name) != "Enabled"):- obj["replication_status"] = "FAILED"- return- if (dest_account != source_account and not _replication_destination_allows(- dest_account, dest_name, key, role, dest, dest_bucket)):+ target = _replication_destination(bucket_name, key, rule, role)+ if target is None:obj["replication_status"] = "FAILED"return+ dest_name, dest_account, dest_bucket = target+ dest = rule.get("Destination") or {}replica = copy.deepcopy(obj)replica["replication_status"] = "REPLICA"@@ -5032,6 +5327,7 @@ def _delete_object(bucket_name: str, key: str, headers: dict | None = None, querdelete_marker_id = _record_delete_marker(bucket_name, key, bucket["objects"].get(key))existed = key in bucket["objects"]bucket["objects"].pop(key, None)+ _maybe_replicate_delete_marker(bucket_name, key)if existed:_fire_s3_event_async(bucket_name,@@ -5355,7 +5651,7 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):resp_headers["x-amz-copy-source-version-id"] = copy_src_vidif dest_sc != "STANDARD":resp_headers["x-amz-storage-class"] = dest_sc- _maybe_replicate(bucket_name, dest_key, dest_obj, src_body)+ _maybe_replicate(bucket_name, dest_key, dest_obj, src_body, pending_dest_tags)version_id = _record_object_version(bucket_name, dest_key, dest_prior_obj, dest_obj, src_body)if version_id:resp_headers["x-amz-version-id"] = version_id@@ -6851,6 +7147,7 @@ def _delete_objects(bucket_name: str, body: bytes, headers: dict = None):existed = k in bucket["objects"]marker_id = _record_delete_marker(bucket_name, k, bucket["objects"].get(k))bucket["objects"].pop(k, None)+ _maybe_replicate_delete_marker(bucket_name, k)deleted.append({"key": k, "version_id": "", "was_marker": False, "marker_created": marker_id})if existed:_fire_s3_event_async(@@ -7942,6 +8239,319 @@ def _load_persisted_history(account_id, bucket, bucket_name, key, meta):_load_persisted_data()+# ---------------------------------------------------------------------------+# S3 Control: Multi-Region Access Points+# ---------------------------------------------------------------------------++S3CONTROL_NS = "https://awss3control.amazonaws.com/doc/2018-08-20/"+_MRAP_ASYNC_PREFIX = "/v20180820/async-requests/mrap/"+_MRAP_INSTANCES_PREFIX = "/v20180820/mrap/instances"+# Where AWS serves the MRAP control plane (observed 2026-10-12). Route+# operations are listed in the order AWS's redirect message names them.+_MRAP_MANAGEMENT_REGION = "us-west-2"+_MRAP_ROUTE_REGIONS = ("us-west-2", "ap-southeast-2", "ap-northeast-1", "eu-west-1", "us-east-1")+_MRAP_ASYNC_OPERATIONS = {+ "create": "CreateMultiRegionAccessPoint",+ "delete": "DeleteMultiRegionAccessPoint",+ "put-policy": "PutMultiRegionAccessPointPolicy",+}+++def s3control_error(code: str, message: str, status: int, extra: dict[str, str] | None = None) -> tuple:+ """An S3 Control error, ``<ErrorResponse>``-wrapped as S3 Control answers."""+ root = Element("ErrorResponse")+ err = SubElement(root, "Error")+ SubElement(err, "Code").text = code+ SubElement(err, "Message").text = message+ for tag, text in (extra or {}).items():+ SubElement(err, tag).text = text+ SubElement(root, "RequestId").text = new_uuid()+ SubElement(root, "HostId").text = base64.b64encode(os.urandom(48)).decode()+ return status, {"Content-Type": "application/xml"}, _xml_body(root)+++def s3control_account_error(headers: dict) -> tuple | None:+ """S3 Control names the account in ``x-amz-account-id``; a caller may only+ address its own."""+ if headers.get("x-amz-account-id", "") != get_account_id():+ return s3control_error("AccessDenied", "Access Denied", 403)+ return None+++def _s3control_response(root: Element) -> tuple:+ return 200, {"Content-Type": "application/xml"}, _xml_body(root)+++def _local_tag(el) -> str:+ return el.tag.split("}")[-1]+++def _child(el, name: str):+ return next((c for c in el if _local_tag(c) == name), None) if el is not None else None+++def _child_text(el, name: str, default: str = "") -> str:+ found = _child(el, name)+ return found.text or default if found is not None else default+++def _mrap_region_error(path: str, routes: bool) -> tuple:+ regions = (", ".join(_MRAP_ROUTE_REGIONS[:-1]) + f" and {_MRAP_ROUTE_REGIONS[-1]}") if routes \+ else _MRAP_MANAGEMENT_REGION+ return s3control_error(+ "PermanentRedirect",+ f"This API operation is only available in the following Regions: {regions}. "+ "Make sure to send all future requests to a supported Region.",+ 301,+ extra={"Endpoint": f"https://s3-control.{_MRAP_MANAGEMENT_REGION}.amazonaws.com{path}"},+ )+++def _no_such_mrap(name: str) -> tuple:+ return s3control_error("NoSuchMultiRegionAccessPoint",+ "The specified Multi-Region Access Point does not exist.", 404,+ extra={"MultiRegionAccessPointName": name, "AccountId": get_account_id()})+++def _pab_xml(parent, pab: dict | None) -> None:+ el = SubElement(parent, "PublicAccessBlock")+ for field in ("BlockPublicAcls", "IgnorePublicAcls", "BlockPublicPolicy", "RestrictPublicBuckets"):+ value = (pab or {}).get(field, True)+ SubElement(el, field).text = str(value).lower() if isinstance(value, bool) else str(value or "true").lower()+++def _mrap_report_xml(parent, record: dict, tag: str = "AccessPoint") -> None:+ ap = SubElement(parent, tag)+ SubElement(ap, "Name").text = record["Name"]+ SubElement(ap, "Alias").text = record["Alias"]+ SubElement(ap, "CreatedAt").text = record["CreatedAt"]+ _pab_xml(ap, record.get("PublicAccessBlockConfiguration"))+ # AWS reports CREATING for about a minute; MiniStack creates synchronously.+ SubElement(ap, "Status").text = "READY"+ regions = SubElement(ap, "Regions")+ for bucket in record.get("Regions") or []:+ region_el = SubElement(regions, "Region")+ SubElement(region_el, "Bucket").text = bucket+ SubElement(region_el, "Region").text = bucket_region(bucket) or get_region()+ SubElement(region_el, "BucketAccountId").text = get_account_id()+++def _parse_pab(el) -> dict:+ if el is None:+ return {}+ return {_local_tag(c): (c.text or "").strip().lower() == "true" for c in el}+++def _mrap_async(op_segment: str, body: bytes, signed_region: str | None) -> tuple:+ """Create, Delete and PutPolicy. AWS runs them asynchronously, walking NEW+ -> INPROGRESS -> SUCCEEDED/FAILED over about a minute; MiniStack applies+ them at once and records the final status for Describe."""+ operation = _MRAP_ASYNC_OPERATIONS[op_segment]+ try:+ root = fromstring(body)+ except Exception:+ return s3control_error("MalformedXML", "The XML you provided was not well-formed", 400)+ details = _child(root, "Details")+ name = _child_text(details, "Name")+ token_arn = (f"arn:aws:s3:{signed_region or get_region()}:{get_account_id()}:async-request/mrap/"+ f"{op_segment}/{new_uuid()}")+ region_results: list[dict] = []+ if operation == "CreateMultiRegionAccessPoint":+ regions_el = _child(details, "Regions")+ buckets = [_child_text(r, "Bucket") for r in regions_el] if regions_el is not None else []+ params = {"Name": name, "PublicAccessBlock": _parse_pab(_child(details, "PublicAccessBlock")),+ "Regions": buckets}+ elif operation == "PutMultiRegionAccessPointPolicy":+ params = {"Name": name, "Policy": _child_text(details, "Policy")}+ else:+ params = {"Name": name}++ error = None+ try:+ if operation == "CreateMultiRegionAccessPoint":+ record = create_mrap(name, params["Regions"], params["PublicAccessBlock"])+ region_results = [{"Name": bucket_region(b), "RequestStatus": "SUCCEEDED"} for b in record["Regions"]]+ elif operation == "DeleteMultiRegionAccessPoint":+ record = find_mrap(name)+ if record is None:+ raise MrapError("NoSuchMultiRegionAccessPoint",+ "The specified Multi-Region Access Point does not exist.")+ region_results = [{"Name": bucket_region(b) or get_region(), "RequestStatus": "SUCCEEDED"}+ for b in record["Regions"]]+ delete_mrap(name)+ else:+ record = find_mrap(name)+ if record is None:+ raise MrapError("NoSuchMultiRegionAccessPoint",+ "The specified Multi-Region Access Point does not exist.")+ record["Policy"] = params["Policy"]+ except MrapError as exc:+ error = {"Code": exc.code, "Message": exc.message, "Resource": name, "RequestId": new_uuid()}+ region_results = []++ _mrap_operations[token_arn] = {+ "RequestTokenARN": token_arn,+ "Operation": operation,+ "RequestParameters": params,+ "RequestStatus": "FAILED" if error else "SUCCEEDED",+ "CreationTime": now_iso(),+ "Regions": region_results,+ "ErrorDetails": error,+ }+ out = Element(f"{operation}Result", xmlns=S3CONTROL_NS)+ SubElement(out, "RequestTokenARN").text = token_arn+ return _s3control_response(out)+++def _mrap_describe(token_arn: str) -> tuple:+ op = _mrap_operations.get(token_arn)+ if op is None:+ return s3control_error("NoSuchAsyncRequest", "The specified async request does not exist.", 404)+ out = Element("DescribeMultiRegionAccessPointOperationResult", xmlns=S3CONTROL_NS)+ async_op = SubElement(out, "AsyncOperation")+ SubElement(async_op, "CreationTime").text = op["CreationTime"]+ SubElement(async_op, "Operation").text = op["Operation"]+ SubElement(async_op, "RequestTokenARN").text = op["RequestTokenARN"]+ params_el = SubElement(SubElement(async_op, "RequestParameters"), f"{op['Operation']}Request")+ params = op["RequestParameters"]+ SubElement(params_el, "Name").text = params.get("Name", "")+ if "Policy" in params:+ SubElement(params_el, "Policy").text = params["Policy"]+ if "Regions" in params:+ _pab_xml(params_el, params.get("PublicAccessBlock"))+ regions = SubElement(params_el, "Regions")+ for bucket in params["Regions"]:+ SubElement(SubElement(regions, "Region"), "Bucket").text = bucket+ SubElement(async_op, "RequestStatus").text = op["RequestStatus"]+ details = SubElement(async_op, "ResponseDetails")+ regions = SubElement(SubElement(details, "MultiRegionAccessPointDetails"), "Regions")+ for result in op["Regions"]:+ region_el = SubElement(regions, "Region")+ SubElement(region_el, "Name").text = result["Name"]+ SubElement(region_el, "RequestStatus").text = result["RequestStatus"]+ if op["ErrorDetails"]:+ err_el = SubElement(details, "ErrorDetails")+ for field in ("Code", "Message", "Resource", "RequestId"):+ SubElement(err_el, field).text = op["ErrorDetails"][field]+ return _s3control_response(out)+++def _mrap_list(query_params: dict) -> tuple:+ records = sorted(_mraps.values(), key=lambda r: (r["CreatedAt"], r["Name"]))+ start = int(_qp(query_params, "nextToken", "0") or "0")+ max_results = int(_qp(query_params, "maxResults", "1000") or "1000")+ page = records[start:start + max_results]+ out = Element("ListMultiRegionAccessPointsResult", xmlns=S3CONTROL_NS)+ aps = SubElement(out, "AccessPoints")+ for record in page:+ _mrap_report_xml(aps, record)+ if start + max_results < len(records):+ SubElement(out, "NextToken").text = str(start + max_results)+ return _s3control_response(out)+++def _mrap_policy(record: dict) -> tuple:+ out = Element("GetMultiRegionAccessPointPolicyResult", xmlns=S3CONTROL_NS)+ policy_el = SubElement(out, "Policy")+ if record.get("Policy"):+ # AWS keeps the proposed policy until it propagates; MiniStack applies at once.+ for state in ("Established", "Proposed"):+ SubElement(SubElement(policy_el, state), "Policy").text = record["Policy"]+ return _s3control_response(out)+++def _mrap_get_routes(arn: str, record: dict) -> tuple:+ out = Element("GetMultiRegionAccessPointRoutesResult", xmlns=S3CONTROL_NS)+ SubElement(out, "Mrap").text = arn+ routes_el = SubElement(out, "Routes")+ for bucket, dial in mrap_routes(record).items():+ route = SubElement(routes_el, "Route")+ SubElement(route, "Bucket").text = bucket+ SubElement(route, "Region").text = bucket_region(bucket) or get_region()+ SubElement(route, "TrafficDialPercentage").text = str(dial)+ return _s3control_response(out)+++def _mrap_submit_routes(record: dict, body: bytes) -> tuple:+ """Traffic dials are 0 or 100, only for members, and at least one member+ must stay active (observed); a refused update leaves the routes as they were."""+ try:+ root = fromstring(body)+ except Exception:+ return s3control_error("MalformedXML", "The XML you provided was not well-formed", 400)+ routes = mrap_routes(record)+ by_region = {bucket_region(b): b for b in routes}+ updated = dict(routes)+ updates_el = _child(root, "RouteUpdates")+ for route in updates_el if updates_el is not None else []:+ dial = _child_text(route, "TrafficDialPercentage")+ if dial not in ("0", "100"):+ return s3control_error("InvalidRequest", "Request invalid", 400)+ bucket = _child_text(route, "Bucket") or by_region.get(_child_text(route, "Region"))+ if bucket not in routes:+ return s3control_error("InvalidRequest",+ "The provided Region or bucket is not part of the Multi-Region Access Point.",+ 400)+ updated[bucket] = int(dial)+ if not any(updated.values()):+ return s3control_error(+ "InvalidRequest",+ "At least one Region or bucket in the Multi-Region Access Point must be configured to receive "+ "traffic. Set at least one Region or bucket to Active, and then try again.",+ 400,+ )+ record["Routes"] = updated+ return 200, {"Content-Type": "application/xml"}, b""+++def handle_mrap_control(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:+ """S3 Control's Multi-Region Access Point operations (``/v20180820/mrap/``+ and ``/v20180820/async-requests/mrap/``). Management is served from+ us-west-2 and route operations from five regions, as on AWS; a request+ without a signing region is let through, as S3's own region check does."""+ signed = _signed_region(headers, query_params)+ decoded = url_unquote(path)+ is_routes = decoded.startswith(_MRAP_INSTANCES_PREFIX + "/") and decoded.endswith("/routes")+ if signed is not None:+ if is_routes and signed not in _MRAP_ROUTE_REGIONS:+ return _mrap_region_error(path, routes=True)+ if not is_routes and signed != _MRAP_MANAGEMENT_REGION:+ return _mrap_region_error(path, routes=False)++ if decoded.startswith(_MRAP_ASYNC_PREFIX):+ tail = decoded[len(_MRAP_ASYNC_PREFIX):]+ if method == "POST" and tail in _MRAP_ASYNC_OPERATIONS:+ return _mrap_async(tail, body, signed)+ if method == "GET":+ return _mrap_describe(tail)+ elif decoded.rstrip("/") == _MRAP_INSTANCES_PREFIX and method == "GET":+ return _mrap_list(query_params)+ elif decoded.startswith(_MRAP_INSTANCES_PREFIX + "/"):+ ref = decoded[len(_MRAP_INSTANCES_PREFIX) + 1:]+ if is_routes:+ ref = ref[: -len("/routes")]+ if not ref.startswith("arn:"):+ return s3control_error("InvalidRequest", "Request invalid", 400)+ record = find_mrap(ref)+ if record is None:+ return _no_such_mrap(ref.rsplit("/", 1)[-1])+ if method == "GET":+ return _mrap_get_routes(ref, record)+ if method == "PATCH":+ return _mrap_submit_routes(record, body)+ elif ref.endswith("/policy") and method == "GET":+ record = find_mrap(ref[: -len("/policy")])+ return _mrap_policy(record) if record else _no_such_mrap(ref[: -len("/policy")])+ elif method == "GET":+ record = find_mrap(ref)+ if record is None:+ return _no_such_mrap(ref)+ out = Element("GetMultiRegionAccessPointResult", xmlns=S3CONTROL_NS)+ _mrap_report_xml(out, record)+ return _s3control_response(out)+ return s3control_error("MethodNotAllowed", "The specified method is not allowed against this resource.", 405)++def reset():"""Wipe all in-memory state (used by /_ministack/reset)."""global _buckets, _bucket_policies, _bucket_notifications, _bucket_tags@@ -7975,6 +8585,7 @@ def reset():_object_legal_hold,_object_versions,_mraps,+ _mrap_operations,):d.clear()diff --git a/ministack/services/tagging.py b/ministack/services/tagging.pyindex 09dceb89..d171e03c 100644--- a/ministack/services/tagging.py+++ b/ministack/services/tagging.py@@ -80,8 +80,12 @@ def _normalise_ecs(tag_list):def _collect_s3():import ministack.services.s3 as svc+ region = get_region()for name, tags in svc._bucket_tags.items():- yield f"arn:aws:s3:::{name}", _normalise_flat(tags)+ # Bucket ARNs carry no region, but GetResources only lists buckets+ # homed in the region it is called in.+ if svc.bucket_region(name) == region:+ yield f"arn:aws:s3:::{name}", _normalise_flat(tags)def _collect_lambda():diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 84139cf6..6a12b7f1 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -14723,6 +14723,38 @@ def test_cfn_s3_multi_region_access_point(cfn, s3):assert ei.value.code in (403, 404)+def test_cfn_s3_mrap_visible_through_s3control(cfn, s3):+ """A stack-provisioned MRAP is the same record the S3 Control API reads,+ and its routes can fail traffic over like one created through S3 Control."""+ from conftest import patch_endpoint_dns++ uid = _uuid_mod.uuid4().hex[:8]+ stack_name, name = f"cfn-mrap-ctl-{uid}", f"cfn-mrap-ctl-{uid}"+ one, two = _mrap_buckets(s3, uid)+ template = json.dumps({+ "Resources": {"Mrap": {"Type": "AWS::S3::MultiRegionAccessPoint",+ "Properties": {"Name": name, "Regions": [{"Bucket": one}, {"Bucket": two}]}}},+ "Outputs": {"Alias": {"Value": {"Fn::GetAtt": ["Mrap", "Alias"]}}},+ })+ cfn.create_stack(StackName=stack_name, TemplateBody=template)+ ctl = boto3.client("s3control", endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),+ region_name="us-west-2", aws_access_key_id="test", aws_secret_access_key="test")+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ alias = _output(stack, "Alias")+ with patch_endpoint_dns():+ ap = ctl.get_multi_region_access_point(AccountId="000000000000", Name=name)["AccessPoint"]+ assert (ap["Alias"], [r["Bucket"] for r in ap["Regions"]]) == (alias, [one, two])+ assert _mrap_get(alias, "who.txt") == (200, one)+ ctl.submit_multi_region_access_point_routes(+ AccountId="000000000000", Mrap=f"arn:aws:s3::000000000000:accesspoint/{alias}",+ RouteUpdates=[{"Bucket": one, "TrafficDialPercentage": 0}])+ assert _mrap_get(alias, "who.txt") == (200, two)+ finally:+ _delete_cfn_test_stack(cfn, stack_name)++def test_s3_mrap_alias_matches_the_documented_pattern():# In-process: the generator alone. A digit-only draw was possible before# (uuid hex prefix), which is outside ^[a-z][a-z0-9]*[.]mrap$.@@ -19765,6 +19797,10 @@ def test_cfn_signer_signing_profile_platform_outside_the_schema_enum(cfn, signer"Validation failure detected. See the operation's FAILED event for details.", None),("ROLLBACK_COMPLETE", "", None),]+ errors = [e for e in cfn.describe_events(StackName=stack_name)["OperationEvents"]+ if e["EventType"] == "VALIDATION_ERROR"]+ assert sorted((e["LogicalResourceId"], e["ValidationPath"]) for e in errors) == [+ ("Bogus", "/Resources/Bogus/Properties/PlatformId"), ("Iot", "/Resources/Iot/Properties/PlatformId")]assert cfn.describe_stack_resources(StackName=stack_name)["StackResources"] == []with pytest.raises(ClientError):signer.get_signing_profile(profileName=stack_name.replace("-", "_"))@@ -36180,6 +36216,196 @@ def test_cfn_iam_user_generated_name(cfn, iam):_wait_stack(cfn, stack_name)[email protected]("resource", ["function", "layer"])+def test_cfn_lambda_s3_code_region(s3, resource):+ """S3 code in another region fails the resource with Lambda's message+ (observed on AWS 2026-10-12 through the Lambda API)."""+ uid = _uuid_mod.uuid4().hex[:8]+ bucket, stack_name = f"cfn-code-use1-{uid}", f"cfn-code-region-{uid}"+ s3.create_bucket(Bucket=bucket)+ s3.put_object(Bucket=bucket, Key="fn.zip", Body=b"PK\x05\x06" + b"\x00" * 18)+ euw1 = boto3.client("cloudformation", endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),+ region_name="eu-west-1", aws_access_key_id="test", aws_secret_access_key="test")+ if resource == "function":+ res = {"Type": "AWS::Lambda::Function", "Properties": {+ "Runtime": "python3.12", "Handler": "index.handler", "Role": _CR_LAMBDA_ROLE,+ "Code": {"S3Bucket": bucket, "S3Key": "fn.zip"}}}+ s3_part = ("The bucket you are attempting to access must be addressed using the specified endpoint. "+ "Please send all future requests to this endpoint.")+ else:+ res = {"Type": "AWS::Lambda::LayerVersion", "Properties": {+ "Content": {"S3Bucket": bucket, "S3Key": "fn.zip"}}}+ s3_part = "The bucket is in this region: us-east-1. Please use this region to retry the request"+ euw1.create_stack(StackName=stack_name, TemplateBody=json.dumps({"Resources": {"Code": res}}))+ try:+ stack = _wait_stack(euw1, stack_name)+ assert stack["StackStatus"] in ("ROLLBACK_COMPLETE", "CREATE_FAILED")+ assert ("Error occurred while GetObject. S3 Error Code: PermanentRedirect. S3 Error Message: "+ + s3_part) in _stack_event_reasons(euw1, stack_name)+ finally:+ _delete_cfn_test_stack(euw1, stack_name)+ s3.delete_object(Bucket=bucket, Key="fn.zip")+ s3.delete_bucket(Bucket=bucket)+++# ---------------------------------------------------------------------------+# AWS::S3::Bucket and the global bucket namespace (#2158)+# ---------------------------------------------------------------------------++_NAME_EXISTS = "Resource of type 'AWS::S3::Bucket' with identifier '{}' already exists."+++def foreign_bucket():+ """A bucket another account owns, placed straight into the in-process store."""+ from ministack.services import s3 as s3_svc++ name = f"cfn-foreign-{_uuid_mod.uuid4().hex[:8]}"+ s3_svc._buckets.set_scoped("111122223333", None, name, {"created": "", "objects": {}, "region": "us-east-1"})+ yield name+ s3_svc._buckets.pop_scoped("111122223333", None, name, None)+++def test_cfn_s3_bucket_other_account_name_is_refused(foreign_bucket, monkeypatch):+ from ministack.services import s3 as s3_svc+ from ministack.services.cloudformation import provisioners++ for adopt in (True, False):+ monkeypatch.setattr(provisioners, "CFN_S3_ADOPT_EXISTING_BUCKET", adopt)+ with pytest.raises(ValueError) as exc:+ provisioners._s3_create("B", {"BucketName": foreign_bucket}, "stack")+ assert str(exc.value) == _NAME_EXISTS.format(foreign_bucket)+ # Rename on update and recreate go through the same check.+ with pytest.raises(ValueError):+ provisioners._s3_update("old-name", {"BucketName": "old-name"}, {"BucketName": foreign_bucket}, "stack")+ assert s3_svc._buckets.get(foreign_bucket) is None+++def test_cfn_s3_bucket_adopt_existing_setting(monkeypatch):+ import contextvars++ from ministack.services import s3 as s3_svc+ from ministack.services.cloudformation import provisioners++ name = f"cfn-own-{_uuid_mod.uuid4().hex[:8]}"+ s3_svc._buckets[name] = {"created": "", "objects": {"k": {}}, "region": "us-east-1"}+ try:+ monkeypatch.setattr(provisioners, "CFN_S3_ADOPT_EXISTING_BUCKET", True)+ assert provisioners._s3_create("B", {"BucketName": name}, "stack")[0] == name+ assert s3_svc._buckets[name]["objects"] == {"k": {}}++ monkeypatch.setattr(provisioners, "CFN_S3_ADOPT_EXISTING_BUCKET", False)+ with pytest.raises(ValueError) as exc:+ provisioners._s3_create("B", {"BucketName": name}, "stack")+ assert str(exc.value) == _NAME_EXISTS.format(name)+ finally:+ s3_svc._buckets.pop(name, None)++ def create_auto_named():+ return provisioners._s3_create("Assets", {}, "seeded-stack")[0]++ created = []+ try:+ monkeypatch.setattr(provisioners, "CFN_S3_ADOPT_EXISTING_BUCKET", True)+ first, again = (contextvars.copy_context().run(create_auto_named) for _ in range(2))+ assert first == again # adoption keeps the deterministic name+ created.append(first)+ monkeypatch.setattr(provisioners, "CFN_S3_ADOPT_EXISTING_BUCKET", False)+ one, two = (contextvars.copy_context().run(create_auto_named) for _ in range(2))+ created += [one, two]+ assert len({first, one, two}) == 3 # a fresh name per stack instance+ assert one.startswith("seeded-stack-assets-")+ finally:+ for bucket in created:+ s3_svc._buckets.pop(bucket, None)+++_VALIDATION_FAILED_ONE = (+ "Validation failed with 1 error(s). Call DescribeEvents to retrieve the full list of issues with "+ "resource and property details, resolve each error, then retry the operation.")+++def other_account_bucket():+ other = boto3.client("s3", endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),+ region_name="us-east-1", aws_access_key_id="111122223333", aws_secret_access_key="test")+ name = f"cfn-taken-{_uuid_mod.uuid4().hex[:8]}"+ other.create_bucket(Bucket=name)+ yield name+ other.delete_bucket(Bucket=name)+++def _stack_level_events(cfn, stack_name):+ events = cfn.describe_stack_events(StackName=stack_name)["StackEvents"]+ return list(reversed(events))++[email protected]("disable_rollback", [False, True])+def test_cfn_s3_name_conflict_validation(cfn, other_account_bucket, disable_rollback):+ """A BucketName another account owns fails pre-deployment validation the+ way AWS reports it (observed 2026-10-12): stack events, no resource event,+ and the error itself through DescribeEvents."""+ stack_name = f"cfn-name-conflict-{_uuid_mod.uuid4().hex[:8]}"+ template = {"Resources": {"Bucket": {"Type": "AWS::S3::Bucket",+ "Properties": {"BucketName": other_account_bucket}}}}+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template), DisableRollback=disable_rollback)+ try:+ stack = _wait_stack(cfn, stack_name)+ events = _stack_level_events(cfn, stack_name)+ assert all(e["LogicalResourceId"] == stack_name for e in events)+ failed = [e for e in events if e["ResourceStatus"] == "CREATE_FAILED"]+ assert failed[0]["ResourceStatusReason"] == _VALIDATION_FAILED_ONE+ assert failed[0]["DetailedStatus"] == "VALIDATION_FAILED"+ if disable_rollback:+ assert stack["StackStatus"] == "CREATE_FAILED"+ assert [e["ResourceStatusReason"] for e in failed[1:]] == [+ "Validation failure detected. See the operation's FAILED event for details."]+ else:+ assert stack["StackStatus"] == "ROLLBACK_COMPLETE"++ ops = cfn.describe_events(StackName=stack_name)["OperationEvents"]+ errors = [e for e in ops if e["EventType"] == "VALIDATION_ERROR"]+ assert len(errors) == 1+ error = errors[0]+ assert (error["OperationType"], error["LogicalResourceId"], error["ResourceType"]) == (+ "CREATE_STACK", "Bucket", "AWS::S3::Bucket")+ assert (error["ValidationFailureMode"], error["ValidationName"], error["ValidationStatus"]) == (+ "FAIL", "NAME_CONFLICT_VALIDATION", "FAILED")+ assert error["ValidationStatusReason"] == _NAME_EXISTS.format(other_account_bucket)+ assert error["ValidationPath"] == "/Resources/Bucket"+ assert any(e["EventType"] == "PROVISIONING_ERROR" and e["LogicalResourceId"] == stack_name for e in ops)+ assert {e["OperationId"] for e in ops} == {error["OperationId"]}+ failed_only = cfn.describe_events(StackName=stack_name, Filters={"FailedEvents": True})["OperationEvents"]+ assert error["EventId"] in {e["EventId"] for e in failed_only}+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+++def test_cfn_s3_name_conflict_own_bucket_when_adoption_is_off(monkeypatch):+ """In-process: with CFN_S3_ADOPT_EXISTING_BUCKET=0, an own existing name+ is a NAME_CONFLICT_VALIDATION error too."""+ from ministack.services import s3 as s3_svc+ from ministack.services.cloudformation import _stack_events, provisioners, stacks++ name = f"cfn-own-conflict-{_uuid_mod.uuid4().hex[:8]}"+ s3_svc._buckets[name] = {"created": "", "objects": {}, "region": "us-east-1"}+ stack_id = f"arn:aws:cloudformation:us-east-1:000000000000:stack/own-conflict/{name}"+ resources = {"B": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": name}}}+ stack = {"StackId": stack_id, "StackName": "own-conflict"}+ try:+ monkeypatch.setattr(provisioners, "CFN_S3_ADOPT_EXISTING_BUCKET", True)+ assert not stacks._fail_property_validation(stack, stack_id, "own-conflict", resources, ["B"], {}, {}, {},+ True)+ monkeypatch.setattr(provisioners, "CFN_S3_ADOPT_EXISTING_BUCKET", False)+ assert stacks._fail_property_validation(stack, stack_id, "own-conflict", resources, ["B"], {}, {}, {}, True)+ assert stack["StackStatus"] == "CREATE_FAILED"+ [error] = [e for e in stack["_operation_events"] if e["EventType"] == "VALIDATION_ERROR"]+ assert error["ValidationStatusReason"] == _NAME_EXISTS.format(name)+ finally:+ s3_svc._buckets.pop(name, None)+ _stack_events.pop(stack_id, None)++@pytest.mark.parametrize("custom_bus", [True, False])def test_cfn_events_rule_bus_arn_delivery_and_lifecycle(cfn, eb, sqs, custom_bus):"""ARN/name aliases share a rule on create, update, delivery, drift and delete."""diff --git a/tests/test_firehose.py b/tests/test_firehose.pyindex ed036389..bc7b0413 100644--- a/tests/test_firehose.py+++ b/tests/test_firehose.py@@ -1075,3 +1075,27 @@ def test_firehose_partition_keys_from_lambda(fh, s3, lam):finally:fh.delete_delivery_stream(DeliveryStreamName=name)lam.delete_function(FunctionName=fn)+++def test_firehose_region_delivery_into_regional_bucket():+ """A stream in eu-west-1 delivers into an eu-west-1 bucket; the internal+ S3 write is unsigned, so the bucket home-region check doesn't apply."""+ suffix = _uuid_mod.uuid4().hex[:8]+ bucket, name = f"fh-euw1-{suffix}", f"fh-euw1-{suffix}"+ fh, s3 = _regional_client("firehose", "eu-west-1"), _regional_client("s3", "eu-west-1")+ s3.create_bucket(Bucket=bucket, CreateBucketConfiguration={"LocationConstraint": "eu-west-1"})+ fh.create_delivery_stream(DeliveryStreamName=name, DeliveryStreamType="DirectPut",+ ExtendedS3DestinationConfiguration={+ "RoleARN": "arn:aws:iam::000000000000:role/firehose",+ "BucketARN": f"arn:aws:s3:::{bucket}", "Prefix": "out/",+ "BufferingHints": {"SizeInMBs": 1, "IntervalInSeconds": 1}})+ try:+ fh.put_record(DeliveryStreamName=name, Record={"Data": b"regional"})+ objs = _wait_objects(s3, bucket, "out/")+ assert len(objs) == 1, objs+ assert s3.get_object(Bucket=bucket, Key=objs[0]["Key"])["Body"].read() == b"regional"+ finally:+ fh.delete_delivery_stream(DeliveryStreamName=name)+ for obj in s3.list_objects_v2(Bucket=bucket).get("Contents", []):+ s3.delete_object(Bucket=bucket, Key=obj["Key"])+ s3.delete_bucket(Bucket=bucket)diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex e2fe38a2..40a3930b 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -5612,6 +5612,63 @@ def test_stage_policy_is_enforced_on_dispatch(monkeypatch, prefix, suffix, case,assert f"apigateway:{method}" in json.loads(body)["message"][email protected]("method,path,action", [+ ("POST", "/v20180820/async-requests/mrap/create", "s3:CreateMultiRegionAccessPoint"),+ ("POST", "/v20180820/async-requests/mrap/delete", "s3:DeleteMultiRegionAccessPoint"),+ ("POST", "/v20180820/async-requests/mrap/put-policy", "s3:PutMultiRegionAccessPointPolicy"),+ ("GET", "/v20180820/async-requests/mrap/arn%3Aaws%3As3%3Aus-west-2%3A000000000000%3Aasync-request/mrap/create/t",+ "s3:DescribeMultiRegionAccessPointOperation"),+ ("GET", "/v20180820/mrap/instances", "s3:ListMultiRegionAccessPoints"),+ ("GET", "/v20180820/mrap/instances/m1", "s3:GetMultiRegionAccessPoint"),+ ("GET", "/v20180820/mrap/instances/m1/policy", "s3:GetMultiRegionAccessPointPolicy"),+ ("GET", "/v20180820/mrap/instances/arn%3Aaws%3As3%3A%3A000000000000%3Aaccesspoint/a.mrap/routes",+ "s3:GetMultiRegionAccessPointRoutes"),+ ("PATCH", "/v20180820/mrap/instances/arn%3Aaws%3As3%3A%3A000000000000%3Aaccesspoint/a.mrap/routes",+ "s3:SubmitMultiRegionAccessPointRoutes"),+])+def test_s3control_mrap_iam_action(method, path, action):+ from ministack.core.iam_actions import s3control_action++ assert s3control_action(method, path) == action+++def test_s3control_mrap_denied_without_the_action(monkeypatch):+ """Under AUTH=true an S3 Control MRAP call needs its own IAM action."""+ import ministack.app as app+ from ministack.services import iam as iam_svc++ fake_key = "AKIATESTMRAPCTL0001"+ iam_svc._access_keys[fake_key] = {+ "UserName": "mrap-user", "AccessKeyId": fake_key,+ "SecretAccessKey": "s", "Status": "Active", "CreateDate": "2024-01-01",+ }+ iam_svc._users["mrap-user"] = {+ "UserName": "mrap-user", "Arn": "arn:aws:iam::000000000000:user/mrap-user",+ "UserId": "AIDAMRAP1", "CreateDate": "2024-01-01", "Path": "/",+ "AttachedPolicies": [], "Tags": [],+ }+ iam_svc._user_inline_policies["mrap-user"] = {"p": json.dumps({"Statement": [{+ "Effect": "Allow", "Action": "s3:ListMultiRegionAccessPoints", "Resource": "*"}]})}+ monkeypatch.setattr(app, "AUTH", True)+ headers = {+ "authorization": f"AWS4-HMAC-SHA256 Credential={fake_key}/20261012/us-west-2/s3/aws4_request, "+ "SignedHeaders=host, Signature=deadbeef",+ "x-amz-account-id": "000000000000",+ }+ try:+ listed = asyncio.run(app._handle_s3_control_request(+ "/v20180820/mrap/instances", "GET", b"", {}, "rid", headers))+ denied = asyncio.run(app._handle_s3_control_request(+ "/v20180820/mrap/instances/nope", "GET", b"", {}, "rid", headers))+ finally:+ iam_svc._access_keys.pop(fake_key, None)+ iam_svc._users.pop("mrap-user", None)+ iam_svc._user_inline_policies.pop("mrap-user", None)+ assert listed[0] == 200+ assert denied[0] == 403+ assert b"s3:GetMultiRegionAccessPoint" in denied[2]++@pytest.mark.parametrize("addressing", ["path", "virtual"])def test_s3_list_grants_scoped_by_prefix_condition(monkeypatch, addressing):"""s3:prefix, s3:delimiter and s3:max-keys come from a ListBucket or ListBucketVersions request."""diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex ed4043a4..6ffa1f61 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -14911,3 +14911,64 @@ exports.handler = async () => {assert json.loads(payload) == {"ok": True}expected_logs = ["invoke-console-message", "invoke-stderr-message"]assert base64.b64decode(headers["X-Amz-Log-Result"]).decode().splitlines() == expected_logs+++def _regional(service, region):+ return boto3.client(service, endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),+ region_name=region, aws_access_key_id="test", aws_secret_access_key="test")+++_S3_CODE_REDIRECT = ("Error occurred while GetObject. S3 Error Code: PermanentRedirect. S3 Error Message: "+ "The bucket you are attempting to access must be addressed using the specified endpoint. "+ "Please send all future requests to this endpoint.")+++def use1_code_bucket(s3):+ bucket = f"code-use1-{_uuid_mod.uuid4().hex[:8]}"+ s3.create_bucket(Bucket=bucket)+ s3.put_object(Bucket=bucket, Key="fn.zip", Body=_make_zip("def handler(e, c):\n return 1\n"))+ yield bucket+ s3.delete_object(Bucket=bucket, Key="fn.zip")+ s3.delete_bucket(Bucket=bucket)+++def test_lambda_s3_code_region_create_and_update(lam, use1_code_bucket):+ """S3 code must come from a bucket in the function's region (observed on+ AWS 2026-10-12: eu-west-1 function, us-east-1 bucket)."""+ euw1 = _regional("lambda", "eu-west-1")+ name = f"s3-code-region-{_uuid_mod.uuid4().hex[:8]}"+ with pytest.raises(ClientError) as exc:+ euw1.create_function(FunctionName=name, Runtime="python3.12", Role=_LAMBDA_ROLE, Handler="index.handler",+ Code={"S3Bucket": use1_code_bucket, "S3Key": "fn.zip"})+ assert exc.value.response["Error"]["Code"] == "InvalidParameterValueException"+ assert exc.value.response["Error"]["Message"] == _S3_CODE_REDIRECT+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400++ euw1.create_function(FunctionName=name, Runtime="python3.12", Role=_LAMBDA_ROLE, Handler="index.handler",+ Code={"ZipFile": _make_zip("def handler(e, c):\n return 0\n")})+ try:+ with pytest.raises(ClientError) as exc:+ euw1.update_function_code(FunctionName=name, S3Bucket=use1_code_bucket, S3Key="fn.zip")+ assert exc.value.response["Error"]["Message"] == _S3_CODE_REDIRECT+ # A same-region bucket still works.+ lam.create_function(FunctionName=f"{name}-use1", Runtime="python3.12", Role=_LAMBDA_ROLE,+ Handler="index.handler", Code={"S3Bucket": use1_code_bucket, "S3Key": "fn.zip"})+ lam.delete_function(FunctionName=f"{name}-use1")+ finally:+ euw1.delete_function(FunctionName=name)+++def test_lambda_s3_code_region_publish_layer_version(use1_code_bucket):+ euw1 = _regional("lambda", "eu-west-1")+ layer = f"s3-code-region-{_uuid_mod.uuid4().hex[:8]}"+ with pytest.raises(ClientError) as exc:+ euw1.publish_layer_version(LayerName=layer, Content={"S3Bucket": use1_code_bucket, "S3Key": "fn.zip"})+ assert exc.value.response["Error"]["Code"] == "InvalidParameterValueException"+ assert exc.value.response["Error"]["Message"] == (+ "Error occurred while GetObject. S3 Error Code: PermanentRedirect. S3 Error Message: "+ "The bucket is in this region: us-east-1. Please use this region to retry the request")+ # The refused publish didn't consume a version number.+ published = euw1.publish_layer_version(LayerName=layer, Content={"ZipFile": _make_zip("x = 1\n")})+ assert published["Version"] == 1+ euw1.delete_layer_version(LayerName=layer, VersionNumber=1)diff --git a/tests/test_router.py b/tests/test_router.pyindex 721c3645..61fa95ab 100644--- a/tests/test_router.py+++ b/tests/test_router.py@@ -585,3 +585,54 @@ def test_cfn_signal_prefix_matches_wait_conditions():from ministack.services.cloudformation import wait_conditionsassert wait_conditions.SIGNAL_PATH == "/_ministack/cfn-signal/"+++_SIGV4_AUTH = (+ "AWS4-HMAC-SHA256 Credential=AKID/20261012/{region}/s3/aws4_request, "+ "SignedHeaders=host, Signature=abc"+)+_SIGV4A_AUTH = (+ "AWS4-ECDSA-P256-SHA256 Credential=AKID/20261012/s3/aws4_request, "+ "SignedHeaders=host;x-amz-region-set, Signature=abc"+)++[email protected]("headers,query,expected", [+ ({"authorization": _SIGV4_AUTH.format(region="eu-west-1")}, None, "eu-west-1"),+ ({}, {"X-Amz-Algorithm": ["AWS4-HMAC-SHA256"],+ "X-Amz-Credential": ["AKID/20261012/ap-south-1/s3/aws4_request"]}, "ap-south-1"),+ ({}, {"X-Amz-Credential": ["AKID/20261012/us-west-2/appsync/aws4_request"]}, "us-west-2"),+ ({}, {"X-Amz-Credential": ["AKID/20261012/s3/aws4_request"]}, None),+ ({"authorization": _SIGV4A_AUTH, "x-amz-region-set": "eu-west-1"}, None, "eu-west-1"),+ ({"authorization": _SIGV4A_AUTH, "x-amz-region-set": "*"}, None, None),+ ({"authorization": _SIGV4A_AUTH, "x-amz-region-set": "us-east-1,eu-west-1"}, None, None),+ ({"authorization": _SIGV4A_AUTH}, None, None),+ ({}, {"X-Amz-Algorithm": ["AWS4-ECDSA-P256-SHA256"],+ "X-Amz-Credential": ["AKID/20261012/s3/aws4_request"],+ "X-Amz-Region-Set": ["us-west-2"]}, "us-west-2"),+ ({}, {"X-Amz-Algorithm": ["AWS4-ECDSA-P256-SHA256"],+ "X-Amz-Credential": ["AKID/20261012/s3/aws4_request"],+ "X-Amz-Region-Set": ["*"]}, None),+ ({"authorization": "AWS AKID:signature"}, None, None),+ ({}, {"AWSAccessKeyId": ["AKID"], "Signature": ["x"]}, None),+ ({}, None, None),+ ({"authorization": "AWS4-HMAC-SHA256 Credential=AKID/20261012/s3/aws4_request"}, None, None),+])+def test_extract_signed_region(headers, query, expected):+ from ministack.core.router import extract_signed_region++ assert extract_signed_region(headers, query) == expected+++def test_extract_region_never_returns_the_service_for_sigv4a(monkeypatch):+ """A SigV4a scope has no region segment; it used to yield region "s3"."""+ from ministack.core.router import extract_region++ monkeypatch.delenv("MINISTACK_REGION", raising=False)+ assert extract_region({"authorization": _SIGV4A_AUTH, "x-amz-region-set": "*"}) == "us-east-1"+ query = {"X-Amz-Algorithm": ["AWS4-ECDSA-P256-SHA256"],+ "X-Amz-Credential": ["AKID/20261012/s3/aws4_request"]}+ assert extract_region({}, query) == "us-east-1"+ monkeypatch.setenv("MINISTACK_REGION", "eu-central-1")+ assert extract_region({}, query) == "eu-central-1"+ assert extract_region({"authorization": _SIGV4_AUTH.format(region="sa-east-1")}) == "sa-east-1"diff --git a/tests/test_s3.py b/tests/test_s3.pyindex 0c03f58c..15786817 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -829,28 +829,96 @@ def test_s3_get_bucket_location_us_east_1_is_none(s3):loc = s3.get_bucket_location(Bucket=bkt)assert loc["LocationConstraint"] is None-def test_s3_get_bucket_location_defaults_to_signing_region(s3):- """A bucket created WITHOUT CreateBucketConfiguration lands in the region- the request was signed for — GetBucketLocation must echo that region."""- import boto3- from botocore.config import Config+def _create_bucket_error(client, **kwargs):+ with pytest.raises(ClientError) as exc:+ client.create_bucket(**kwargs)+ return exc.value.response- west_s3 = boto3.client(- "s3",- endpoint_url=ENDPOINT,- aws_access_key_id="test",- aws_secret_access_key="test",- region_name="eu-west-1",- config=Config(- region_name="eu-west-1",- retries={"mode": "standard"},- max_pool_connections=50,- ),- )++def test_s3_location_constraint_required_outside_us_east_1(s3):+ """A regional endpoint other than us-east-1 refuses CreateBucket without a+ LocationConstraint naming its own region (observed on AWS 2026-10-12)."""+ euw1 = _regional_client("s3", "eu-west-1")bkt = f"intg-s3-loc-signing-{_uuid_mod.uuid4().hex[:8]}"- west_s3.create_bucket(Bucket=bkt)- loc = west_s3.get_bucket_location(Bucket=bkt)- assert loc["LocationConstraint"] == "eu-west-1"+ resp = _create_bucket_error(euw1, Bucket=bkt)+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 400+ assert resp["Error"]["Code"] == "IllegalLocationConstraintException"+ assert resp["Error"]["Message"] == ("The unspecified location constraint is incompatible for the "+ "region specific endpoint this request was sent to.")++ resp = _create_bucket_error(euw1, Bucket=bkt, CreateBucketConfiguration={"LocationConstraint": "us-west-2"})+ assert resp["Error"]["Code"] == "IllegalLocationConstraintException"+ assert resp["Error"]["Message"] == ("The us-west-2 location constraint is incompatible for the "+ "region specific endpoint this request was sent to.")+ with pytest.raises(ClientError):+ s3.head_bucket(Bucket=bkt)++ euw1.create_bucket(Bucket=bkt, CreateBucketConfiguration={"LocationConstraint": "eu-west-1"})+ try:+ assert euw1.get_bucket_location(Bucket=bkt)["LocationConstraint"] == "eu-west-1"+ # The constraint check precedes BucketAlreadyOwnedByYou.+ resp = _create_bucket_error(euw1, Bucket=bkt)+ assert resp["Error"]["Code"] == "IllegalLocationConstraintException"+ resp = _create_bucket_error(euw1, Bucket=bkt, CreateBucketConfiguration={"LocationConstraint": "eu-west-1"})+ assert resp["Error"]["Code"] == "BucketAlreadyOwnedByYou"+ assert resp["Error"]["BucketName"] == bkt+ finally:+ euw1.delete_bucket(Bucket=bkt)+++def test_s3_location_constraint_us_east_1_is_invalid(s3):+ bkt = f"intg-s3-loc-use1-{_uuid_mod.uuid4().hex[:8]}"+ for client in (s3, _regional_client("s3", "eu-west-1")):+ resp = _create_bucket_error(client, Bucket=bkt, CreateBucketConfiguration={"LocationConstraint": "us-east-1"})+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 400+ assert resp["Error"]["Code"] == "InvalidLocationConstraint"+ assert resp["Error"]["Message"] == "The specified location-constraint is not valid"+ assert resp["Error"]["LocationConstraint"] == "us-east-1"+++def test_s3_location_constraint_internal_callers_unchanged():+ """Internal callers (Glue warehouse, Transcribe) pass no endpoint region and+ keep landing the bucket in the request region without a constraint."""+ import contextvars++ from ministack.core.responses import set_request_region+ from ministack.services import s3 as s3_svc++ name = f"intg-s3-loc-internal-{_uuid_mod.uuid4().hex[:8]}"++ def create_in_eu_west_1():+ set_request_region("eu-west-1")+ try:+ assert s3_svc._create_bucket(name, b"", {})[0] == 200+ assert s3_svc.bucket_region(name) == "eu-west-1"+ finally:+ s3_svc._buckets.pop(name, None)++ contextvars.copy_context().run(create_in_eu_west_1)+++def test_s3_location_constraint_bucket_already_exists_names_bucket(s3):+ import boto3++ other = boto3.client("s3", endpoint_url=ENDPOINT, region_name="us-east-1",+ aws_access_key_id="111122223333", aws_secret_access_key="test")+ bkt = f"intg-s3-loc-taken-{_uuid_mod.uuid4().hex[:8]}"+ s3.create_bucket(Bucket=bkt)+ try:+ resp = _create_bucket_error(other, Bucket=bkt)+ assert resp["Error"]["Code"] == "BucketAlreadyExists"+ assert resp["Error"]["BucketName"] == bkt+ finally:+ s3.delete_bucket(Bucket=bkt)+++def test_s3_location_constraint_us_east_1_endpoint_accepts_any_region(s3):+ bkt = f"intg-s3-loc-any-{_uuid_mod.uuid4().hex[:8]}"+ s3.create_bucket(Bucket=bkt, CreateBucketConfiguration={"LocationConstraint": "ap-southeast-2"})+ try:+ assert s3.get_bucket_location(Bucket=bkt)["LocationConstraint"] == "ap-southeast-2"+ finally:+ _regional_client("s3", "ap-southeast-2").delete_bucket(Bucket=bkt)def test_s3_create_bucket_without_tags_has_no_tag_set(s3):"""A CreateBucket with no tags must not create an empty tag set — a@@ -7036,11 +7104,13 @@ 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 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."""+ no virtual-host rule. It now lands on the existing vhost path. AWS routes+ by network proximity, not by the signing region (observed 2026-10-12:+ us-east-1 and eu-west-1 clients in one location were served by the same+ member), so MiniStack serves the member homed in its own MINISTACK_REGION+ (us-east-1 for the test server) whatever region the request names. 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-1s3.create_bucket(Bucket=eu_bucket, CreateBucketConfiguration={@@ -7049,8 +7119,8 @@ def test_s3_mrap_alias_serves_the_region_member(cfn, s3):"AWSTemplateFormatVersion": "2010-09-09","Resources": {"Mrap": {"Type": "AWS::S3::MultiRegionAccessPoint","Properties": {"Name": "serve-mrap-app",- "Regions": [{"Bucket": us_bucket},- {"Bucket": eu_bucket}]}}},+ "Regions": [{"Bucket": eu_bucket},+ {"Bucket": us_bucket}]}}},"Outputs": {"Alias": {"Value": {"Fn::GetAtt": ["Mrap", "Alias"]}}},})cfn.create_stack(StackName="cfn-s3-mrap-serve", TemplateBody=template)@@ -7062,15 +7132,10 @@ def test_s3_mrap_alias_serves_the_region_member(cfn, s3):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+ # eu-west-1 is listed first, so serving the us-east-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")+ for region in ("eu-west-1", "us-east-1", "ap-south-1", None):+ assert _mrap_get(alias, "who.txt", region=region) == (200, "US BUCKET")finally:cfn.delete_stack(StackName="cfn-s3-mrap-serve")_wait_stack(cfn, "cfn-s3-mrap-serve")@@ -8155,8 +8220,696 @@ def test_s3_create_owned_bucket_again(s3):with pytest.raises(ClientError) as exc:s3.create_bucket(Bucket=west, CreateBucketConfiguration={"LocationConstraint": "us-west-2"})assert exc.value.response["Error"]["Code"] == "BucketAlreadyOwnedByYou"- assert exc.value.response["Error"]["Message"] == "The bucket you tried to create already exists, and you own it."+ assert exc.value.response["Error"]["Message"] == (+ "Your previous request to create the named bucket succeeded and you already own it.")+ assert exc.value.response["Error"]["BucketName"] == westassert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409finally:s3.delete_bucket(Bucket=east)s3.delete_bucket(Bucket=west)+++# ---------------------------------------------------------------------------+# Bucket home region (#2158)+# ---------------------------------------------------------------------------++[email protected]("headers,query,expected", [+ ({"authorization": "AWS4-HMAC-SHA256 Credential=AKID/20261012/eu-west-1/s3/aws4_request, "+ "SignedHeaders=host, Signature=abc"}, {}, "eu-west-1"),+ ({}, {"X-Amz-Algorithm": ["AWS4-HMAC-SHA256"],+ "X-Amz-Credential": ["AKID/20261012/us-west-2/s3/aws4_request"]}, "us-west-2"),+ ({"authorization": "AWS4-HMAC-SHA256 Credential=AKID/20261012/eu-west-1/sqs/aws4_request, "+ "SignedHeaders=host, Signature=abc"}, {}, None),+ ({"authorization": "AWS4-ECDSA-P256-SHA256 Credential=AKID/20261012/s3/aws4_request, "+ "SignedHeaders=host, Signature=abc", "x-amz-region-set": "eu-west-1"}, {}, None),+ ({"authorization": "AWS AKID:sig"}, {}, None),+ ({}, {}, None),+ ({"authorization": "AWS4-HMAC-SHA256 Credential=broken"}, {}, None),+])+def test_s3_signed_region(headers, query, expected):+ from ministack.services import s3 as s3_svc++ assert s3_svc._signed_region(headers, query) == expected+++def test_s3_error_extra_elements_and_headers():+ from xml.etree.ElementTree import fromstring++ from ministack.services import s3 as s3_svc++ status, headers, body = s3_svc._error("Plain", "msg", 400, "/b")+ assert status == 400 and headers == {"Content-Type": "application/xml"}+ assert [c.tag for c in fromstring(body)] == ["Code", "Message", "Resource", "RequestId"]++ status, headers, body = s3_svc._error(+ "PermanentRedirect", "moved", 301, "/b",+ extra={"Endpoint": "b.s3-eu-west-1.amazonaws.com", "Bucket": "b"},+ headers={"x-amz-bucket-region": "eu-west-1"},+ )+ root = fromstring(body)+ assert status == 301+ assert headers == {"Content-Type": "application/xml", "x-amz-bucket-region": "eu-west-1"}+ assert [c.tag for c in root] == ["Code", "Message", "Resource", "Endpoint", "Bucket", "RequestId"]+ assert root.findtext("Endpoint") == "b.s3-eu-west-1.amazonaws.com"+++def test_s3_list_buckets_region_filter(s3):+ tag = _uuid_mod.uuid4().hex[:8]+ east = [f"lbr-{tag}-e{i}" for i in range(2)]+ west = [f"lbr-{tag}-w{i}" for i in range(3)]+ for name in east:+ s3.create_bucket(Bucket=name)+ for name in west:+ s3.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": "eu-west-1"})+ euw1 = _regional_client("s3", "eu-west-1")+ prefix = f"lbr-{tag}-"+ try:+ listed = euw1.list_buckets(Prefix=prefix, BucketRegion="eu-west-1")["Buckets"]+ assert [b["Name"] for b in listed] == west+ assert {b["BucketRegion"] for b in listed} == {"eu-west-1"}++ listed = s3.list_buckets(Prefix=prefix, BucketRegion="us-east-1")["Buckets"]+ assert [b["Name"] for b in listed] == east++ # Pagination stays within the filter.+ names, token = [], None+ while True:+ kwargs = {"Prefix": prefix, "BucketRegion": "eu-west-1", "MaxBuckets": 1}+ if token:+ kwargs["ContinuationToken"] = token+ page = euw1.list_buckets(**kwargs)+ names += [b["Name"] for b in page["Buckets"]]+ token = page.get("ContinuationToken")+ if not token:+ break+ assert names == west++ # No filter lists every region.+ listed = euw1.list_buckets(Prefix=prefix)["Buckets"]+ assert [b["Name"] for b in listed] == sorted(east + west)+ finally:+ for name in east:+ s3.delete_bucket(Bucket=name)+ for name in west:+ euw1.delete_bucket(Bucket=name)+++def test_s3_list_buckets_region_filter_must_match_endpoint(s3):+ with pytest.raises(ClientError) as exc:+ s3.list_buckets(BucketRegion="eu-west-1")+ err = exc.value.response["Error"]+ assert err["Code"] == "InvalidArgument"+ assert err["Message"] == ("Requests with bucket-region specified must be made to the "+ "corresponding regional endpoint")+ assert err["ArgumentName"] == "bucket-region"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+++def _raw_signed(method, path, region, host=None, presign=False, body=b""):+ """Send a SigV4-signed S3 request without any client-side redirect+ handling. ``host`` overrides the Host header (signed as sent)."""+ import http.client++ from botocore.auth import S3SigV4Auth, S3SigV4QueryAuth+ from botocore.awsrequest import AWSRequest+ from botocore.credentials import Credentials++ parsed = urlparse(ENDPOINT)+ netloc = host or parsed.netloc+ req = AWSRequest(method=method, url=f"http://{netloc}{path}", data=body)+ creds = Credentials("test", "test")+ if presign:+ S3SigV4QueryAuth(creds, "s3", region, expires=300).add_auth(req)+ else:+ req.headers["x-amz-content-sha256"] = hashlib.sha256(body).hexdigest()+ S3SigV4Auth(creds, "s3", region).add_auth(req)+ target = urlparse(req.url)+ conn = http.client.HTTPConnection(parsed.hostname, parsed.port or 80, timeout=30)+ headers = {k: v for k, v in req.headers.items()}+ headers["Host"] = netloc+ conn.request(method, target.path + (f"?{target.query}" if target.query else ""), body=body or None,+ headers=headers)+ resp = conn.getresponse()+ data = resp.read()+ conn.close()+ return resp.status, {k.lower(): v for k, v in resp.getheaders()}, data+++def _xml_error(body):+ from xml.etree.ElementTree import fromstring++ root = fromstring(body)+ return {child.tag: child.text for child in root}+++def euw1_bucket(s3):+ name = f"home-euw1-{_uuid_mod.uuid4().hex[:8]}"+ s3.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": "eu-west-1"})+ euw1 = _regional_client("s3", "eu-west-1")+ euw1.put_object(Bucket=name, Key="k.txt", Body=b"hello")+ yield name+ for obj in euw1.list_objects_v2(Bucket=name).get("Contents", []):+ euw1.delete_object(Bucket=name, Key=obj["Key"])+ euw1.delete_bucket(Bucket=name)+++_REDIRECT_MSG = ("The bucket you are attempting to access must be addressed using the specified "+ "endpoint. Please send all future requests to this endpoint.")+++def test_s3_wrong_region_get_is_permanent_redirect(euw1_bucket):+ for presign in (False, True):+ status, headers, body = _raw_signed("GET", f"/{euw1_bucket}/k.txt", "us-west-2", presign=presign)+ assert status == 301, body+ assert headers["x-amz-bucket-region"] == "eu-west-1"+ err = _xml_error(body)+ assert err["Code"] == "PermanentRedirect"+ assert err["Message"] == _REDIRECT_MSG+ assert err["Endpoint"] == f"{euw1_bucket}.s3-eu-west-1.amazonaws.com"+ assert err["Bucket"] == euw1_bucket++ # A us-east-1 client on the global host is pointed at the global endpoint.+ status, headers, body = _raw_signed("PUT", f"/{euw1_bucket}/new.txt", "us-east-1", body=b"x")+ assert status == 301+ assert _xml_error(body)["Endpoint"] == f"{euw1_bucket}.s3.amazonaws.com"+ assert headers["x-amz-bucket-region"] == "eu-west-1"+++def test_s3_wrong_region_head_is_bodiless_redirect(euw1_bucket):+ for path in (f"/{euw1_bucket}", f"/{euw1_bucket}/k.txt"):+ status, headers, body = _raw_signed("HEAD", path, "us-east-1")+ assert (status, body) == (301, b"")+ assert headers["x-amz-bucket-region"] == "eu-west-1"+++def test_s3_wrong_region_at_home_endpoint_is_authorization_error(euw1_bucket):+ host = f"s3.eu-west-1.{urlparse(ENDPOINT).netloc}"+ status, headers, body = _raw_signed("GET", f"/{euw1_bucket}/k.txt", "us-east-1", host=host)+ assert status == 400+ err = _xml_error(body)+ assert err["Code"] == "AuthorizationHeaderMalformed"+ assert err["Message"] == ("The authorization header is malformed; the region 'us-east-1' is wrong; "+ "expecting 'eu-west-1'")+ assert err["Region"] == "eu-west-1"+ assert "x-amz-bucket-region" not in headers++ vhost = f"{euw1_bucket}.s3.eu-west-1.{urlparse(ENDPOINT).netloc}"+ status, headers, body = _raw_signed("GET", "/k.txt", "us-east-1", host=vhost, presign=True)+ assert status == 400+ err = _xml_error(body)+ assert err["Code"] == "AuthorizationQueryParametersError"+ assert err["Message"] == ("Error parsing the X-Amz-Credential parameter; the region 'us-east-1' is "+ "wrong; expecting 'eu-west-1'")+ assert err["Region"] == "eu-west-1"++ status, headers, body = _raw_signed("HEAD", f"/{euw1_bucket}", "us-east-1", host=host)+ assert (status, body) == (400, b"")+ assert headers["x-amz-bucket-region"] == "eu-west-1"+ status, headers, body = _raw_signed("HEAD", f"/{euw1_bucket}/k.txt", "us-east-1", host=host)+ assert (status, body) == (400, b"")+ assert "x-amz-bucket-region" not in headers+++def test_s3_wrong_region_exemptions_and_match(euw1_bucket):+ status, _, body = _raw_signed("GET", f"/{euw1_bucket}?location", "us-east-1")+ assert status == 200 and b"eu-west-1" in body+ status, _, body = _raw_signed("GET", "/", "ap-south-1")+ assert status == 200 and euw1_bucket.encode() in body+ status, _, body = _raw_signed("GET", f"/{euw1_bucket}/k.txt", "eu-west-1")+ assert (status, body) == (200, b"hello")+ status, _, _ = _raw_signed("GET", f"/no-such-{euw1_bucket}/k.txt", "us-west-2")+ assert status == 404+++def test_s3_unsigned_region_request_is_not_redirected(euw1_bucket):+ """Anonymous requests carry no signing region, so a public-read object in+ eu-west-1 answers 200 wherever the request lands."""+ import urllib.request++ _regional_client("s3", "eu-west-1").put_object(Bucket=euw1_bucket, Key="public.txt", Body=b"open",+ ACL="public-read")+ with urllib.request.urlopen(f"{ENDPOINT}/{euw1_bucket}/public.txt") as resp:+ assert (resp.status, resp.read()) == (200, b"open")+++def test_s3_cross_region_boto3_follows_redirect(s3):+ """boto3 configured for us-east-1 reaches a us-west-2 bucket through the+ PermanentRedirect + x-amz-bucket-region it gets back."""+ name = f"redir-usw2-{_uuid_mod.uuid4().hex[:8]}"+ usw2 = _regional_client("s3", "us-west-2")+ usw2.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": "us-west-2"})+ try:+ s3.put_object(Bucket=name, Key="a.txt", Body=b"redirected")+ assert s3.get_object(Bucket=name, Key="a.txt")["Body"].read() == b"redirected"+ assert [o["Key"] for o in s3.list_objects_v2(Bucket=name)["Contents"]] == ["a.txt"]+ assert s3.head_bucket(Bucket=name)["ResponseMetadata"]["HTTPHeaders"]["x-amz-bucket-region"] == "us-west-2"+ assert s3.head_object(Bucket=name, Key="a.txt")["ContentLength"] == 10+ s3.delete_object(Bucket=name, Key="a.txt")+ assert usw2.list_objects_v2(Bucket=name)["KeyCount"] == 0+ finally:+ usw2.delete_bucket(Bucket=name)+++def test_s3_cross_region_copy_and_upload_part_copy(s3):+ tag = _uuid_mod.uuid4().hex[:8]+ src, dst = f"copy-src-usw2-{tag}", f"copy-dst-euw1-{tag}"+ usw2, euw1 = _regional_client("s3", "us-west-2"), _regional_client("s3", "eu-west-1")+ usw2.create_bucket(Bucket=src, CreateBucketConfiguration={"LocationConstraint": "us-west-2"})+ euw1.create_bucket(Bucket=dst, CreateBucketConfiguration={"LocationConstraint": "eu-west-1"})+ part = b"p" * (5 * 1024 * 1024)+ try:+ usw2.put_object(Bucket=src, Key="obj", Body=b"copy me")+ usw2.put_object(Bucket=src, Key="big", Body=part)+ euw1.copy_object(Bucket=dst, Key="copied", CopySource={"Bucket": src, "Key": "obj"})+ assert euw1.get_object(Bucket=dst, Key="copied")["Body"].read() == b"copy me"++ upload = euw1.create_multipart_upload(Bucket=dst, Key="multi")+ etag = euw1.upload_part_copy(Bucket=dst, Key="multi", UploadId=upload["UploadId"], PartNumber=1,+ CopySource={"Bucket": src, "Key": "big"})["CopyPartResult"]["ETag"]+ euw1.complete_multipart_upload(Bucket=dst, Key="multi", UploadId=upload["UploadId"],+ MultipartUpload={"Parts": [{"PartNumber": 1, "ETag": etag}]})+ assert euw1.head_object(Bucket=dst, Key="multi")["ContentLength"] == len(part)+ finally:+ for client, bucket in ((usw2, src), (euw1, dst)):+ for obj in client.list_objects_v2(Bucket=bucket).get("Contents", []):+ client.delete_object(Bucket=bucket, Key=obj["Key"])+ client.delete_bucket(Bucket=bucket)+++# ---------------------------------------------------------------------------+# Cross-Region Replication (#2158)+# ---------------------------------------------------------------------------++_REPL_ROLE = "arn:aws:iam::000000000000:role/repl"+++def _versioned_bucket(region, slug):+ client = _regional_client("s3", region)+ name = f"crr-{slug}-{_uuid_mod.uuid4().hex[:8]}"+ kwargs = {} if region == "us-east-1" else {"CreateBucketConfiguration": {"LocationConstraint": region}}+ client.create_bucket(Bucket=name, **kwargs)+ client.put_bucket_versioning(Bucket=name, VersioningConfiguration={"Status": "Enabled"})+ return client, name+++def _replicate(client, src, dst, **rule):+ rule = {"ID": "r1", "Status": "Enabled", "Destination": {"Bucket": f"arn:aws:s3:::{dst}"}, **rule}+ client.put_bucket_replication(Bucket=src, ReplicationConfiguration={"Role": _REPL_ROLE, "Rules": [rule]})+++def _purge(client, bucket):+ lv = client.list_object_versions(Bucket=bucket)+ for v in lv.get("Versions", []) + lv.get("DeleteMarkers", []):+ client.delete_object(Bucket=bucket, Key=v["Key"], VersionId=v["VersionId"])+ client.delete_bucket(Bucket=bucket)+++def crr_pair():+ """A us-east-1 source and an eu-west-1 destination, both versioned."""+ use1, src = _versioned_bucket("us-east-1", "src")+ euw1, dst = _versioned_bucket("eu-west-1", "dst")+ yield use1, src, euw1, dst+ _purge(use1, src)+ _purge(euw1, dst)+++def test_s3_replication_cross_region_replica_readable_in_destination(crr_pair):+ use1, src, euw1, dst = crr_pair+ _replicate(use1, src, dst, Filter={"Prefix": ""}, DeleteMarkerReplication={"Status": "Disabled"})+ use1.put_object(Bucket=src, Key="a.txt", Body=b"across regions")+ assert use1.head_object(Bucket=src, Key="a.txt")["ReplicationStatus"] == "COMPLETED"+ replica = euw1.get_object(Bucket=dst, Key="a.txt")+ assert replica["ReplicationStatus"] == "REPLICA"+ assert replica["Body"].read() == b"across regions"+++def _delete_markers(client, bucket, key):+ return [m for m in client.list_object_versions(Bucket=bucket).get("DeleteMarkers", []) if m["Key"] == key]+++def test_s3_delete_marker_replication_enabled_v2_rule(crr_pair):+ use1, src, euw1, dst = crr_pair+ _replicate(use1, src, dst, Filter={"Prefix": ""}, DeleteMarkerReplication={"Status": "Enabled"})+ use1.put_object(Bucket=src, Key="gone.txt", Body=b"x")+ use1.put_object(Bucket=src, Key="batch.txt", Body=b"y")+ use1.delete_object(Bucket=src, Key="gone.txt")+ use1.delete_objects(Bucket=src, Delete={"Objects": [{"Key": "batch.txt"}]})+ for key in ("gone.txt", "batch.txt"):+ assert len(_delete_markers(euw1, dst, key)) == 1+ with pytest.raises(ClientError) as exc:+ euw1.get_object(Bucket=dst, Key=key)+ assert exc.value.response["Error"]["Code"] == "NoSuchKey"+++def test_s3_delete_marker_replication_version_id_delete_stays_local(crr_pair):+ use1, src, euw1, dst = crr_pair+ _replicate(use1, src, dst, Filter={"Prefix": ""}, DeleteMarkerReplication={"Status": "Enabled"})+ vid = use1.put_object(Bucket=src, Key="v.txt", Body=b"x")["VersionId"]+ use1.delete_object(Bucket=src, Key="v.txt", VersionId=vid)+ assert euw1.get_object(Bucket=dst, Key="v.txt")["Body"].read() == b"x"+ assert _delete_markers(euw1, dst, "v.txt") == []++[email protected]("rule", [+ {"Filter": {"Prefix": ""}, "DeleteMarkerReplication": {"Status": "Disabled"}},+ {"Prefix": ""},+ {"Filter": {"Tag": {"Key": "keep", "Value": "yes"}}, "DeleteMarkerReplication": {"Status": "Enabled"}},+], ids=["disabled", "v1-rule", "tag-filter"])+def test_s3_delete_marker_replication_not_replicated(crr_pair, rule):+ use1, src, euw1, dst = crr_pair+ _replicate(use1, src, dst, **rule)+ use1.put_object(Bucket=src, Key="k.txt", Body=b"x", Tagging="keep=yes")+ assert euw1.get_object(Bucket=dst, Key="k.txt")["Body"].read() == b"x"+ use1.delete_object(Bucket=src, Key="k.txt")+ assert _delete_markers(euw1, dst, "k.txt") == []+ assert euw1.get_object(Bucket=dst, Key="k.txt")["Body"].read() == b"x"+++def _replicated_keys(client, bucket):+ return sorted(o["Key"] for o in client.list_objects_v2(Bucket=bucket).get("Contents", []))+++def test_s3_replication_tag_filter_single_tag(crr_pair):+ use1, src, euw1, dst = crr_pair+ _replicate(use1, src, dst, Filter={"Tag": {"Key": "replicate", "Value": "yes"}},+ DeleteMarkerReplication={"Status": "Disabled"})+ use1.put_object(Bucket=src, Key="tagged", Body=b"1", Tagging="replicate=yes&other=1")+ use1.put_object(Bucket=src, Key="wrong-value", Body=b"2", Tagging="replicate=no")+ use1.put_object(Bucket=src, Key="untagged", Body=b"3")+ use1.copy_object(Bucket=src, Key="copy-replaced", CopySource={"Bucket": src, "Key": "untagged"},+ TaggingDirective="REPLACE", Tagging="replicate=yes")+ use1.copy_object(Bucket=src, Key="copy-kept", CopySource={"Bucket": src, "Key": "tagged"})+ assert _replicated_keys(euw1, dst) == ["copy-kept", "copy-replaced", "tagged"]+ assert "ReplicationStatus" not in use1.head_object(Bucket=src, Key="untagged")+++def test_s3_replication_tag_filter_and(crr_pair):+ use1, src, euw1, dst = crr_pair+ _replicate(use1, src, dst,+ Filter={"And": {"Prefix": "logs/", "Tags": [{"Key": "a", "Value": "1"}, {"Key": "b", "Value": "2"}]}},+ DeleteMarkerReplication={"Status": "Disabled"})+ use1.put_object(Bucket=src, Key="logs/both", Body=b"x", Tagging="a=1&b=2")+ use1.put_object(Bucket=src, Key="logs/one", Body=b"x", Tagging="a=1")+ use1.put_object(Bucket=src, Key="data/both", Body=b"x", Tagging="a=1&b=2")+ assert _replicated_keys(euw1, dst) == ["logs/both"]+++def test_s3_two_way_replication_has_no_loop():+ use1, a = _versioned_bucket("us-east-1", "a")+ euw1, b = _versioned_bucket("eu-west-1", "b")+ try:+ _replicate(use1, a, b, Filter={"Prefix": ""}, DeleteMarkerReplication={"Status": "Disabled"})+ _replicate(euw1, b, a, Filter={"Prefix": ""}, DeleteMarkerReplication={"Status": "Disabled"})+ use1.put_object(Bucket=a, Key="from-a", Body=b"a")+ euw1.put_object(Bucket=b, Key="from-b", Body=b"b")+ for client, bucket in ((use1, a), (euw1, b)):+ versions = client.list_object_versions(Bucket=bucket)["Versions"]+ assert sorted(v["Key"] for v in versions) == ["from-a", "from-b"]+ assert euw1.head_object(Bucket=b, Key="from-a")["ReplicationStatus"] == "REPLICA"+ assert use1.head_object(Bucket=a, Key="from-b")["ReplicationStatus"] == "REPLICA"+ assert use1.head_object(Bucket=a, Key="from-a")["ReplicationStatus"] == "COMPLETED"+ finally:+ _purge(use1, a)+ _purge(euw1, b)+++# ---------------------------------------------------------------------------+# Multi-Region Access Points through S3 Control (#2158)+# ---------------------------------------------------------------------------++_ACCOUNT = "000000000000"+++def s3control_dns():+ """boto3 prefixes S3 Control hosts with the account id."""+ with patch_endpoint_dns():+ yield+++def mrap_members():+ """One bucket in us-east-1 and one in eu-west-1, each holding who.txt."""+ tag = _uuid_mod.uuid4().hex[:8]+ use1, use1_bucket = _versioned_bucket("us-east-1", f"mrap-{tag}-use1")+ euw1, euw1_bucket = _versioned_bucket("eu-west-1", f"mrap-{tag}-euw1")+ use1.put_object(Bucket=use1_bucket, Key="who.txt", Body=b"use1")+ euw1.put_object(Bucket=euw1_bucket, Key="who.txt", Body=b"euw1")+ yield use1, use1_bucket, euw1, euw1_bucket+ for client, bucket in ((use1, use1_bucket), (euw1, euw1_bucket)):+ try:+ _purge(client, bucket)+ except ClientError:+ pass+++def _mrap_name():+ return f"mrap-{_uuid_mod.uuid4().hex[:10]}"+++def test_s3_mrap_routes_default_for_records_persisted_before_routes():+ from ministack.services import s3 as s3_svc++ legacy = {"Name": "old", "Alias": "a.mrap", "Regions": ["b1", "b2"], "CreatedAt": "2026-01-01T00:00:00Z"}+ assert s3_svc.mrap_routes(legacy) == {"b1": 100, "b2": 100}+ assert s3_svc.mrap_routes({**legacy, "Routes": {"b1": 0}}) == {"b1": 0, "b2": 100}+++def _mrap_create(ctl, name, buckets):+ token = ctl.create_multi_region_access_point(+ AccountId=_ACCOUNT, ClientToken=_uuid_mod.uuid4().hex,+ Details={"Name": name, "Regions": [{"Bucket": b} for b in buckets]})["RequestTokenARN"]+ return ctl.describe_multi_region_access_point_operation(+ AccountId=_ACCOUNT, RequestTokenARN=token)["AsyncOperation"]+++def _mrap_delete(ctl, name):+ token = ctl.delete_multi_region_access_point(+ AccountId=_ACCOUNT, ClientToken=_uuid_mod.uuid4().hex, Details={"Name": name})["RequestTokenARN"]+ return ctl.describe_multi_region_access_point_operation(+ AccountId=_ACCOUNT, RequestTokenARN=token)["AsyncOperation"]+++def test_s3_mrap_control_async_create_describe_delete(s3control_dns, mrap_members):+ _, use1_bucket, _, euw1_bucket = mrap_members+ ctl = _regional_client("s3control", "us-west-2")+ name = _mrap_name()+ op = _mrap_create(ctl, name, [use1_bucket, euw1_bucket])+ assert re.fullmatch(rf"arn:aws:s3:us-west-2:{_ACCOUNT}:async-request/mrap/create/.+", op["RequestTokenARN"])+ assert op["Operation"] == "CreateMultiRegionAccessPoint"+ assert op["RequestStatus"] == "SUCCEEDED"+ assert op["RequestParameters"]["CreateMultiRegionAccessPointRequest"]["Name"] == name+ regions = op["ResponseDetails"]["MultiRegionAccessPointDetails"]["Regions"]+ assert sorted(r["Name"] for r in regions) == ["eu-west-1", "us-east-1"]++ again = _mrap_create(ctl, name, [use1_bucket, euw1_bucket])+ assert again["RequestStatus"] == "FAILED"+ assert again["ResponseDetails"]["ErrorDetails"]["Code"] == "MultiRegionAccessPointAlreadyOwnedByYou"+ assert again["ResponseDetails"]["ErrorDetails"]["Message"] == (+ "You must provide a unique name for each Multi-Region Access Point in your account. "+ "A MRAP with this name already exists.")++ deleted = _mrap_delete(ctl, name)+ assert (deleted["Operation"], deleted["RequestStatus"]) == ("DeleteMultiRegionAccessPoint", "SUCCEEDED")+ with pytest.raises(ClientError) as exc:+ ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=name)+ assert exc.value.response["Error"]["Code"] == "NoSuchMultiRegionAccessPoint"+++def test_s3_mrap_control_async_validation_failures(s3control_dns, mrap_members):+ use1, use1_bucket, _, euw1_bucket = mrap_members+ ctl = _regional_client("s3control", "us-west-2")+ name = _mrap_name()+ op = _mrap_create(ctl, name, [use1_bucket, f"missing-{use1_bucket}"])+ assert op["RequestStatus"] == "FAILED"+ err = op["ResponseDetails"]["ErrorDetails"]+ assert (err["Code"], err["Message"], err["Resource"]) == (+ "NoSuchBucket", "The specified bucket does not exist.", name)+ assert op["ResponseDetails"]["MultiRegionAccessPointDetails"]["Regions"] == []++ second_use1 = f"{use1_bucket}-2"+ use1.create_bucket(Bucket=second_use1)+ try:+ op = _mrap_create(ctl, name, [use1_bucket, second_use1])+ assert op["ResponseDetails"]["ErrorDetails"]["Code"] == "MultiRegionAccessPointSameBucketRegion"+ assert op["ResponseDetails"]["ErrorDetails"]["Message"] == (+ "The buckets specified must be part of different Regions.")+ finally:+ use1.delete_bucket(Bucket=second_use1)+ with pytest.raises(ClientError):+ ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=name)+++def test_s3_mrap_control_read_get_list_policy(s3control_dns, mrap_members):+ use1, use1_bucket, _, euw1_bucket = mrap_members+ ctl = _regional_client("s3control", "us-west-2")+ names = [_mrap_name(), _mrap_name()]+ for name in names:+ assert _mrap_create(ctl, name, [use1_bucket, euw1_bucket])["RequestStatus"] == "SUCCEEDED"+ try:+ ap = ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=names[0])["AccessPoint"]+ assert ap["Name"] == names[0]+ assert re.fullmatch(r"[a-z][a-z0-9]{12}\.mrap", ap["Alias"])+ assert ap["Status"] == "READY"+ assert {(r["Bucket"], r["Region"], r["BucketAccountId"]) for r in ap["Regions"]} == {+ (use1_bucket, "us-east-1", _ACCOUNT), (euw1_bucket, "eu-west-1", _ACCOUNT)}++ listed, token = [], None+ while True:+ kwargs = {"AccountId": _ACCOUNT, "MaxResults": 1, **({"NextToken": token} if token else {})}+ page = ctl.list_multi_region_access_points(**kwargs)+ listed += [a["Name"] for a in page["AccessPoints"]]+ token = page.get("NextToken")+ if not token:+ break+ assert set(names) <= set(listed)++ policy = json.dumps({"Version": "2012-10-17", "Statement": [{+ "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{_ACCOUNT}:root"},+ "Action": "s3:GetObject", "Resource": f"arn:aws:s3::{_ACCOUNT}:accesspoint/{ap['Alias']}/object/*"}]})+ token = ctl.put_multi_region_access_point_policy(+ AccountId=_ACCOUNT, ClientToken="p", Details={"Name": names[0], "Policy": policy})["RequestTokenARN"]+ op = ctl.describe_multi_region_access_point_operation(AccountId=_ACCOUNT, RequestTokenARN=token)+ assert op["AsyncOperation"]["RequestStatus"] == "SUCCEEDED"+ doc = ctl.get_multi_region_access_point_policy(AccountId=_ACCOUNT, Name=names[0])["Policy"]+ assert doc["Established"]["Policy"] == policy+ assert doc["Proposed"]["Policy"] == policy++ with pytest.raises(ClientError) as exc:+ use1.delete_bucket(Bucket=use1_bucket)+ assert exc.value.response["Error"]["Code"] == "BucketHasAccessPointsAttached"+ assert exc.value.response["Error"]["Message"] == "Bucket has access points attached and cannot be deleted."+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+ finally:+ for name in names:+ _mrap_delete(ctl, name)++ with pytest.raises(ClientError) as exc:+ ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=names[0])+ err = exc.value.response["Error"]+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404+ assert err["Message"] == "The specified Multi-Region Access Point does not exist."+ assert (err["MultiRegionAccessPointName"], err["AccountId"]) == (names[0], _ACCOUNT)+++def test_s3_mrap_control_read_routes(s3control_dns, mrap_members):+ _, use1_bucket, _, euw1_bucket = mrap_members+ ctl, routes_ctl = _regional_client("s3control", "us-west-2"), _regional_client("s3control", "eu-west-1")+ name = _mrap_name()+ _mrap_create(ctl, name, [use1_bucket, euw1_bucket])+ try:+ alias = ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=name)["AccessPoint"]["Alias"]+ arn = f"arn:aws:s3::{_ACCOUNT}:accesspoint/{alias}"+ routes = routes_ctl.get_multi_region_access_point_routes(AccountId=_ACCOUNT, Mrap=arn)+ assert routes["Mrap"] == arn+ assert {(r["Bucket"], r["Region"], r["TrafficDialPercentage"]) for r in routes["Routes"]} == {+ (use1_bucket, "us-east-1", 100), (euw1_bucket, "eu-west-1", 100)}++ def submit_error(updates, mrap=arn):+ with pytest.raises(ClientError) as exc:+ routes_ctl.submit_multi_region_access_point_routes(AccountId=_ACCOUNT, Mrap=mrap, RouteUpdates=updates)+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+ return exc.value.response["Error"]++ assert submit_error([{"Bucket": use1_bucket, "TrafficDialPercentage": 50}]) == {+ "Code": "InvalidRequest", "Message": "Request invalid"}+ assert submit_error([{"Bucket": f"x-{use1_bucket}", "TrafficDialPercentage": 0}])["Message"] == (+ "The provided Region or bucket is not part of the Multi-Region Access Point.")+ assert submit_error([{"Bucket": use1_bucket, "TrafficDialPercentage": 0},+ {"Bucket": euw1_bucket, "TrafficDialPercentage": 0}])["Message"] == (+ "At least one Region or bucket in the Multi-Region Access Point must be configured to receive "+ "traffic. Set at least one Region or bucket to Active, and then try again.")+ assert submit_error([{"Bucket": use1_bucket, "TrafficDialPercentage": 0}], mrap=name)["Message"] == (+ "Request invalid")++ routes_ctl.submit_multi_region_access_point_routes(+ AccountId=_ACCOUNT, Mrap=arn, RouteUpdates=[{"Bucket": use1_bucket, "TrafficDialPercentage": 0}])+ dials = {r["Bucket"]: r["TrafficDialPercentage"]+ for r in routes_ctl.get_multi_region_access_point_routes(AccountId=_ACCOUNT, Mrap=arn)["Routes"]}+ assert dials == {use1_bucket: 0, euw1_bucket: 100}+ finally:+ _mrap_delete(ctl, name)+++def test_s3_mrap_control_region_rules(s3control_dns, mrap_members):+ """Management operations are served only from us-west-2 and route+ operations from five regions; anything else is redirected (observed)."""+ _, use1_bucket, _, euw1_bucket = mrap_members+ with pytest.raises(ClientError) as exc:+ _mrap_create(_regional_client("s3control", "us-east-1"), _mrap_name(), [use1_bucket, euw1_bucket])+ err = exc.value.response["Error"]+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 301+ assert err["Code"] == "PermanentRedirect"+ assert err["Message"] == ("This API operation is only available in the following Regions: us-west-2. "+ "Make sure to send all future requests to a supported Region.")+ assert err["Endpoint"] == "https://s3-control.us-west-2.amazonaws.com/v20180820/async-requests/mrap/create"++ ctl = _regional_client("s3control", "us-west-2")+ name = _mrap_name()+ _mrap_create(ctl, name, [use1_bucket, euw1_bucket])+ try:+ alias = ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=name)["AccessPoint"]["Alias"]+ arn = f"arn:aws:s3::{_ACCOUNT}:accesspoint/{alias}"+ with pytest.raises(ClientError) as exc:+ _regional_client("s3control", "eu-central-1").submit_multi_region_access_point_routes(+ AccountId=_ACCOUNT, Mrap=arn, RouteUpdates=[{"Bucket": use1_bucket, "TrafficDialPercentage": 0}])+ assert exc.value.response["Error"]["Message"] == (+ "This API operation is only available in the following Regions: us-west-2, ap-southeast-2, "+ "ap-northeast-1, eu-west-1 and us-east-1. Make sure to send all future requests to a supported Region.")+ for region in ("us-east-1", "us-west-2", "eu-west-1", "ap-northeast-1", "ap-southeast-2"):+ _regional_client("s3control", region).get_multi_region_access_point_routes(AccountId=_ACCOUNT, Mrap=arn)++ with pytest.raises(ClientError) as exc:+ ctl.get_multi_region_access_point(AccountId="111122223333", Name=name)+ assert exc.value.response["Error"]["Code"] == "AccessDenied"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403+ finally:+ _mrap_delete(ctl, name)+++def _mrap_request(alias, method, key, body=b""):+ import http.client++ parsed = urlparse(ENDPOINT)+ conn = http.client.HTTPConnection(parsed.hostname, parsed.port or 80, timeout=30)+ conn.request(method, f"/{key}", body=body or None,+ headers={"Host": f"{alias}.accesspoint.s3-global.amazonaws.com"})+ resp = conn.getresponse()+ data = resp.read()+ conn.close()+ return resp.status, data+++def test_s3_mrap_end_to_end_routing_failover_and_replication(s3control_dns, mrap_members):+ use1, use1_bucket, euw1, euw1_bucket = mrap_members+ _replicate(use1, use1_bucket, euw1_bucket, Filter={"Prefix": "data/"},+ DeleteMarkerReplication={"Status": "Disabled"})+ _replicate(euw1, euw1_bucket, use1_bucket, Filter={"Prefix": "data/"},+ DeleteMarkerReplication={"Status": "Disabled"})+ ctl, routes_ctl = _regional_client("s3control", "us-west-2"), _regional_client("s3control", "eu-west-1")+ name = _mrap_name()+ # Listed eu-west-1 first: the us-east-1 member wins on region, not position.+ _mrap_create(ctl, name, [euw1_bucket, use1_bucket])+ alias = ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=name)["AccessPoint"]["Alias"]+ arn = f"arn:aws:s3::{_ACCOUNT}:accesspoint/{alias}"+ try:+ for region in ("us-east-1", "eu-west-1", None):+ assert _mrap_get(alias, "who.txt", region=region) == (200, "use1")++ routes_ctl.submit_multi_region_access_point_routes(+ AccountId=_ACCOUNT, Mrap=arn, RouteUpdates=[{"Bucket": use1_bucket, "TrafficDialPercentage": 0}])+ assert _mrap_get(alias, "who.txt") == (200, "euw1")+ with pytest.raises(ClientError):+ routes_ctl.submit_multi_region_access_point_routes(+ AccountId=_ACCOUNT, Mrap=arn, RouteUpdates=[{"Bucket": euw1_bucket, "TrafficDialPercentage": 0}])+ assert _mrap_get(alias, "who.txt") == (200, "euw1")++ assert _mrap_request(alias, "PUT", "data/new.txt", b"through mrap")[0] == 200+ assert euw1.get_object(Bucket=euw1_bucket, Key="data/new.txt")["ReplicationStatus"] == "COMPLETED"+ assert use1.get_object(Bucket=use1_bucket, Key="data/new.txt")["Body"].read() == b"through mrap"+ finally:+ _mrap_delete(ctl, name)+ assert _mrap_request(alias, "GET", "who.txt")[0] in (403, 404)diff --git a/tests/test_tagging.py b/tests/test_tagging.pyindex 85cddd92..86809815 100644--- a/tests/test_tagging.py+++ b/tests/test_tagging.py@@ -75,6 +75,26 @@ def test_tagging_get_resources_s3_tags_returned(tagging, s3):assert tag_map["team"] == "platform"+def test_tagging_get_resources_s3_follows_bucket_region(tagging):+ """GetResources lists only buckets homed in the API's region, while+ TagResources still tags a bucket in another region (observed on AWS+ 2026-10-12)."""+ name = f"tg-s3-usw2-{_uid()}"+ usw2_s3 = _regional_client("s3", "us-west-2")+ usw2_s3.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": "us-west-2"})+ try:+ arn = f"arn:aws:s3:::{name}"+ tagging.tag_resources(ResourceARNList=[arn], Tags={_TAG_KEY: "s3-region"})+ filters = [{"Key": _TAG_KEY, "Values": ["s3-region"]}]+ listed = [r["ResourceARN"] for r in tagging.get_resources(TagFilters=filters)["ResourceTagMappingList"]]+ assert arn not in listed+ usw2 = _regional_client("resourcegroupstaggingapi", "us-west-2")+ listed = [r["ResourceARN"] for r in usw2.get_resources(TagFilters=filters)["ResourceTagMappingList"]]+ assert arn in listed+ finally:+ usw2_s3.delete_bucket(Bucket=name)++# ========== SQS ==========def test_tagging_get_resources_sqs(tagging, sqs):