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): check access point requests on the access point and bucket (#2357)
iot-rocketf9e12f6cc369
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e127dc35..1720ce65 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **CloudFront — VPC origins** — `CreateVpcOrigin`, `GetVpcOrigin`, `UpdateVpcOrigin`, `DeleteVpcOrigin` and `ListVpcOrigins` replace the empty `ListVpcOrigins` stub, so Terraform's `aws_cloudfront_vpc_origin` and a distribution's `vpc_origin_config` apply. As on AWS, a create, update or delete answers `Deploying`; MiniStack then finishes it at once, so the next read shows `Deployed` with the next `ETag`, or 404 after a delete. Names are unique per account, endpoints are not, and an origin a distribution names can't be deleted or changed. Validation, its order, the `TLSv1`/`TLSv1.1`/`TLSv1.2` default, `IpAddressType`, the list paging (no `Marker` or `IsTruncated`) and the IAM resources follow AWS captures. The endpoint has to be a load balancer or instance that exists in MiniStack, and viewer requests are not routed to it. Contributed by @kharabasz.### Fixed+- **Auth — requests through an S3 access point are checked on the access point and its bucket** — under `AUTH=true` a request through an access point alias was checked on `arn:aws:s3:::<alias>`, so a policy naming the bucket or the access point refused it, and a request through the access point ARN was checked on the bucket only; both are now checked on the access point and on its bucket, each with `s3:DataAccessPointArn`, `s3:DataAccessPointAccount` and `s3:AccessPointNetworkOrigin`, and the bucket policy applies. Contributed by @iot-rocket.- **S3 Control — Multi-Region Access Point requests authorize the operation they run** — the action was read from the end of the path, so an MRAP named `policy` was authorized as its policy and a trailing slash after `/policy` or `/routes` was authorized for that operation and served as `GetMultiRegionAccessPoint`; the action now comes from the route the handler serves, a method a resource lacks answers 405 `MethodNotAllowed` with `Method` and `ResourceType`, and a path S3 Control cannot parse 400 `InvalidURI`. Contributed by @iot-rocket.- **S3 Control — access point requests authorize the operation they run** — access point and Object Lambda Access Point requests were authorized by a second reading of the path, so a POST on a policy returned it, an extra segment or a double slash deleted the Object Lambda Access Point or set its policy without the action, and an access point named `policy` was authorized as its policy; the action now comes from the route the handler serves, a method a resource lacks answers 405 `MethodNotAllowed` with `Method` and `ResourceType`, and a path S3 Control cannot parse 400 `InvalidURI`. Contributed by @iot-rocket.- **Lambda — the local Node executor's SDK stubs sign their calls** — the `@aws-sdk/client-lambda` stub and the JSON-RPC `@aws-sdk/client-*` stubs sent their requests without credentials, so a call landed in the default account whatever account the function belongs to, and under `AUTH=true` it ran as the account root. They now sign with the function's credentials, as the real SDK does: with `AUTH` unset a call lands in the function's own account, under `AUTH=true` it runs as the execution role. Contributed by @iot-rocket.diff --git a/ministack/app.py b/ministack/app.pyindex 0a76c45e..c1268e41 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -2233,7 +2233,7 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: dif 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`.- access_point_region = None+ access_point_region = access_point_alias = Noneap_match = _ACCESS_POINT_HOST_RE.match(bucket)s3 = _get_module("s3")if ap_match and s3.signed_service(headers, query_params) == "s3-object-lambda":@@ -2265,6 +2265,8 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: dif ap_error:return ap_errorbucket, access_point_region = ap_bucket, ap_region+ access_point_alias = s3.resolve_access_point(ap_match.group("name"), ap_match.group("account"),+ ap_region)["Alias"]# CloudFront KVS data-plane clients (boto3 cloudfront-keyvaluestore with# inject_host_prefix=False) hit ministack with host=localhost and path# prefixed by /key-value-stores/. Host-name exclusion above doesn't fire,@@ -2297,27 +2299,34 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: dfrom ministack.core.iam_actions import (_s3_action,extract_resource_arn,+ s3_access_point_resources,s3_additional_checks,s3_service_context,)- s3_action = _s3_action(method, vhost_path, query_params)+ # An access point ARN host is authorized as its alias.+ iam_path = vhost_path if access_point_alias is None else f"/{access_point_alias}{vhost_path[len(bucket) + 1:]}"+ s3_action = _s3_action(method, iam_path, query_params)# x-amz-* headers hoisted into the query string count as the headers they stand for.s3_headers = s3._merge_hoisted_amz_headers(headers, query_params)if s3_action:- s3_resource = extract_resource_arn("s3", method, vhost_path, s3_headers, body, query_params, "", "")- denied = _enforce_data_plane(- "s3", f"s3:{s3_action}", headers, query_params, "", resource_arn=s3_resource,- service_context=s3_service_context(f"s3:{s3_action}", query_params, vhost_path, s3_headers),- )- if denied:- return denied- # A copy also reads its source, a batch delete is one check per- # key, an attributes call is a pair, a governance bypass its own action.- for extra_action, extra_arn in s3_additional_checks(method, vhost_path, s3_headers, body, query_params):- denied = _enforce_data_plane("s3", extra_action, headers, query_params, "", resource_arn=extra_arn)+ s3_resource = extract_resource_arn("s3", method, iam_path, s3_headers, body, query_params, "", "")+ service_context = s3_service_context(f"s3:{s3_action}", query_params, iam_path, s3_headers)+ for resource, keys in s3_access_point_resources(s3_resource):+ denied = _enforce_data_plane(+ "s3", f"s3:{s3_action}", headers, query_params, "", resource_arn=resource,+ service_context={**service_context, **keys},+ )if denied:return denied+ # A copy also reads its source, a batch delete is one check per+ # key, an attributes call is a pair, a governance bypass its own action.+ for extra_action, extra_arn in s3_additional_checks(method, iam_path, s3_headers, body, query_params):+ for resource, keys in s3_access_point_resources(extra_arn):+ denied = _enforce_data_plane("s3", extra_action, headers, query_params, "", resource_arn=resource,+ service_context=keys)+ if denied:+ return deniedtry:# The access point an ARN host names, for its Block Public Access settings.@@ -2868,6 +2877,7 @@ async def _dispatch_service_request(extract_resource_arn,logs_service_context,request_tag_context,+ s3_access_point_resources,s3_service_context,)from ministack.core.iam_evaluator import AuthError, enforce, pin_request_caller@@ -2933,10 +2943,15 @@ async def _dispatch_service_request(iam_action = item_action # named in the AccessDenied messagebreakelse:- denied = enforce(- access_key, iam_action, service, region,- resource_arn=resource_arn, service_context=service_context,- )+ # Through an S3 access point alias the check is made on the access point and on its bucket.+ for checked_arn, keys in (s3_access_point_resources(resource_arn) if service == "s3"+ else [(resource_arn, {})]):+ denied = enforce(+ access_key, iam_action, service, region,+ resource_arn=checked_arn, service_context={**service_context, **keys},+ )+ if denied:+ break# A malformed Logs tagging ARN fails validation ahead of a policy denial.if service == "logs" and logs_validation_error is not None and not isinstance(denied, AuthError):return logs_validation_error@@ -2946,8 +2961,13 @@ async def _dispatch_service_request(from ministack.core.iam_actions import s3_additional_checkss3_headers = _get_module("s3")._merge_hoisted_amz_headers(headers, query_params)- for extra_action, extra_arn in s3_additional_checks(method, path, s3_headers, body, routing_params):- denied = enforce(access_key, extra_action, service, region, resource_arn=extra_arn)+ extra_checks = [(extra_action, checked_arn, keys)+ for extra_action, extra_arn in s3_additional_checks(method, path, s3_headers, body,+ routing_params)+ for checked_arn, keys in s3_access_point_resources(extra_arn)]+ for extra_action, checked_arn, keys in extra_checks:+ denied = enforce(access_key, extra_action, service, region, resource_arn=checked_arn,+ service_context=keys)if denied:iam_action = extra_actionbreakdiff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex 989b7856..2b9088ec 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -434,6 +434,20 @@ def s3_additional_checks(method: str, path: str, headers: dict, body: bytes,return checks+def s3_access_point_resources(resource_arn: str) -> list[tuple[str, dict]]:+ """``(resource ARN, condition keys)`` an S3 check is made on, the access point and its bucket for an alias."""+ from ministack.services import s3 as s3_svc++ alias, sep, key = resource_arn.removeprefix("arn:aws:s3:::").partition("/")+ access_point = s3_svc.access_point_for_alias(alias) if resource_arn.startswith("arn:aws:s3:::") else None+ if access_point is None:+ return [(resource_arn, {})]+ access_point_arn, bucket, keys = access_point+ if sep:+ return [(f"{access_point_arn}/object/{key}", keys), (f"arn:aws:s3:::{bucket}/{key}", keys)]+ return [(access_point_arn, keys), (f"arn:aws:s3:::{bucket}", keys)]++# Lambda REST path → IAM actiondef _lambda_action(method: str, path: str) -> str | None:parts = [p for p in path.split("/") if p]diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex 280a0020..49b429de 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -191,6 +191,19 @@ def resolve_access_point_alias(alias: str):_ACCESS_POINT_ALIAS_SUFFIX = "-s3alias"+def access_point_for_alias(alias: str) -> tuple[str, str, dict] | None:+ """``(access point ARN, bucket, condition keys)`` of an alias in the caller's account, for IAM checks."""+ if not alias.endswith(_ACCESS_POINT_ALIAS_SUFFIX):+ return None+ resolved = resolve_access_point_alias(alias)+ if resolved is None or resolved[0] != get_account_id():+ return None+ account, region, record = resolved+ arn = access_point_arn(record["Name"], account, region)+ return arn, record["Bucket"], {"s3:DataAccessPointArn": arn, "s3:DataAccessPointAccount": account,+ "s3:AccessPointNetworkOrigin": record["NetworkOrigin"]}++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", "")diff --git a/tests/test_s3_access_points.py b/tests/test_s3_access_points.pyindex 15659126..3e8aeab0 100644--- a/tests/test_s3_access_points.py+++ b/tests/test_s3_access_points.py@@ -386,6 +386,115 @@ def test_access_point_alias_from_another_account_is_denied(access_point):assert exc.value.response["Error"]["Code"] == "AccessDenied"+def _access_point_policy(bucket, access_point_arn, grant, deny=None, condition=None):+ """An identity policy allowing reads and copies on ``grant`` ("bucket", "access point" or "both")."""+ arns = {"bucket": [f"arn:aws:s3:::{bucket}", f"arn:aws:s3:::{bucket}/*"],+ "access point": [access_point_arn, f"{access_point_arn}/object/*"]}+ resources = arns["bucket"] + arns["access point"] if grant == "both" else arns[grant]+ statements = [{"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:ListBucket"],+ "Resource": resources}]+ if deny or condition:+ statements.append({"Effect": "Deny", "Action": ["s3:GetObject", "s3:ListBucket"],+ "Resource": arns[deny] if deny else "*", **({"Condition": condition} if condition else {})})+ return {"Version": "2012-10-17", "Statement": statements}+++def _assert_access(auth_enabled, allowed, call):+ """Under AUTH a refused call answers 403 AccessDenied; anything else succeeds."""+ if auth_enabled and not allowed:+ with pytest.raises(ClientError) as exc:+ call()+ error = exc.value.response+ assert (error["Error"]["Code"], error["ResponseMetadata"]["HTTPStatusCode"]) == ("AccessDenied", 403)+ else:+ call()++[email protected]_contract[email protected]("via", ["AccessPointArn", "Alias"])[email protected]("grant, deny, allowed", [+ ("both", None, True),+ ("bucket", None, False),+ ("access point", None, False),+ ("both", "access point", False),+ ("both", "bucket", False),+], ids=["both", "bucket-only", "access-point-only", "deny-access-point", "deny-bucket"])+def test_access_point_request_needs_access_point_and_bucket_contract(auth_enabled, iam_user, bucket, access_point,+ via, grant, deny, allowed):+ """Through an access point a read and a listing are checked on the access point and on its bucket."""+ _name, created = access_point+ client = iam_user(policy=_access_point_policy(bucket, created["AccessPointArn"], grant, deny)).client("s3")+ target = created[via]+ _assert_access(auth_enabled, allowed, lambda: client.get_object(Bucket=target, Key="k.txt"))+ _assert_access(auth_enabled, allowed, lambda: client.list_objects_v2(Bucket=target))+ _assert_access(auth_enabled, grant != "access point" and deny != "bucket",+ lambda: client.get_object(Bucket=bucket, Key="k.txt"))++[email protected]_contract[email protected]("via", ["AccessPointArn", "Alias"])[email protected]("key, condition_value, through_access_point, through_bucket", [+ ("s3:DataAccessPointArn", "arn", False, True),+ ("s3:DataAccessPointAccount", ACCOUNT, False, True),+ ("s3:AccessPointNetworkOrigin", "Internet", False, True),+ ("s3:ExistingObjectTag/class", "secret", False, False),+ ("s3:DataAccessPointArn", None, True, False),+], ids=["arn", "account", "network-origin", "object-tag", "arn-absent"])+def test_access_point_condition_keys_contract(auth_enabled, iam_user, bucket, access_point, via, key,+ condition_value, through_access_point, through_bucket):+ """A request through an access point carries its ARN, account and network origin, and the object's tags."""+ _name, created = access_point+ _client("s3", "us-east-1").put_object_tagging(Bucket=bucket, Key="k.txt",+ Tagging={"TagSet": [{"Key": "class", "Value": "secret"}]})+ arn = created["AccessPointArn"]+ condition = ({"Null": {key: "true"}} if condition_value is None+ else {"StringEquals": {key: arn if condition_value == "arn" else condition_value}})+ client = iam_user(policy=_access_point_policy(bucket, arn, "both", condition=condition)).client("s3")+ _assert_access(auth_enabled, through_access_point, lambda: client.get_object(Bucket=created[via], Key="k.txt"))+ _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]("condition, through_bucket", [(False, False), (True, True)], ids=["deny", "deny-on-arn-key"])+def test_access_point_request_meets_the_bucket_policy_contract(auth_enabled, iam_user, bucket, access_point, via,+ condition, through_bucket):+ """The bucket policy applies through an access point and sees its ARN."""+ _name, created = access_point+ arn = created["AccessPointArn"]+ user = iam_user(policy=_access_point_policy(bucket, arn, "both"))+ statement = {"Effect": "Deny", "Principal": {"AWS": user.arn}, "Action": "s3:GetObject",+ "Resource": f"arn:aws:s3:::{bucket}/*"}+ if condition:+ statement["Condition"] = {"StringEquals": {"s3:DataAccessPointArn": arn}}+ _client("s3", "us-east-1").put_bucket_policy(+ Bucket=bucket, Policy=json.dumps({"Version": "2012-10-17", "Statement": [statement]}))+ client = user.client("s3")+ _assert_access(auth_enabled, False, lambda: client.get_object(Bucket=created[via], Key="k.txt"))+ _assert_access(auth_enabled, through_bucket, lambda: client.get_object(Bucket=bucket, Key="k.txt"))++[email protected]_contract[email protected]("grant, deny, condition, allowed", [+ ("both", None, False, True),+ ("bucket", None, False, False),+ ("both", "access point", False, False),+ ("both", None, True, False),+], ids=["both", "bucket-only", "deny-access-point", "deny-on-arn-key"])+def test_access_point_alias_copy_source_contract(auth_enabled, iam_user, bucket, access_point, grant, deny,+ condition, allowed):+ """A copy source named by an alias is read through its access point."""+ _name, created = access_point+ arn = created["AccessPointArn"]+ policy = _access_point_policy(bucket, arn, grant, deny,+ {"StringEquals": {"s3:DataAccessPointArn": arn}} if condition else None)+ client = iam_user(policy=policy).client("s3")+ _assert_access(auth_enabled, allowed, lambda: client.copy_object(+ Bucket=bucket, Key="copy.txt", CopySource={"Bucket": created["Alias"], "Key": "k.txt"}))+ _assert_access(auth_enabled, True, lambda: client.copy_object(+ Bucket=bucket, Key="copy.txt", CopySource={"Bucket": bucket, "Key": "k.txt"}))++def test_access_point_control_invalid_name(bucket):ctl = _client("s3control", "us-east-1")with pytest.raises(ClientError) as exc: