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 an access point's Block Public Access settings (#2342)
iot-rocket0ddf387c587f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3d7aa268..45e27273 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **Route 53 — VPC associations for private hosted zones** — `AssociateVPCWithHostedZone`, `DisassociateVPCFromHostedZone` and `ListHostedZonesByVPC` (paged with `MaxItems` and `NextToken`). They refuse a public zone (`PublicZoneVPCAssociation`), a VPC already associated with a zone of the same name (`ConflictingDomainExists`), a VPC the zone doesn't have (404 `VPCAssociationNotFound`) and the zone's last VPC (`LastVPCAssociation`). Contributed by @kharabasz.### Fixed+- **S3 — access point Block Public Access** — requests through an access point alias or ARN followed the bucket's Block Public Access settings alone, so a public ACL sent through an access point with the default settings was accepted. An access point's settings other than `BlockPublicPolicy` now count as the bucket's for requests through it, and its `BlockPublicAcls` refuses a public canned ACL, grant header or ACL body with 403 `AccessDenied`. Contributed by @iot-rocket.- **Lambda — Node.js HTTPS to a TLS gateway in the local executor** — with `USE_SSL=1` a Node function's `https` requests to the gateway went out as plain HTTP to its TLS port and the built-in SDK v3 clients always spoke HTTP, so custom resource callbacks and SDK calls failed with `socket hang up`; they now keep TLS on the gateway port, and `https.request` or `https.get` with a URL plus options no longer throws `ERR_INVALID_ARG_TYPE`. Contributed by @iot-rocket.- **Lambda — Node.js custom resource callbacks in the Docker executor under `USE_SSL`** — the Node shim kept the port of an https request to the gateway when `USE_SSL=1`, so a `cfn-response` or CDK style `ResponseURL` PUT (no port, or 443) went to port 443 and the stack waited out `ServiceTimeout`; it now goes to the gateway port over TLS, and other explicit ports are kept. Contributed by @iot-rocket.- **TLS — the generated certificate names `host.docker.internal`** — with `USE_SSL=1` and the Docker Lambda executor, functions reach the gateway as `https://host.docker.internal:<port>`, a name the generated certificate lacked, so every SDK call and callback from a container failed hostname verification; the certificate now carries it, and a cached one without it is regenerated. Contributed by @iot-rocket.diff --git a/ministack/app.py b/ministack/app.pyindex 372559e8..c39c894f 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -2322,11 +2322,15 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: dreturn deniedtry:+ # The access point an ARN host names, for its Block Public Access settings.+ access_point = (s3.resolve_access_point(ap_match.group("name"), ap_match.group("account"), access_point_region)+ if access_point_region else None)# Pass the original (pre-rewrite) URI as signed_path so a presigned# virtual-hosted URL, which signed the canonical URI without the bucket,# verifies against what the client actually signed.return await _get_module("s3").handle_request(method, vhost_path, headers, body, query_params, signed_path=path,- access_point_region=access_point_region)+ access_point_region=access_point_region,+ access_point=access_point)except Exception as e:logger.exception("Error handling virtual-hosted S3 request: %s", e)from xml.sax.saxutils import escape as _xml_escdiff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex a9c27666..ce17f6fc 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -114,6 +114,8 @@ _mrap_operations = AccountScopedDict()# {Name, Bucket, BucketAccountId, Alias, CreationDate, NetworkOrigin, VpcConfiguration,# PublicAccessBlockConfiguration, Policy, Tags}_access_points = AccountRegionScopedDict()+# The access point record a data-plane request came through, while it is handled.+_request_access_point: contextvars.ContextVar[dict | None] = contextvars.ContextVar("s3_access_point", default=None)# Object Lambda Access Points, by name within an account and region:# {Name, Alias: {Value, Status}, CreationDate, Configuration, Policy, PublicAccessBlockConfiguration}@@ -1017,7 +1019,12 @@ def _acl_grants(stored_xml: str | None, grantee: str = "URI") -> list[tuple[str,def _public_access_blocked(owner_account: str, bucket_name: str, setting: str) -> bool:- """Whether the bucket's Public Access Block turns *setting* on, e.g. ``IgnorePublicAcls``."""+ """Whether the bucket's or the request's access point's Public Access Block turns *setting* on."""+ access_point = _request_access_point.get()+ # An access point's BlockPublicPolicy does not cover the bucket's policy.+ if access_point and access_point["Bucket"] == bucket_name and setting != "BlockPublicPolicy" and \+ access_point["PublicAccessBlockConfiguration"].get(setting):+ return Truerecord = _buckets.get_scoped(owner_account, None, bucket_name) or {}stored = record.get("_public_access_block")if not stored:@@ -2367,9 +2374,11 @@ async def handle_request(enforce_bucket_region: bool = True,internal: bool = False,access_point_region: str | None = None,+ access_point: dict | None = None,) -> tuple:- """``access_point_region`` is set for a request that came through an access- point host; the region check then compares against the access point."""+ """``access_point_region`` and ``access_point`` are set for a request that came+ through an access point host; the region check then compares against the+ access point."""bucket, key = _parse_bucket_key(path, headers)# A virtual-hosted request is rewritten to path-style before it reaches here@@ -2408,7 +2417,7 @@ async def handle_request(account, access_point_region, record = resolvedif account != get_account_id():return _error("AccessDenied", "Access Denied", 403, f"/{bucket}")- bucket = record["Bucket"]+ bucket, access_point = record["Bucket"], recordheaders, denied = _resolve_copy_source_alias(headers)if denied is not None:return denied@@ -2423,7 +2432,11 @@ async def handle_request(resp_headers.setdefault("x-amz-id-2", base64.b64encode(os.urandom(48)).decode())return status, resp_headers, resp_body- result = _dispatch(method, bucket, key, headers, body, query_params)+ token = _request_access_point.set(access_point)+ try:+ result = _dispatch(method, bucket, key, headers, body, query_params)+ finally:+ _request_access_point.reset(token)status, resp_headers, resp_body = resultresp_headers.setdefault("x-amz-request-id", new_uuid())diff --git a/tests/test_s3_access_points.py b/tests/test_s3_access_points.pyindex ba51672c..b2ea1878 100644--- a/tests/test_s3_access_points.py+++ b/tests/test_s3_access_points.py@@ -263,6 +263,44 @@ def test_access_point_alias_upload_permission_contract(assert body.read() == b"via alias"+def _status(call):+ try:+ return call()["ResponseMetadata"]["HTTPStatusCode"]+ except ClientError as exc:+ return exc.response["ResponseMetadata"]["HTTPStatusCode"], exc.response["Error"]["Code"]+++def test_access_point_block_public_acls_refuses_public_acl_writes():+ """An access point's BlockPublicAcls refuses public ACLs sent through it, whatever the bucket's settings;+ its BlockPublicPolicy leaves a bucket policy sent through it alone."""+ s3, ctl = _client("s3", "us-east-1"), _client("s3control", "us-east-1")+ name = f"ap-acl-{_uid()}"+ all_off = {k: False for k in ("BlockPublicAcls", "IgnorePublicAcls", "BlockPublicPolicy", "RestrictPublicBuckets")}+ s3.create_bucket(Bucket=name, ObjectOwnership="BucketOwnerPreferred")+ s3.put_public_access_block(Bucket=name, PublicAccessBlockConfiguration=all_off)+ s3.put_object(Bucket=name, Key="k.txt", Body=b"hello")+ blocking = ctl.create_access_point(AccountId=ACCOUNT, Name=f"ap-on-{_uid()}", Bucket=name)+ open_ap = ctl.create_access_point(+ AccountId=ACCOUNT, Name=f"ap-off-{_uid()}", Bucket=name, PublicAccessBlockConfiguration=all_off)+ public_policy = json.dumps({"Version": "2012-10-17", "Statement": [{+ "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": f"arn:aws:s3:::{name}/*"}]})+ try:+ denied = (403, "AccessDenied")+ for target in (blocking["Alias"], blocking["AccessPointArn"]):+ assert _status(lambda: s3.put_object(Bucket=target, Key="w", Body=b"x", ACL="public-read")) == denied+ assert _status(lambda: s3.put_object_acl(Bucket=target, Key="k.txt", ACL="public-read")) == denied+ assert _status(lambda: s3.put_object(Bucket=target, Key="w", Body=b"x", ACL="private")) == 200+ assert _status(lambda: s3.put_bucket_policy(Bucket=target, Policy=public_policy)) == 204+ for target in (open_ap["Alias"], open_ap["AccessPointArn"], name):+ assert _status(lambda: s3.put_object(Bucket=target, Key="w", Body=b"x", ACL="public-read")) == 200+ finally:+ for ap in (blocking, open_ap):+ ctl.delete_access_point(AccountId=ACCOUNT, Name=ap["AccessPointArn"].rsplit("/", 1)[1])+ for obj in s3.list_objects_v2(Bucket=name).get("Contents", []):+ s3.delete_object(Bucket=name, Key=obj["Key"])+ s3.delete_bucket(Bucket=name)++def test_access_point_alias_from_another_account_is_denied(access_point):_name, created = access_pointother = _client("s3", "us-east-1", account_key="111122223333")