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): honor canned ACLs on buckets and key object ACLs by version (#1434)
Andrew Gaul170cac8e2d28
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6a18c2ce..fd3abf1a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed- **CloudFormation — `AWS::IoT::Policy` updates apply instead of rolling the stack back** — the type had a create and a delete but no update handler, so a stack update fell through to create, hit `ResourceAlreadyExistsException` on the policy it had provisioned itself, and rolled back with the document unchanged: an IoT policy could be deployed once and never edited again. A changed `PolicyDocument` is now a no-interruption update stored as a new policy version and made the default, so `Ref` keeps naming the same policy and `GetPolicy` returns the new document; a changed `PolicyName` is a replacement, creating the policy under the new name and removing the old one. Because IoT caps a policy at five versions, the update prunes the oldest non-default versions before storing a new document, as the CloudFormation handler does on AWS.- **EC2 — instance public IP and DNS reach the SDKs, and generated addresses are addresses** — `DescribeInstances` and `RunInstances` emitted the public address under `publicIpAddress` / `publicDnsName`, which are not the tags the EC2 wire schema defines (`ipAddress` / `dnsName`, per botocore's `ec2-2016-11-15` model), so every SDK dropped both fields silently and `PublicIpAddress` came back absent on instances that had one. They now ride the real tags. Fixing that exposed a second one: `_random_ip` appended two octets whatever it was given, so a one-octet prefix produced `52.55.218` — `AllocateAddress` has been handing back that shape as `PublicIp` all along, and no address parser accepts it. The generator now completes any prefix to four octets. Contributed by @iot-rocket.+- **S3 — canned ACLs are stored, and object ACLs bind to versions** — SDKs send `put-bucket-acl --acl public-read` as an `x-amz-acl` header with an empty body, and `PutBucketAcl` read only the body, so the canned grant vanished and the bucket read back owner-only — a caller that gates anonymous access on the reported grants (S3Proxy's `aws-s3` backend among them) then treated every bucket as private. `CreateBucket`'s `x-amz-acl` was dropped the same way. Both now validate the canned value (`InvalidArgument` otherwise) and store the grants it implies, `log-delivery-write` included, exactly as the object side has since #1322; an XML body must be well-formed (`MalformedACLError`) and a request with neither header nor body answers `MissingSecurityHeader`, as on AWS. Object ACLs are now per-version like tags (#1058): `?versionId=` reads or writes that version's ACL, a fresh version starts from the default policy instead of inheriting its predecessor's, the canned value on `PutObject` sticks to the version that PUT created, and version and bucket deletes drop the stored entries. The browser-POST form names its field `acl` rather than `x-amz-acl`, so it never matched the header list and was discarded; it now applies to the uploaded object. Contributed by @gaul.- **S3 — `CRC64NVME` checksums are computed instead of refused** — CRC-64/NVME is the algorithm current AWS SDKs and the CLI checksum uploads with by default, and MiniStack answered it with `InvalidRequest` ("requires optional native dependencies"), so a stock `aws s3 cp` or `aws s3api put-object` failed before it began unless the caller knew to set `AWS_REQUEST_CHECKSUM_CALCULATION=when_required`. The algorithm is plain arithmetic — the reflected form of polynomial `0xAD93D23594C93659` with all-ones init and xorout — so it is now computed from a byte-at-a-time table in the stdlib, adding no dependency: `PutObject` and `CopyObject` validate a client-supplied `x-amz-checksum-crc64nvme` (`BadDigest` on mismatch) and `GetObject` / `HeadObject` return it under `x-amz-checksum-mode: ENABLED`, typed `FULL_OBJECT`. The tests pin the implementation to the algorithm's published check value (`b"123456789"` → `0xAE8B14860A799888`) and to a bit-at-a-time reference rather than to itself. `CRC32C` still requires the native `google-crc32c` and is still refused.## [1.4.19] — 2026-08-16diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex 8942a700..57c2b8e9 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -84,7 +84,7 @@ _bucket_accelerate_config = AccountScopedDict()_bucket_request_payment_config = AccountScopedDict()_object_tags = AccountScopedDict()-_object_acl = AccountScopedDict() # (bucket, key) -> stored ACL XML string+_object_acl = AccountScopedDict() # (bucket, key, version_id) -> stored ACL XML string_object_versions = AccountScopedDict() # (bucket, key) -> [{version_id, obj_record}, ...]_bucket_object_lock = AccountScopedDict()@@ -1050,7 +1050,7 @@ def _dispatch(if "legal-hold" in query_params:return _get_object_legal_hold(bucket, key)if "acl" in query_params:- return _get_object_acl(bucket, key)+ return _get_object_acl(bucket, key, query_params)if "attributes" in query_params:return _get_object_attributes(bucket, key, headers, query_params)return _get_object(bucket, key, headers, query_params)@@ -1067,7 +1067,7 @@ def _dispatch(if "legal-hold" in query_params:return _put_object_legal_hold(bucket, key, body)if "acl" in query_params:- return _put_object_acl(bucket, key, body, headers)+ return _put_object_acl(bucket, key, body, headers, query_params)if "x-amz-copy-source" in headers:return _copy_object(bucket, key, headers)return _put_object(bucket, key, body, headers)@@ -1166,7 +1166,7 @@ def _dispatch(if "cors" in query_params:return _put_bucket_cors(bucket, body)if "acl" in query_params:- return _put_bucket_acl(bucket, body)+ return _put_bucket_acl(bucket, body, headers)if "website" in query_params:return _put_bucket_website(bucket, body)if "logging" in query_params:@@ -1253,6 +1253,11 @@ def _create_bucket(name: str, body: bytes, headers: dict = None):return _error("InvalidBucketName", "The specified bucket is not valid.", 400, f"/{name}")+ # A canned ACL supplied at CreateBucket time is validated up front and+ # stored below, so GetBucketAcl reflects it instead of dropping it.+ canned_acl = headers.get("x-amz-acl")+ if canned_acl and canned_acl not in _CANNED_BUCKET_ACLS:+ return _error("InvalidArgument", f"Invalid x-amz-acl value: {canned_acl}", 400)if name in _buckets:# Idempotent: same account already owns it — return 200 like real AWSreturn 200, {"Location": f"/{name}"}, b""@@ -1284,6 +1289,8 @@ def _create_bucket(name: str, body: bytes, headers: dict = None):_buckets[name] = {"created": now_iso(), "objects": {}, "region": region}if tags:_bucket_tags[name] = tags+ if canned_acl:+ _bucket_acl[name] = _canned_acl_policy_xml(canned_acl, get_account_id())if headers.get("x-amz-bucket-object-lock-enabled", "").lower() == "true":_bucket_object_lock[name] = {"enabled": True, "default_retention": None}@@ -1326,6 +1333,8 @@ def _delete_bucket(name: str):_bucket_replication.pop(name, None)for k in [k for k in _object_tags if k[0] == name]:del _object_tags[k]+ for k in [k for k in _object_acl if k[0] == name]:+ del _object_acl[k]for k in [k for k in _object_retention if k[0] == name]:del _object_retention[k]for k in [k for k in _object_legal_hold if k[0] == name]:@@ -1754,11 +1763,39 @@ def _get_bucket_acl(name: str):return 200, {"Content-Type": "application/xml"}, body-def _put_bucket_acl(name: str, body: bytes):+def _put_bucket_acl(name: str, body: bytes, headers: dict | None = None):+ headers = headers or {}if name not in _buckets:return _no_such_bucket(name)- if body:- _bucket_acl[name] = body.decode("utf-8", errors="replace")++ # Canned ACL from x-amz-acl header takes precedence and is mutually+ # exclusive with an XML body per the AWS API reference. SDK callers send+ # the canned value as a header with an EMPTY body, so ignoring the header+ # silently dropped every `put-bucket-acl --acl public-read`. Either path+ # stores the resulting policy XML so GetBucketAcl round-trips the value+ # the caller set, matching what real AWS would return.+ canned = headers.get("x-amz-acl")+ if canned:+ if canned not in _CANNED_BUCKET_ACLS:+ return _error("InvalidArgument",+ f"Invalid x-amz-acl value: {canned}", 400)+ _bucket_acl[name] = _canned_acl_policy_xml(canned, get_account_id())+ return 200, {}, b""++ if not body:+ return _error("MissingSecurityHeader",+ "Your request was missing a required header.", 400)+ try:+ # Validate XML well-formedness — real AWS rejects malformed bodies+ # with MalformedACLError. We don't enforce grantee/permission+ # semantics on the data plane, so any well-formed AccessControlPolicy+ # is accepted and round-tripped verbatim.+ fromstring(body)+ except Exception:+ return _error("MalformedACLError",+ "The XML you provided was not well-formed or did not validate "+ "against our published schema.", 400)+ _bucket_acl[name] = body.decode("utf-8", errors="replace")return 200, {}, b""@@ -2634,8 +2671,9 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):return csum_err# A canned ACL supplied at PutObject time is validated up front (an invalid- # value rejects the whole request, as AWS does) and applied below, so- # GetObjectAcl reflects it instead of dropping it. (#1322, rest of defect 9)+ # value rejects the whole request, as AWS does) and applied below once the+ # version id is assigned, so GetObjectAcl reflects it instead of dropping+ # it. (#1322, rest of defect 9)canned_acl = headers.get("x-amz-acl")if canned_acl and canned_acl not in _CANNED_OBJECT_ACLS:return _error("InvalidArgument", f"Invalid x-amz-acl value: {canned_acl}", 400)@@ -2643,8 +2681,6 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):etag = f'"{md5_hash(body)}"'obj = _build_object_record(body, headers, etag=etag, checksums=checksums)bucket["objects"][key] = obj- if canned_acl:- _object_acl[(bucket_name, key)] = _canned_acl_policy_xml(canned_acl, get_account_id())# --- Object Lock headers on PutObject ---_apply_object_lock_from_headers(bucket_name, key, headers)@@ -2697,6 +2733,9 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):if pending_tags is not None:_object_tags[(bucket_name, key, obj.get("version_id"))] = pending_tags+ if canned_acl:+ _object_acl[(bucket_name, key, obj.get("version_id"))] = (+ _canned_acl_policy_xml(canned_acl, get_account_id()))return 200, resp_headers, b""@@ -2848,11 +2887,18 @@ def _post_object(bucket_name: str, body: bytes, headers: dict):"x-amz-object-lock-legal-hold"):if h in fields:synth[h] = fields[h]+ # The POST form names its canned-ACL field `acl` (not `x-amz-acl`).+ if "acl" in fields:+ synth["x-amz-acl"] = fields["acl"]_, sc_err = _resolve_storage_class(synth)if sc_err:return sc_err+ canned_acl = synth.get("x-amz-acl")+ if canned_acl and canned_acl not in _CANNED_OBJECT_ACLS:+ return _error("InvalidArgument", f"Invalid x-amz-acl value: {canned_acl}", 400)+etag = f'"{md5_hash(file_value)}"'obj = _build_object_record(file_value, synth, etag=etag)bucket["objects"][key] = obj@@ -2900,6 +2946,9 @@ def _post_object(bucket_name: str, body: bytes, headers: dict):if pending_tags is not None:_object_tags[(bucket_name, key, version_id)] = pending_tags+ if canned_acl:+ _object_acl[(bucket_name, key, version_id)] = (+ _canned_acl_policy_xml(canned_acl, get_account_id()))location = f"http://{bucket_name}.s3.amazonaws.com/{url_quote(key, safe='/')}"base_resp = {"ETag": etag, "Location": location}@@ -3250,7 +3299,7 @@ def _purge_current_object(bucket_name: str, key: str, bucket: dict):_object_tags.pop((bucket_name, key, None), None)_object_retention.pop((bucket_name, key), None)_object_legal_hold.pop((bucket_name, key), None)- _object_acl.pop((bucket_name, key), None)+ _object_acl.pop((bucket_name, key, None), None)_delete_persisted_object(bucket_name, key)@@ -3306,8 +3355,9 @@ def _delete_object_version(bucket: dict, bucket_name: str, key: str,removed = versions.pop(idx)was_delete_marker = bool(removed.get("is_delete_marker"))- # Per-version tags travel with the version being removed.+ # Per-version tags and ACLs travel with the version being removed._object_tags.pop((bucket_name, key, version_id), None)+ _object_acl.pop((bucket_name, key, version_id), None)if not versions:# History is now empty — drop the index entry and the current object.@@ -3405,7 +3455,7 @@ def _delete_object(bucket_name: str, key: str, headers: dict | None = None,_object_tags.pop((bucket_name, key, None), None)_object_retention.pop((bucket_name, key), None)_object_legal_hold.pop((bucket_name, key), None)- _object_acl.pop((bucket_name, key), None)+ _object_acl.pop((bucket_name, key, None), None)_delete_persisted_object(bucket_name, key)if existed:@@ -3705,13 +3755,13 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):# ----------------------------------------------------------------------------def _resolve_tagging_version(query_params: dict, bucket: dict, key: str):- """Resolve the (key, version_id) pair an Object Tagging op should act on.+def _resolve_subresource_version(query_params: dict, bucket: dict, key: str):+ """Resolve the (key, version_id) pair an object subresource op acts on.- Per AWS, object tags are per-version: when ``?versionId=`` is present the- op targets that specific version; otherwise it targets the current object.- The literal ``versionId=null`` means the pre-versioning object (stored as- ``None`` in our key tuple)."""+ Per AWS, object tags and ACLs are per-version: when ``?versionId=`` is+ present the op targets that specific version; otherwise it targets the+ current object. The literal ``versionId=null`` means the pre-versioning+ object (stored as ``None`` in our key tuple)."""vid = _qp(query_params or {}, "versionId", "")if vid:return None if vid == "null" else vid@@ -3731,7 +3781,7 @@ def _get_object_tagging(bucket_name: str, key: str, query_params: dict | None =f"/{bucket_name}/{key}",)- version_id = _resolve_tagging_version(query_params, bucket, key)+ version_id = _resolve_subresource_version(query_params, bucket, key)tags = _object_tags.get((bucket_name, key, version_id), {})root = Element("Tagging", xmlns=S3_NS)tag_set = SubElement(root, "TagSet")@@ -3764,7 +3814,7 @@ def _put_object_tagging(return _error("MalformedXML", "The XML you provided was not well-formed", 400)if len(tags) > 10:return _error("BadRequest", "Object tags cannot be greater than 10", 400)- version_id = _resolve_tagging_version(query_params, bucket, key)+ version_id = _resolve_subresource_version(query_params, bucket, key)_object_tags[(bucket_name, key, version_id)] = tagsresp_headers = {"Content-Type": "application/xml"}if version_id:@@ -3785,7 +3835,7 @@ def _delete_object_tagging(404,f"/{bucket_name}/{key}",)- version_id = _resolve_tagging_version(query_params, bucket, key)+ version_id = _resolve_subresource_version(query_params, bucket, key)_object_tags.pop((bucket_name, key, version_id), None)resp_headers = {}if version_id:@@ -4063,9 +4113,20 @@ _CANNED_OBJECT_ACLS = {"bucket-owner-full-control",}+# Canned ACLs accepted by CreateBucket / PutBucketAcl `x-amz-acl`: the object+# set minus the object-only variants, plus log-delivery-write (bucket-only).+_CANNED_BUCKET_ACLS = {+ "private",+ "public-read",+ "public-read-write",+ "authenticated-read",+ "log-delivery-write",+}+_ACL_GROUP_ALL_USERS = "http://acs.amazonaws.com/groups/global/AllUsers"_ACL_GROUP_AUTH_USERS = "http://acs.amazonaws.com/groups/global/AuthenticatedUsers"+_ACL_GROUP_LOG_DELIVERY = "http://acs.amazonaws.com/groups/s3/LogDelivery"# Group grants each canned ACL adds on top of the owner's FULL_CONTROL, per the# AWS S3 "Canned ACL" reference. The bucket-owner-* / aws-exec-read variants add@@ -4075,6 +4136,7 @@ _CANNED_ACL_GROUP_GRANTS = {"public-read": [(_ACL_GROUP_ALL_USERS, "READ")],"public-read-write": [(_ACL_GROUP_ALL_USERS, "READ"), (_ACL_GROUP_ALL_USERS, "WRITE")],"authenticated-read": [(_ACL_GROUP_AUTH_USERS, "READ")],+ "log-delivery-write": [(_ACL_GROUP_LOG_DELIVERY, "WRITE"), (_ACL_GROUP_LOG_DELIVERY, "READ_ACP")],}@@ -4127,7 +4189,7 @@ def _default_object_acl_xml() -> bytes:)-def _get_object_acl(bucket_name: str, key: str):+def _get_object_acl(bucket_name: str, key: str, query_params: dict | None = None):bucket = _ensure_bucket(bucket_name)if bucket is None:return _no_such_bucket(bucket_name)@@ -4139,12 +4201,19 @@ def _get_object_acl(bucket_name: str, key: str):f"/{bucket_name}/{key}",)- stored = _object_acl.get((bucket_name, key))+ # ACLs are per-version, like tags: a `?versionId=` reads that version's+ # ACL, and a version that never had one set reads as the default policy.+ version_id = _resolve_subresource_version(query_params, bucket, key)+ stored = _object_acl.get((bucket_name, key, version_id))body = stored.encode("utf-8") if stored else _default_object_acl_xml()- return 200, {"Content-Type": "application/xml"}, body+ resp_headers = {"Content-Type": "application/xml"}+ if version_id:+ resp_headers["x-amz-version-id"] = version_id+ return 200, resp_headers, body-def _put_object_acl(bucket_name: str, key: str, body: bytes, headers: dict):+def _put_object_acl(bucket_name: str, key: str, body: bytes, headers: dict,+ query_params: dict | None = None):bucket = _ensure_bucket(bucket_name)if bucket is None:return _no_such_bucket(bucket_name)@@ -4156,6 +4225,10 @@ def _put_object_acl(bucket_name: str, key: str, body: bytes, headers: dict):f"/{bucket_name}/{key}",)+ # A `?versionId=` sets that specific version's ACL; without it the current+ # version's. Later versions are separate objects and keep their defaults.+ version_id = _resolve_subresource_version(query_params, bucket, key)+# Canned ACL from x-amz-acl header takes precedence and is mutually# exclusive with an XML body per the AWS API reference. Either path# stores the resulting policy XML so GetObjectAcl round-trips the value@@ -4165,7 +4238,8 @@ def _put_object_acl(bucket_name: str, key: str, body: bytes, headers: dict):if canned not in _CANNED_OBJECT_ACLS:return _error("InvalidArgument",f"Invalid x-amz-acl value: {canned}", 400)- _object_acl[(bucket_name, key)] = _canned_acl_policy_xml(canned, get_account_id())+ _object_acl[(bucket_name, key, version_id)] = (+ _canned_acl_policy_xml(canned, get_account_id()))return 200, {}, b""if not body:@@ -4181,7 +4255,7 @@ def _put_object_acl(bucket_name: str, key: str, body: bytes, headers: dict):return _error("MalformedACLError","The XML you provided was not well-formed or did not validate ""against our published schema.", 400)- _object_acl[(bucket_name, key)] = body.decode("utf-8", errors="replace")+ _object_acl[(bucket_name, key, version_id)] = body.decode("utf-8", errors="replace")return 200, {}, b""@@ -4564,7 +4638,7 @@ def _delete_objects(bucket_name: str, body: bytes, headers: dict = None):_object_tags.pop((bucket_name, k, None), None)_object_retention.pop((bucket_name, k), None)_object_legal_hold.pop((bucket_name, k), None)- _object_acl.pop((bucket_name, k), None)+ _object_acl.pop((bucket_name, k, None), None)_delete_persisted_object(bucket_name, k)deleted.append({"key": k, "version_id": "", "was_marker": False})diff --git a/tests/test_s3.py b/tests/test_s3.pyindex c532e3d9..c01b52e8 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -2455,6 +2455,75 @@ def test_s3_bucket_acl(s3):assert "Owner" in respassert "Grants" in resp+def test_s3_bucket_acl_canned(s3):+ """Canned x-amz-acl on CreateBucket and PutBucketAcl round-trips as the+ grants it implies. SDKs send the canned value as a header with an empty+ body, which used to be dropped, so `--acl public-read` read back as+ owner-only."""+ import uuid as _u+ bucket = f"acl-bkt-canned-{_u.uuid4().hex[:8]}"+ s3.create_bucket(Bucket=bucket, ACL="public-read")+ grants = s3.get_bucket_acl(Bucket=bucket)["Grants"]+ assert len(grants) == 2+ group = [g for g in grants if g["Grantee"]["Type"] == "Group"]+ assert group[0]["Grantee"]["URI"].endswith("global/AllUsers")+ assert group[0]["Permission"] == "READ"++ s3.put_bucket_acl(Bucket=bucket, ACL="public-read-write")+ grants = s3.get_bucket_acl(Bucket=bucket)["Grants"]+ perms = {g["Permission"] for g in grants if g["Grantee"]["Type"] == "Group"}+ assert perms == {"READ", "WRITE"}++ s3.put_bucket_acl(Bucket=bucket, ACL="private")+ grants = s3.get_bucket_acl(Bucket=bucket)["Grants"]+ assert len(grants) == 1+ assert grants[0]["Permission"] == "FULL_CONTROL"+ s3.delete_bucket(Bucket=bucket)++def test_s3_put_bucket_acl_invalid_canned(s3):+ """Invalid x-amz-acl values are rejected with InvalidArgument (400)."""+ import uuid as _u+ bucket = f"acl-bkt-bad-{_u.uuid4().hex[:8]}"+ s3.create_bucket(Bucket=bucket)+ with pytest.raises(ClientError) as exc:+ s3.put_bucket_acl(Bucket=bucket, ACL="not-a-real-canned-acl")+ assert exc.value.response["Error"]["Code"] == "InvalidArgument"+ s3.delete_bucket(Bucket=bucket)++def test_s3_put_bucket_acl_xml_body(s3):+ """A well-formed AccessControlPolicy XML body is accepted and round-trips."""+ import uuid as _u+ bucket = f"acl-bkt-xml-{_u.uuid4().hex[:8]}"+ s3.create_bucket(Bucket=bucket)+ s3.put_bucket_acl(+ Bucket=bucket,+ AccessControlPolicy={+ "Owner": {"ID": "test-owner-id", "DisplayName": "tester"},+ "Grants": [+ {+ "Grantee": {+ "Type": "CanonicalUser",+ "ID": "test-owner-id",+ "DisplayName": "tester",+ },+ "Permission": "FULL_CONTROL",+ },+ {+ "Grantee": {+ "Type": "Group",+ "URI": "http://acs.amazonaws.com/groups/global/AllUsers",+ },+ "Permission": "READ",+ },+ ],+ },+ )+ acl = s3.get_bucket_acl(Bucket=bucket)+ assert acl["Owner"]["ID"] == "test-owner-id"+ perms = sorted(g["Permission"] for g in acl["Grants"])+ assert perms == ["FULL_CONTROL", "READ"]+ s3.delete_bucket(Bucket=bucket)+def test_s3_range_suffix(s3):"""Range: bytes=-N returns last N bytes."""s3.create_bucket(Bucket="qa-s3-range-suffix")@@ -3718,6 +3787,81 @@ def test_s3_put_object_acl_xml_body(s3):s3.delete_bucket(Bucket=bucket)+def test_s3_object_acl_per_version(s3):+ """Object ACLs are per-version, like tags: `?versionId=` targets that+ version, and a later version is a separate object that starts from the+ default ACL while the addressed version keeps what was set."""+ import uuid as _u+ bucket = f"acl-ver-{_u.uuid4().hex[:8]}"+ s3.create_bucket(Bucket=bucket)+ s3.put_bucket_versioning(+ Bucket=bucket, VersioningConfiguration={"Status": "Enabled"})+ v1 = s3.put_object(Bucket=bucket, Key="k", Body=b"one")["VersionId"]+ s3.put_object(Bucket=bucket, Key="k", Body=b"two")++ s3.put_object_acl(Bucket=bucket, Key="k", VersionId=v1, ACL="public-read")++ acl = s3.get_object_acl(Bucket=bucket, Key="k", VersionId=v1)+ assert any(g["Grantee"].get("URI", "").endswith("global/AllUsers")+ for g in acl["Grants"])+ # The current version is a different object and keeps its default.+ assert len(s3.get_object_acl(Bucket=bucket, Key="k")["Grants"]) == 1++ # A fresh version starts from the default; v1 keeps what was set.+ s3.put_object(Bucket=bucket, Key="k", Body=b"three")+ assert len(s3.get_object_acl(Bucket=bucket, Key="k")["Grants"]) == 1+ acl = s3.get_object_acl(Bucket=bucket, Key="k", VersionId=v1)+ assert any(g["Grantee"].get("URI", "").endswith("global/AllUsers")+ for g in acl["Grants"])++ for v in s3.list_object_versions(Bucket=bucket).get("Versions", []):+ s3.delete_object(Bucket=bucket, Key=v["Key"], VersionId=v["VersionId"])+ s3.delete_bucket(Bucket=bucket)+++def test_s3_put_object_canned_acl_versioned(s3):+ """x-amz-acl on PutObject sticks to the version that PUT created."""+ import uuid as _u+ bucket = f"acl-put-ver-{_u.uuid4().hex[:8]}"+ s3.create_bucket(Bucket=bucket)+ s3.put_bucket_versioning(+ Bucket=bucket, VersioningConfiguration={"Status": "Enabled"})+ v1 = s3.put_object(+ Bucket=bucket, Key="k", Body=b"one", ACL="public-read")["VersionId"]+ assert len(s3.get_object_acl(Bucket=bucket, Key="k")["Grants"]) == 2++ s3.put_object(Bucket=bucket, Key="k", Body=b"two")+ assert len(s3.get_object_acl(Bucket=bucket, Key="k")["Grants"]) == 1+ acl = s3.get_object_acl(Bucket=bucket, Key="k", VersionId=v1)+ assert len(acl["Grants"]) == 2++ for v in s3.list_object_versions(Bucket=bucket).get("Versions", []):+ s3.delete_object(Bucket=bucket, Key=v["Key"], VersionId=v["VersionId"])+ s3.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."""+ import uuid as _u++ import requests+ bucket = f"acl-post-{_u.uuid4().hex[:8]}"+ s3.create_bucket(Bucket=bucket)+ post = s3.generate_presigned_post(+ Bucket=bucket, Key="k",+ Fields={"acl": "public-read"},+ Conditions=[{"acl": "public-read"}],+ )+ r = requests.post(post["url"], data=post["fields"], files={"file": ("k", b"x")})+ assert r.status_code == 204+ grants = s3.get_object_acl(Bucket=bucket, Key="k")["Grants"]+ assert any(g["Grantee"].get("URI", "").endswith("global/AllUsers")+ for g in grants)+ s3.delete_object(Bucket=bucket, Key="k")+ s3.delete_bucket(Bucket=bucket)++def test_s3_put_object_with_sha256_checksum_roundtrips(s3):"""PutObject + ChecksumAlgorithm=SHA256 must be retrievable viaGetObject(ChecksumMode='ENABLED'). Issue #831."""