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): apply access point policies and refuse unsigned requests (#2369)
iot-rocket66f879ffa89b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8ae1860e..4052f6df 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Fixed+- **S3 — access point policies and unsigned requests** — an access point policy was stored but never applied, and an unsigned request through an access point was served. With `AUTH=true` a request through an access point alias or ARN is allowed on the access point by an identity policy or the access point policy (a Deny in either refuses it), and an unsigned one gets 400 `InvalidRequest`; S3 Control calls on the access point are unaffected. Contributed by @iot-rocket.+## [1.5.31] — 2026-10-21### Addeddiff --git a/ministack/app.py b/ministack/app.pyindex c1268e41..3bb93d14 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -2232,7 +2232,7 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: dbucket = _extract_s3_vhost_bucket(host)if not bucket or _S3_VHOST_EXCLUDE_RE.search(host) or bucket in _NON_S3_VHOST_NAMES:return None- # An access point ARN is addressed as `<name>-<account>.<host>`, signed `s3`.+ # An access point ARN is addressed as `<name>-<account>.<host>`, signed `s3` or unsigned.access_point_region = access_point_alias = Noneap_match = _ACCESS_POINT_HOST_RE.match(bucket)s3 = _get_module("s3")@@ -2257,7 +2257,7 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: durl = f"http://{host}{path}" + (f"?{query}" if query else "")return await s3_object_lambda.handle_request(record, olap_region, method, path.lstrip("/"), headers, body,query_params, url)- if ap_match and s3.signed_service(headers, query_params) == "s3":+ if ap_match and s3.signed_service(headers, query_params) in ("s3", None):target = s3.resolve_access_point_host(ap_match.group("name"), ap_match.group("account"),s3._signed_region(headers, query_params))if target is not None:diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.pyindex 1b83b831..d4bd8411 100644--- a/ministack/core/iam_evaluator.py+++ b/ministack/core/iam_evaluator.py@@ -1619,6 +1619,11 @@ def enforce(access_key_id: str, iam_action: str, service: str,result = evaluate(ctx, principal.policies, *principal.limits)found = _resource_policy(service, resource_arn)+ if found is None and service == "s3" and "s3:dataaccesspointarn" in context:+ # A data request through an access point meets the access point policy on the access point ARN.+ from ministack.services.s3 import access_point_policy_for_arn++ found = access_point_policy_for_arn(resource_arn)if found is not None:result = combine_resource_policy(result, ctx, *found, required=service in _POLICY_REQUIRED,limits=principal.limits)diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex 49b429de..b485398b 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -204,6 +204,19 @@ def access_point_for_alias(alias: str) -> tuple[str, str, dict] | None:"s3:AccessPointNetworkOrigin": record["NetworkOrigin"]}+def access_point_policy_for_arn(resource_arn: str) -> tuple[str, str] | None:+ """The access point policy and owner for an IAM check on an access point ARN."""+ try:+ arn = parse_arn(resource_arn)+ except ArnParseError:+ return None+ kind, _, rest = arn.resource.partition("/")+ if arn.service != "s3" or kind != "accesspoint":+ return None+ record = resolve_access_point(rest.split("/", 1)[0], arn.account_id, arn.region)+ return (record.get("Policy") or "", arn.account_id) if record else None++def _resolve_copy_source_alias(headers: dict) -> tuple:"""``(headers, denied)``: an ``x-amz-copy-source`` access point alias rewritten to its bucket."""source = headers.get("x-amz-copy-source", "")@@ -228,7 +241,7 @@ def resolve_access_point_host(name: str, account_id: str, signed_region: str | Nif not regions:return Noneif account_id != get_account_id():- # Access point policies aren't evaluated; another account is refused.+ # Requests from another account through an access point are refused.return None, None, _error("AccessDenied", "Access Denied", 403, f"/{name}")region = signed_region if signed_region in regions else regions[0]return resolve_access_point(name, account_id, region)["Bucket"], region, None@@ -2411,6 +2424,15 @@ async def handle_request(# reach the handlers exactly as a header-signed request delivers them.headers = _merge_hoisted_amz_headers(headers, query_params)+ if (access_point_region is not None or bucket.endswith(_ACCESS_POINT_ALIAS_SUFFIX)) and not internal:+ from ministack.app import AUTH++ if (AUTH and not _request_access_key(method, key, headers, query_params, body)+ and (access_point_region is not None or resolve_access_point_alias(bucket))):+ # Access points take signed requests only.+ return _error("InvalidRequest", "The authorization mechanism you have provided is not supported. "+ "Please use Signature Version 4.", 400)+# An Object Lambda Access Point alias goes to the Object Lambda flow.if bucket.endswith(_OBJECT_LAMBDA_ALIAS_SUFFIX):resolved = resolve_object_lambda_alias(bucket)diff --git a/tests/test_s3_access_points.py b/tests/test_s3_access_points.pyindex 3e8aeab0..e6b493e2 100644--- a/tests/test_s3_access_points.py+++ b/tests/test_s3_access_points.py@@ -7,6 +7,7 @@ import uuidimport boto3import pytest+from botocore import UNSIGNEDfrom botocore.config import Configfrom botocore.exceptions import ClientErrorfrom conftest import make_client, patch_endpoint_dns@@ -474,6 +475,62 @@ def test_access_point_request_meets_the_bucket_policy_contract(auth_enabled, iam_assert_access(auth_enabled, through_bucket, lambda: client.get_object(Bucket=bucket, Key="k.txt"))[email protected]_contract[email protected]("via", ["AccessPointArn", "Alias"])[email protected]("grant, effect, delegate, allowed", [+ ("bucket", "Allow", False, True),+ (None, "Allow", True, True),+ ("access point", None, True, True),+ ("access point", "Allow", False, False),+ ("both", "Deny", True, False),+], ids=["allow-identity-on-bucket", "allow-delegated", "delegated-identity-on-access-point",+ "allow-not-delegated", "deny"])+def test_access_point_policy_contract(auth_enabled, iam_user, bucket, access_point, via, grant, effect, delegate,+ allowed):+ """The access point policy answers for the access point, the bucket policy or identity for the bucket."""+ name, created = access_point+ arn = created["AccessPointArn"]+ user = iam_user(policy=_access_point_policy(bucket, arn, grant) if grant else None)+ if delegate:+ _client("s3", "us-east-1").put_bucket_policy(Bucket=bucket, Policy=json.dumps({+ "Version": "2012-10-17", "Statement": [{+ "Effect": "Allow", "Principal": {"AWS": "*"}, "Action": "*",+ "Resource": [f"arn:aws:s3:::{bucket}", f"arn:aws:s3:::{bucket}/*"],+ "Condition": {"StringEquals": {"s3:DataAccessPointAccount": ACCOUNT}}}]}))+ if effect:+ _client("s3control", "us-east-1").put_access_point_policy(AccountId=ACCOUNT, Name=name, Policy=json.dumps({+ "Version": "2012-10-17", "Statement": [{+ "Effect": effect, "Principal": {"AWS": user.arn}, "Action": ["s3:GetObject", "s3:ListBucket"],+ "Resource": [arn, f"{arn}/object/*"]}]}))+ client = user.client("s3")+ _assert_access(auth_enabled, allowed, lambda: client.get_object(Bucket=created[via], Key="k.txt"))+ _assert_access(auth_enabled, allowed, lambda: client.list_objects_v2(Bucket=created[via]))+ _assert_access(auth_enabled, grant in ("bucket", "both"), lambda: client.get_object(Bucket=bucket, Key="k.txt"))++[email protected]_contract+def test_access_point_refuses_unsigned_requests_contract(auth_enabled, bucket, access_point):+ """Under AUTH an unsigned request through an access point is refused; the bucket still serves it."""+ _name, created = access_point+ s3 = _client("s3", "us-east-1")+ s3.put_bucket_ownership_controls(Bucket=bucket, OwnershipControls={+ "Rules": [{"ObjectOwnership": "BucketOwnerPreferred"}]})+ s3.put_public_access_block(Bucket=bucket, PublicAccessBlockConfiguration={k: False for k in (+ "BlockPublicAcls", "IgnorePublicAcls", "BlockPublicPolicy", "RestrictPublicBuckets")})+ s3.put_object(Bucket=bucket, Key="pub.txt", Body=b"public", ACL="public-read")+ anon = boto3.client("s3", endpoint_url=ENDPOINT, region_name="us-east-1",+ config=Config(signature_version=UNSIGNED, retries={"mode": "standard"}))+ assert anon.get_object(Bucket=bucket, Key="pub.txt")["Body"].read() == b"public"+ for target in (created["Alias"], created["AccessPointArn"]):+ if auth_enabled:+ with pytest.raises(ClientError) as exc:+ anon.get_object(Bucket=target, Key="pub.txt")+ error = exc.value.response+ assert (error["Error"]["Code"], error["ResponseMetadata"]["HTTPStatusCode"]) == ("InvalidRequest", 400)+ else:+ assert anon.get_object(Bucket=target, Key="pub.txt")["Body"].read() == b"public"++@pytest.mark.auth_contract@pytest.mark.parametrize("grant, deny, condition, allowed", [("both", None, False, True),