Skip to content

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

fix(s3): honour object ACL grants for another account's reads (#2198)

iot-rocket101959022da4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 001f64fa..aee917cc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **S3 — object ACL grants answer another account's read** — a bucket owned by another account refused every read that only the object ACL granted: the ACL was looked up under the wrong version, and a grant to the caller's canonical ID was never read. With ACLs enabled, a `READ` grant to the account or a group now opens `GetObject` and `HeadObject` of the version it was set on, `?versionId=` included, and `READ_ACP` opens `GetObjectAcl`; a grant to one account is not public, so Block Public Access leaves it in force. Contributed by @iot-rocket.
- **CloudWatch — `DescribeAlarms` and `DescribeAlarmHistory` paging** — both returned at most `MaxRecords` items (default 100) and never a `NextToken`, so a paginator stopped after the first page; they now return a `NextToken` while more items match, default to 50 items and refuse a `MaxRecords` outside 1 to 100 with `ValidationError`. `DescribeAlarms` now lists metric and composite alarms in one name-ordered sequence that `MaxRecords` counts together, and `DescribeAlarmHistory` lists the newest items first unless `ScanBy` is `TimestampAscending`. `DescribeAlarms` without `AlarmTypes` now returns metric alarms only, as on AWS; composite alarms need `AlarmTypes=["CompositeAlarm"]`. Contributed by @iot-rocket.
- **CloudWatch Logs — a log group's resource policy by `resourceArn` alone** — `PutResourcePolicy` and `DeleteResourcePolicy` refused a `resourceArn` without `policyName`; they now take it, store the group's policy without a name and with a counting `revisionId`, and answer a request with neither field or a revision conflict with AWS's errors. `AWS::Logs::LogGroup` now creates, rewrites and removes the group's own policy from `ResourcePolicyDocument`. Contributed by @iot-rocket.
- **CloudTrail — trail read-backs and recording switched on at runtime** — `GetTrail` and `DescribeTrails` returned the stored `IsLogging`, `_StartedAt` and `_StoppedAt` keys and empty `S3KeyPrefix` and `SnsTopicName` members, and `GetTrailStatus` left out the six deprecated string members and moved `StopLoggingTime` when a stopped trail was stopped again; they now answer in AWS's shapes, with the start and stop times in milliseconds, and keep the last stop time. Recording switched on through `/_ministack/config` began only after the first CloudTrail API call and now starts with the next request. Contributed by @iot-rocket.
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 064243ba..718ef6a4 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -769,10 +769,13 @@ _ACL_GROUP_AUTHENTICATED = "http://acs.amazonaws.com/groups/global/Authenticated
# The permissions that answer a read and a write, FULL_CONTROL covering both.
_ACL_READ_PERMS = ("READ", "FULL_CONTROL")
_ACL_WRITE_PERMS = ("WRITE", "FULL_CONTROL")
+_ACL_READ_ACP_PERMS = ("READ_ACP", "FULL_CONTROL")
+# Object reads an object ACL grants nothing for: READ covers the data, READ_ACP the ACL.
+_ACL_UNGRANTED_OBJECT_READS = ("uploadId", "annotation", "tagging", "retention", "legal-hold", "attributes")
-def _acl_group_grants(stored_xml: str | None) -> list[tuple[str, str]]:
- """``(group URI, permission)`` for every Group grant in a stored ACL."""
+def _acl_grants(stored_xml: str | None, grantee: str = "URI") -> list[tuple[str, str]]:
+ """``(grantee, permission)`` for every grant in a stored ACL naming a group ``URI`` or a canonical ``ID``."""
if not stored_xml:
return []
try:
@@ -783,14 +786,14 @@ def _acl_group_grants(stored_xml: str | None) -> list[tuple[str, str]]:
for grant in root.iter():
if not grant.tag.endswith("Grant"):
continue
- uri = permission = ""
+ value = permission = ""
for child in grant.iter():
- if child.tag.endswith("URI") and child.text:
- uri = child.text.strip()
+ if child.tag.rsplit("}", 1)[-1] == grantee and child.text:
+ value = child.text.strip()
elif child.tag.endswith("Permission") and child.text:
permission = child.text.strip()
- if uri and permission:
- grants.append((uri, permission))
+ if value and permission:
+ grants.append((value, permission))
return grants
@@ -850,21 +853,26 @@ def _foreign_bucket_allows(owner_account: str, bucket_name: str, key: str,
"""Whether a caller who does not own the bucket may have this request.
The owner's grants decide it: a Group grant on the bucket or the object
- ACL, or an allow in the bucket policy. Nothing granted means the request
- is denied, which is S3's default for a bucket nobody has opened up.
+ ACL, a grant to the caller's canonical ID on the object ACL, or an allow
+ in the bucket policy. Nothing granted means the request is denied, which
+ is S3's default for a bucket nobody has opened up.
"""
+ object_acl, object_wants = _foreign_object_acl(owner_account, bucket_name, key, method, query_params)
+ caller_id = _canonical_owner_id(caller) if caller else ""
+ if any(grantee == caller_id and permission in object_wants
+ for grantee, permission in _acl_grants(object_acl, "ID")):
+ # A grant to one account is not public, so Block Public Access leaves it alone.
+ return True
if _public_access_blocked(owner_account, bucket_name):
return False
wants = _ACL_READ_PERMS if method in ("GET", "HEAD") else _ACL_WRITE_PERMS
groups = [_ACL_GROUP_ALL_USERS] if not caller else [
_ACL_GROUP_ALL_USERS, _ACL_GROUP_AUTHENTICATED]
- acls = [_bucket_acl.get_scoped(owner_account, None, bucket_name)]
- if key:
- acls.append(_object_acl.get_scoped(owner_account, None, (bucket_name, key, "")))
- for stored in acls:
- for uri, permission in _acl_group_grants(stored):
- if uri in groups and permission in wants:
+ for stored, granted in ((_bucket_acl.get_scoped(owner_account, None, bucket_name), wants),
+ (object_acl, object_wants)):
+ for uri, permission in _acl_grants(stored):
+ if uri in groups and permission in granted:
return True
policy = _bucket_policies.get_scoped(owner_account, None, bucket_name)
@@ -886,6 +894,20 @@ def _foreign_bucket_allows(owner_account: str, bucket_name: str, key: str,
return False
+def _foreign_object_acl(owner_account: str, bucket_name: str, key: str, method: str,
+ query_params: dict) -> tuple[str | None, tuple[str, ...]]:
+ """The stored ACL of the object version a read addresses, and the permissions that grant the read."""
+ if not key or method not in ("GET", "HEAD") or any(q in query_params for q in _ACL_UNGRANTED_OBJECT_READS):
+ return None, ()
+ bucket = _buckets.get_scoped(owner_account, None, bucket_name)
+ if bucket is None or _bucket_owner_enforced(bucket):
+ # BucketOwnerEnforced disables ACLs: only policies grant access.
+ return None, ()
+ version_id = _resolve_subresource_version(query_params, bucket, key)
+ wants = _ACL_READ_ACP_PERMS if "acl" in query_params else _ACL_READ_PERMS
+ return _object_acl.get_scoped(owner_account, None, (bucket_name, key, version_id)), wants
+
+
def _request_access_key(method: str, key: str, headers: dict, query_params: dict,
body: bytes) -> str:
"""The caller's access key, including the one a browser POST signs into its
@@ -2126,14 +2148,14 @@ def _dispatch(method: str, bucket: str, key: str, headers: dict, body: bytes, qu
# ---------------------------------------------------------------------------
-def _canonical_owner_id() -> str:
- """The S3 canonical user ID for the current account.
+def _canonical_owner_id(account_id: str = "") -> str:
+ """The S3 canonical user ID for *account_id*, the current account by default.
Real S3 reports an opaque 64-character hex canonical ID (not the account
ID) and returns the same value from every Owner / CanonicalUser field
(ListBuckets, GetBucketAcl, GetObjectAcl, object listings). MiniStack
derives a stable one from the account so those fields agree (#1459)."""
- return hashlib.sha256(get_account_id().encode()).hexdigest()
+ return hashlib.sha256((account_id or get_account_id()).encode()).hexdigest()
def _list_buckets(query_params=None):
diff --git a/tests/test_s3.py b/tests/test_s3.py
index e5f4fe9f..0c03f58c 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -5206,6 +5206,99 @@ def test_s3_put_object_canned_acl_versioned(s3):
s3.delete_bucket(Bucket=bucket)
+def _grant_object_acl(client, bucket, key, grants, **kwargs):
+ """Replace an object's ACL with the owner's FULL_CONTROL plus ``(canonical ID, permission)`` grants."""
+ owner_id = client.list_buckets()["Owner"]["ID"]
+ client.put_object_acl(Bucket=bucket, Key=key, **kwargs, AccessControlPolicy={
+ "Owner": {"ID": owner_id},
+ "Grants": [{"Grantee": {"Type": "CanonicalUser", "ID": grantee}, "Permission": permission}
+ for grantee, permission in [(owner_id, "FULL_CONTROL"), *grants]],
+ })
+
+
+def _acl_enabled_bucket(client, bucket):
+ """A bucket with ACLs enabled (BucketOwnerPreferred), so object ACLs take effect."""
+ client.create_bucket(Bucket=bucket)
+ client.put_bucket_ownership_controls(
+ Bucket=bucket, OwnershipControls={"Rules": [{"ObjectOwnership": "BucketOwnerPreferred"}]})
+
+
+def _denied(call, **kwargs):
+ with pytest.raises(ClientError) as exc:
+ call(**kwargs)
+ return exc.value.response["Error"]["Code"] in ("AccessDenied", "403")
+
+
+def test_s3_object_acl_grant_opens_reads_to_another_account(s3):
+ """Another account's READ grant opens GetObject and HeadObject only; BucketOwnerEnforced drops it."""
+ owner, reader = _s3_account("111111111111"), _s3_account("222222222222")
+ bucket = f"acl-xacct-{uuid.uuid4().hex[:8]}"
+ _acl_enabled_bucket(owner, bucket)
+ try:
+ owner.put_object(Bucket=bucket, Key="k", Body=b"one")
+ assert _denied(reader.get_object, Bucket=bucket, Key="k")
+
+ _grant_object_acl(owner, bucket, "k", [(reader.list_buckets()["Owner"]["ID"], "READ")])
+ assert reader.get_object(Bucket=bucket, Key="k")["Body"].read() == b"one"
+ assert reader.head_object(Bucket=bucket, Key="k")["ContentLength"] == 3
+ assert _denied(reader.get_object_acl, Bucket=bucket, Key="k")
+ assert _denied(reader.get_object_tagging, Bucket=bucket, Key="k")
+ assert _denied(reader.put_object, Bucket=bucket, Key="k", Body=b"two")
+
+ owner.put_public_access_block(Bucket=bucket, PublicAccessBlockConfiguration={
+ "BlockPublicAcls": True, "IgnorePublicAcls": True,
+ "BlockPublicPolicy": True, "RestrictPublicBuckets": True})
+ assert reader.get_object(Bucket=bucket, Key="k")["Body"].read() == b"one"
+
+ owner.put_bucket_ownership_controls(
+ Bucket=bucket, OwnershipControls={"Rules": [{"ObjectOwnership": "BucketOwnerEnforced"}]})
+ assert _denied(reader.get_object, Bucket=bucket, Key="k")
+ finally:
+ owner.delete_object(Bucket=bucket, Key="k")
+ owner.delete_bucket(Bucket=bucket)
+
+
+def test_s3_object_acl_grant_to_another_account_follows_the_version(s3):
+ """The grant stays on the version current when it was set; READ_ACP opens that version's ACL."""
+ owner, reader = _s3_account("111111111111"), _s3_account("222222222222")
+ reader_id = reader.list_buckets()["Owner"]["ID"]
+ bucket = f"acl-xacct-ver-{uuid.uuid4().hex[:8]}"
+ _acl_enabled_bucket(owner, bucket)
+ try:
+ owner.put_bucket_versioning(Bucket=bucket, VersioningConfiguration={"Status": "Enabled"})
+ v1 = owner.put_object(Bucket=bucket, Key="k", Body=b"one")["VersionId"]
+ _grant_object_acl(owner, bucket, "k", [(reader_id, "READ")])
+ assert reader.get_object(Bucket=bucket, Key="k")["Body"].read() == b"one"
+
+ owner.put_object(Bucket=bucket, Key="k", Body=b"two")
+ assert _denied(reader.get_object, Bucket=bucket, Key="k")
+ assert reader.get_object(Bucket=bucket, Key="k", VersionId=v1)["Body"].read() == b"one"
+ assert _denied(reader.get_object_acl, Bucket=bucket, Key="k", VersionId=v1)
+
+ _grant_object_acl(owner, bucket, "k", [(reader_id, "READ_ACP")], VersionId=v1)
+ grants = reader.get_object_acl(Bucket=bucket, Key="k", VersionId=v1)["Grants"]
+ assert {(g["Grantee"]["ID"], g["Permission"]) for g in grants} >= {(reader_id, "READ_ACP")}
+ finally:
+ _purge_foreign(owner, bucket)
+
+
+def test_s3_public_read_object_acl_opens_reads_to_another_account(s3):
+ """A public-read object ACL answers another account's read until IgnorePublicAcls is set."""
+ owner, reader = _s3_account("111111111111"), _s3_account("222222222222")
+ bucket = f"acl-xacct-pub-{uuid.uuid4().hex[:8]}"
+ _acl_enabled_bucket(owner, bucket)
+ try:
+ owner.put_object(Bucket=bucket, Key="k", Body=b"one", ACL="public-read")
+ assert reader.get_object(Bucket=bucket, Key="k")["Body"].read() == b"one"
+
+ owner.put_public_access_block(
+ Bucket=bucket, PublicAccessBlockConfiguration={"IgnorePublicAcls": True})
+ assert _denied(reader.get_object, Bucket=bucket, Key="k")
+ finally:
+ owner.delete_object(Bucket=bucket, Key="k")
+ owner.delete_bucket(Bucket=bucket)
+
+
def test_s3_post_object_acl_field(s3):
"""The POST form names its canned-ACL field `acl`; it applies to the
uploaded object like x-amz-acl does on PutObject."""