Skip to content

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

fix(s3): authorize Multi-Region Access Point requests under AUTH=true (#2387)

iot-rocket0e7fae0a1bb7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9bd83816..278aa712 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **S3 — Multi-Region Access Point requests are authorized** — under `AUTH=true`, requests through an MRAP hostname were served without an IAM check. They are now authorized on the member bucket and then on the MRAP, whose policy is evaluated like a bucket policy, and answer `AccessDenied` naming the resource that refused them. Contributed by @iot-rocket.
- **Cognito — signing keys, managed login and federated users** — every user pool signed with one shared key (`kid` `ministack-key-1`); each pool now has two keys of its own, one for access tokens and one for ID tokens, both published at its JWKS URI, and a token verifies only against its own pool. Managed login refuses PKCE `plain` and a `code_challenge` without `S256` (`error=invalid_request`), any `redirect_uri` the client didn't register, also for a client with no callback URLs, and a `grant_type` other than `authorization_code`, `refresh_token` or `client_credentials` (400 `unsupported_grant_type`). Adding an identity provider creates the group `<user pool id>_<provider name>`, and a federated user's new profile joins it and carries its `identities`, so the ID token has both claims. Reported by @cupidchan.
- **S3 — bucket policy writes through an access point** — under `AUTH=true` `PutBucketPolicy` and `DeleteBucketPolicy` sent through an access point alias or ARN changed the bucket's policy; they now get 403 `AccessDenied` with an explicit deny on the access point, while `GetBucketPolicy` through it and both writes on the bucket itself work as before. Contributed by @iot-rocket.
- **S3 — SigV2 requests through an access point** — under `AUTH=true` a SigV2 presigned URL for an access point ARN failed its signature check, because the check signed the access point host as a bucket, and a SigV2 `Authorization` header through an access point alias or ARN was served. The presigned URL is now checked on its path as the SDK signs it, and the header request gets 400 `InvalidRequest`. Contributed by @iot-rocket.
diff --git a/ministack/app.py b/ministack/app.py
index 0951d277..92b9781c 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -2210,6 +2210,33 @@ def _resolve_mrap_host(host: str):
return None
+def _enforce_mrap_request(host: str, bucket: str, method: str, mrap_path: str, headers: dict, body: bytes,
+ query_params: dict):
+ """Under AUTH=true, authorize an MRAP request on its member bucket and then on the MRAP itself."""
+ from ministack.core.iam_actions import _s3_action, extract_resource_arn, s3_additional_checks, s3_service_context
+ from ministack.core.responses import get_account_id
+
+ s3_action = _s3_action(method, mrap_path, query_params)
+ if not AUTH or not s3_action:
+ return None
+ s3 = _get_module("s3")
+ s3_headers = s3._merge_hoisted_amz_headers(headers, query_params)
+ bucket_arn = extract_resource_arn("s3", method, mrap_path, s3_headers, body, query_params, "", "")
+ key = bucket_arn[len(f"arn:aws:s3:::{bucket}"):]
+ mrap_arn = f"arn:aws:s3::{get_account_id()}:accesspoint/{_MRAP_HOST_RE.match(host).group(1).lower()}"
+ service_context = s3_service_context(f"s3:{s3_action}", query_params, mrap_path, s3_headers)
+ for resource in (bucket_arn, mrap_arn + (f"/object{key}" if key else "")):
+ denied = _enforce_data_plane("s3", f"s3:{s3_action}", headers, query_params, "", resource_arn=resource,
+ service_context=service_context, named_resource=f'"{resource}"')
+ if denied:
+ return denied
+ for extra_action, extra_arn in s3_additional_checks(method, mrap_path, s3_headers, body, query_params):
+ denied = _enforce_data_plane("s3", extra_action, headers, query_params, "", resource_arn=extra_arn)
+ if denied:
+ return denied
+ return None
+
+
async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: dict, body: bytes, query_params: dict):
"""Handle virtual-hosted S3 requests before generic routing."""
if _MRAP_HOST_RE.match(host.split(":")[0].strip()):
@@ -2234,6 +2261,11 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: d
if not k.lower().startswith("x-amz-")
}
mrap_path = "/" + mrap_bucket + (path if path != "/" else "/")
+ # The MRAP and its bucket both have to allow the request.
+ denied = _enforce_mrap_request(host.split(":")[0].strip(), mrap_bucket, method, mrap_path, headers, body,
+ query_params)
+ if denied:
+ return denied
return await _get_module("s3").handle_request(
method, mrap_path, headers, body, query_params, signed_path=path,
enforce_bucket_region=False,
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index d421f8f4..b89252b3 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -1087,8 +1087,17 @@ def _bucket_owner_account(name: str) -> str | None:
return None
+# A Multi-Region Access Point or an object through it: arn:aws:s3::<account>:accesspoint/<alias>[/object/<key>].
+_MRAP_RESOURCE_ARN_RE = re.compile(
+ r"^arn:aws:s3::(\d{12}):accesspoint/([a-z][a-z0-9]*\.mrap)(?:/object/.*)?$", re.DOTALL)
+
+
def bucket_policy_for_arn(resource_arn: str) -> tuple[str, str] | None:
- """The bucket policy and owner for the identity check; ``_apply_bucket_scope`` gates foreign buckets."""
+ """The bucket (or MRAP) policy and owner for the identity check; ``_apply_bucket_scope`` gates foreign buckets."""
+ mrap = _MRAP_RESOURCE_ARN_RE.match(resource_arn)
+ if mrap:
+ record = find_mrap(mrap.group(2)) if mrap.group(1) == get_account_id() else None
+ return (record.get("Policy") or "", mrap.group(1)) if record else None
if not resource_arn.startswith("arn:aws:s3:::"):
return None
bucket = resource_arn[len("arn:aws:s3:::"):].split("/", 1)[0]
diff --git a/tests/test_s3.py b/tests/test_s3.py
index 0e32a17d..826ac16d 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -18,7 +18,14 @@ import pytest
import requests
from botocore.config import Config
from botocore.exceptions import ClientError
-from conftest import inprocess_iam_user, make_client, patch_endpoint_dns, routed_request, sqs_policy_allow_s3
+from conftest import (
+ inprocess_iam_user,
+ make_client,
+ patch_endpoint_dns,
+ routed_request,
+ second_access_key,
+ sqs_policy_allow_s3,
+)
from ministack.core.responses import AccountScopedDict, request_scope
from ministack.services import iam as _iam_mod
@@ -10008,6 +10015,67 @@ def test_s3_mrap_end_to_end_routing_failover_and_replication(s3control_dns, mrap
assert _mrap_request(alias, "GET", "who.txt")[0] in (403, 404)
+def _mrap_signed_request(credentials, alias, method, target, body=b""):
+ """A SigV4-signed request through the MRAP hostname: status and body."""
+ from botocore.auth import S3SigV4Auth
+ from botocore.awsrequest import AWSRequest
+ from botocore.credentials import Credentials
+
+ host = f"{alias}.accesspoint.s3-global.amazonaws.com"
+ request = AWSRequest(method, f"{ENDPOINT.rstrip('/')}{target}", data=body,
+ headers={"host": host, "x-amz-content-sha256": hashlib.sha256(body).hexdigest()})
+ S3SigV4Auth(Credentials(*credentials), "s3", "us-east-1").add_auth(request)
+ response = requests.request(method, request.url, data=body, headers=dict(request.headers.items()), timeout=30)
+ return response.status_code, response.content
+
+
[email protected]("grant,denied_on", [
+ ("none", "bucket"), ("mrap", "bucket"), ("bucket", "mrap"), ("both", None), ("mrap-policy", None),
+])
+def test_s3_mrap_requests_are_authorized_on_the_bucket_and_the_mrap(
+ auth_enabled, iam_user, s3control_dns, mrap_members, grant, denied_on):
+ """Through an MRAP, S3 checks the member bucket first and then the MRAP; an MRAP policy can allow the latter."""
+ _, use1_bucket, _, _ = mrap_members
+ ctl = _regional_client("s3control", "us-west-2")
+ name = _mrap_name()
+ _mrap_create(ctl, name, [use1_bucket])
+ alias = ctl.get_multi_region_access_point(AccountId=_ACCOUNT, Name=name)["AccessPoint"]["Alias"]
+ mrap_arn = f"arn:aws:s3::{_ACCOUNT}:accesspoint/{alias}"
+ bucket_arn = f"arn:aws:s3:::{use1_bucket}"
+
+ def allow(prefix):
+ return [{"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject"], "Resource": f"{prefix}/*"},
+ {"Effect": "Allow", "Action": "s3:ListBucket", "Resource": prefix}]
+
+ identity = {"none": [], "mrap": allow(mrap_arn), "bucket": allow(bucket_arn), "both": allow(mrap_arn)
+ + allow(bucket_arn), "mrap-policy": allow(bucket_arn)}[grant]
+ try:
+ user = iam_user(policy={"Version": "2012-10-17", "Statement": identity} if identity else None)
+ if grant == "mrap-policy":
+ statements = [{**s, "Principal": {"AWS": user.arn}} for s in allow(mrap_arn)]
+ ctl.put_multi_region_access_point_policy(
+ AccountId=_ACCOUNT, ClientToken=_uuid_mod.uuid4().hex,
+ Details={"Name": name, "Policy": json.dumps({"Version": "2012-10-17", "Statement": statements})})
+ with second_access_key(user) as credentials:
+ for action, method, target, body, resource in [
+ ("GetObject", "GET", "/who.txt", b"", "/who.txt"),
+ ("PutObject", "PUT", "/mrap-put.txt", b"x", "/mrap-put.txt"),
+ ("ListBucket", "GET", "/?list-type=2", b"", ""),
+ ]:
+ status, data = _mrap_signed_request(credentials, alias, method, target, body)
+ if not auth_enabled or denied_on is None:
+ assert status == 200, data
+ continue
+ arn = (bucket_arn if denied_on == "bucket" else mrap_arn + ("/object" if resource else "")) + resource
+ assert status == 403 and ElementTree.fromstring(data).findtext("Code") == "AccessDenied"
+ assert ElementTree.fromstring(data).findtext("Message") == (
+ f'User: {user.arn} is not authorized to perform: s3:{action} on resource: "{arn}" '
+ f"because no identity-based policy allows the s3:{action} action")
+ finally:
+ _mrap_delete(ctl, name)
+
+
# IAM contracts, run by CI with AUTH=false and AUTH=true.
@pytest.fixture
def auth_s3_objects(s3):