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): versioning edge cases — the null version, marker signals, versioned copies (#1436)
Andrew Gaul98d5bdedff0d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6f00ca96..6d75df8f 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 — versioning edge cases: the null version, delete-marker signals, and versioned copies** — five behaviors around the edges of object versioning now match AWS. A PUT on a Suspended bucket minted a fresh UUID version id like an Enabled one; it is now stored as the `null` version — replacing any previous null version, answered without `x-amz-version-id` — and a suspended DELETE mints its marker under the literal `null` id the same way. The object written before versioning was enabled used to vanish from the index at the first versioned overwrite; it now stays addressable as `VersionId=null` and becomes current again when the newer version is deleted. Delete markers announce themselves: `DeleteObjects` without a per-key VersionId on a versioned bucket now creates a marker (for keys that never existed too) and reports `DeleteMarker`/`DeleteMarkerVersionId`, and a GET/HEAD 404 for a key hidden by a marker carries `x-amz-delete-marker: true` with the marker's id. `UploadPartCopy` ignored the copy source's `?versionId=` and copied the current bytes; it now copies that exact version and echoes `x-amz-copy-source-version-id`. A versioned `CopyObject` dropped the source version's user metadata (the index kept it; the synthesized source object just didn't carry it). And both copy operations decoded the copy-source header before splitting at `?`, so a key legitimately named `?versionId` — sent percent-encoded — read as an empty key with a version qualifier; the raw header is split first now. The five version-minting sites (PutObject, POST, CopyObject, CompleteMultipartUpload, and the delete-marker path) shared five hand-copied bookkeeping blocks; they now go through one helper, which is what makes the null-version rules uniform. Contributed by @gaul.- **S3 — `CompleteMultipartUpload` honors `If-Match` / `If-None-Match`** — conditional writes landed on PutObject, but CompleteMultipartUpload accepted the same headers and ignored them, so a create-once (`If-None-Match: *`) or compare-and-swap (`If-Match: <etag>`) upload that took the multipart path silently overwrote whatever was there. The complete now evaluates the same preconditions PutObject does, against the current object at complete time — 412 on a violated condition, 404 `NoSuchKey` when If-Match addresses a key with no current object. That last rule also tightens PutObject: the `*` form previously answered the RFC 7232 412 for a missing key, but AWS documents a single If-Match error row — `NoSuchKey` — and ceph/s3-tests pins 404 for both forms, so both operations now answer it. The idempotent complete-retry replay still bypasses the check, since the original request passed its conditions when it committed. Contributed by @gaul.- **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.diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex eefeef67..2ca1c4e6 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -2674,6 +2674,7 @@ 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)+ prior_obj = bucket["objects"].get(key)bucket["objects"][key] = obj# --- Object Lock headers on PutObject ---@@ -2695,30 +2696,9 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):resp_headers = {"ETag": obj["etag"], "Content-Length": "0"}resp_headers.update(_bucket_default_sse_headers(bucket_name))- if _bucket_versioning.get(bucket_name) in ("Enabled", "Suspended"):- version_id = new_uuid()- obj["version_id"] = version_id+ version_id = _record_object_version(bucket_name, key, prior_obj, obj, body)+ if version_id:resp_headers["x-amz-version-id"] = version_id- vkey = (bucket_name, key)- if vkey not in _object_versions:- _object_versions[vkey] = []- _object_versions[vkey].append({- "version_id": version_id,- "last_modified": obj["last_modified"],- "etag": obj["etag"],- "size": obj["size"],- "is_latest": True,- "data": body,- "content_type": obj.get("content_type") or "application/octet-stream",- "content_encoding": obj.get("content_encoding"),- "metadata": obj.get("metadata", {}),- "preserved_headers": obj.get("preserved_headers", {}),- "storage_class": obj.get("storage_class") or "STANDARD",- "checksums": obj.get("checksums") or {},- })- # Mark all previous versions as not latest- for v in _object_versions[vkey][:-1]:- v["is_latest"] = False# Persist only after the versioning block: the .meta.json sidecar must# carry the version_id assigned above (#1058).@@ -2895,6 +2875,7 @@ def _post_object(bucket_name: str, body: bytes, headers: dict):etag = f'"{md5_hash(file_value)}"'obj = _build_object_record(file_value, synth, etag=etag)+ prior_obj = bucket["objects"].get(key)bucket["objects"][key] = obj_apply_object_lock_from_headers(bucket_name, key, synth)@@ -2910,28 +2891,7 @@ def _post_object(bucket_name: str, body: bytes, headers: dict):bucket_name, key, "s3:ObjectCreated:Post", size=obj["size"], etag=etag)- version_id = None- if _bucket_versioning.get(bucket_name) in ("Enabled", "Suspended"):- version_id = new_uuid()- obj["version_id"] = version_id- vkey = (bucket_name, key)- if vkey not in _object_versions:- _object_versions[vkey] = []- _object_versions[vkey].append({- "version_id": version_id,- "last_modified": obj["last_modified"],- "etag": etag,- "size": obj["size"],- "is_latest": True,- "data": file_value,- "content_type": obj.get("content_type") or "application/octet-stream",- "content_encoding": obj.get("content_encoding"),- "metadata": obj.get("metadata", {}),- "preserved_headers": obj.get("preserved_headers", {}),- "storage_class": obj.get("storage_class") or "STANDARD",- })- for v in _object_versions[vkey][:-1]:- v["is_latest"] = False+ version_id = _record_object_version(bucket_name, key, prior_obj, obj, file_value)# Persist only after the versioning block: the .meta.json sidecar must# carry the version_id assigned above (#1058).@@ -3031,6 +2991,14 @@ def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict =return errversion_id = _qp(query_params, "versionId", "")+ if version_id == "null" and not any(+ v["version_id"] == "null"+ for v in _object_versions.get((bucket_name, key), [])):+ # The literal "null" addresses the pre-versioning object; before any+ # versioned write records it in the index, that is the current object.+ obj = bucket["objects"].get(key)+ if obj is not None and not obj.get("version_id"):+ version_id = ""if version_id:vkey = (bucket_name, key)versions = _object_versions.get(vkey, [])@@ -3056,12 +3024,15 @@ def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict =return _error("NoSuchVersion", "The specified version does not exist.", 404, f"/{bucket_name}/{key}")if key not in bucket["objects"]:- return _error(+ status, err_headers, err_body = _error("NoSuchKey","The specified key does not exist.",404,f"/{bucket_name}/{key}",)+ # A key hidden by a delete marker announces the marker on its 404.+ err_headers.update(_delete_marker_404_headers(bucket_name, key))+ return status, err_headers, err_bodyobj = bucket["objects"][key]range_header = headers.get("range", "")@@ -3252,6 +3223,14 @@ def _head_object(bucket_name: str, key: str, headers: dict | None = None,# A `?versionId=` selects a specific version's metadata, matching AWS# HeadObject(VersionId); without it, the current object is used.version_id = _qp(query_params, "versionId", "")+ if version_id == "null" and not any(+ v["version_id"] == "null"+ for v in _object_versions.get((bucket_name, key), [])):+ # The literal "null" addresses the pre-versioning object; before any+ # versioned write records it in the index, that is the current object.+ obj = bucket["objects"].get(key)+ if obj is not None and not obj.get("version_id"):+ version_id = ""if version_id:ventry = next((v for v in _object_versions.get((bucket_name, key), [])@@ -3268,12 +3247,15 @@ def _head_object(bucket_name: str, key: str, headers: dict | None = None,obj = _object_record_from_version(ventry)else:if key not in bucket["objects"]:- return _error(+ status, err_headers, err_body = _error("NoSuchKey","The specified key does not exist.",404,f"/{bucket_name}/{key}",)+ # A key hidden by a delete marker announces the marker on its 404.+ err_headers.update(_delete_marker_404_headers(bucket_name, key))+ return status, err_headers, err_bodyobj = bucket["objects"][key]include_checksums = (headers.get("x-amz-checksum-mode") or "").upper() == "ENABLED"@@ -3315,10 +3297,116 @@ def _object_record_from_version(v: dict) -> dict:"preserved_headers": v.get("preserved_headers", {}),"storage_class": v.get("storage_class") or "STANDARD","checksums": v.get("checksums") or {},- "version_id": v["version_id"],+ # The "null" version promotes to a current object WITHOUT a version+ # id, the same shape a pre-versioning object has — per-version tags+ # and subresources key it as None, and the literal "null" is only a+ # wire-level name for it.+ "version_id": None if v["version_id"] == "null" else v["version_id"],}+def _version_entry_from_record(obj: dict, version_id: str, data) -> dict:+ """A version-index entry projected from a current-object record."""+ return {+ "version_id": version_id,+ "last_modified": obj["last_modified"],+ "etag": obj["etag"],+ "size": obj["size"],+ "is_latest": False,+ "data": data,+ "content_type": obj.get("content_type") or "application/octet-stream",+ "content_encoding": obj.get("content_encoding"),+ "metadata": obj.get("metadata", {}),+ "preserved_headers": obj.get("preserved_headers", {}),+ "storage_class": obj.get("storage_class") or "STANDARD",+ "checksums": obj.get("checksums") or {},+ "parts": obj.get("parts"),+ }+++def _preserve_null_version(bucket_name: str, key: str, versions: list,+ prior_obj: dict | None):+ """Keep the pre-versioning object addressable as the "null" version.++ An object written before versioning was enabled has no version id; the+ first versioned write (or delete marker) that lands on top of it must+ leave it in the version index under VersionId "null" rather than silently+ discarding it — AWS keeps the null version in the stack."""+ if prior_obj is None or prior_obj.get("version_id"):+ return+ if any(v["version_id"] == "null" for v in versions):+ return+ versions.append(_version_entry_from_record(+ prior_obj, "null", _read_body(bucket_name, key, prior_obj)))+++def _record_object_version(bucket_name: str, key: str, prior_obj: dict | None,+ obj: dict, data) -> str | None:+ """Version bookkeeping for a write landing at `key`.++ An Enabled bucket mints a new version id; a Suspended bucket stores the+ write as the "null" version, REPLACING any previous null version, and+ answers without x-amz-version-id — so this returns the id to put on the+ response, or None for unversioned and suspended writes. `prior_obj` is+ the current-object record the write displaced (captured before the+ overwrite), preserved as the null version when it predates versioning."""+ versioning = _bucket_versioning.get(bucket_name)+ if versioning not in ("Enabled", "Suspended"):+ return None+ vkey = (bucket_name, key)+ versions = _object_versions.setdefault(vkey, [])+ if versioning == "Enabled":+ _preserve_null_version(bucket_name, key, versions, prior_obj)+ version_id = new_uuid()+ obj["version_id"] = version_id+ else:+ version_id = "null"+ versions[:] = [v for v in versions if v["version_id"] != "null"]+ entry = _version_entry_from_record(obj, version_id, data)+ entry["is_latest"] = True+ for v in versions:+ v["is_latest"] = False+ versions.append(entry)+ return version_id if versioning == "Enabled" else None+++def _record_delete_marker(bucket_name: str, key: str,+ prior_obj: dict | None) -> str:+ """Append a delete marker per the bucket's versioning state and return its+ version id: a fresh id on Enabled, the literal "null" on Suspended — where+ the marker REPLACES any existing null version, as AWS does."""+ vkey = (bucket_name, key)+ versions = _object_versions.setdefault(vkey, [])+ if _bucket_versioning.get(bucket_name) == "Enabled":+ _preserve_null_version(bucket_name, key, versions, prior_obj)+ marker_id = new_uuid()+ else:+ marker_id = "null"+ versions[:] = [v for v in versions if v["version_id"] != "null"]+ for v in versions:+ v["is_latest"] = False+ versions.append({+ "version_id": marker_id,+ "last_modified": now_iso(),+ "etag": "",+ "size": 0,+ "is_latest": True,+ "is_delete_marker": True,+ })+ return marker_id+++def _delete_marker_404_headers(bucket_name: str, key: str) -> dict:+ """Headers a 404 for `key` must carry when its current version is a delete+ marker: AWS marks the miss with x-amz-delete-marker and the marker's id."""+ versions = _object_versions.get((bucket_name, key)) or []+ latest = versions[-1] if versions else None+ if latest is not None and latest.get("is_delete_marker") and latest.get("is_latest"):+ return {"x-amz-delete-marker": "true",+ "x-amz-version-id": latest["version_id"]}+ return {}++def _delete_object_version(bucket: dict, bucket_name: str, key: str,version_id: str) -> tuple[bool, bool]:"""Physically remove the exact version (or delete marker) addressed by@@ -3332,8 +3420,11 @@ def _delete_object_version(bucket: dict, bucket_name: str, key: str,# No tracked history: the only addressable version is the current object,# exposed under the "null" id (objects put before versioning was enabled).+ # The guard on version_id matters: "null" only addresses a current object+ # that actually IS the null version — one without a version id of its own.if not versions:- if version_id == "null" and key in bucket["objects"]:+ if (version_id == "null" and key in bucket["objects"]+ and not bucket["objects"][key].get("version_id")):_purge_current_object(bucket_name, key, bucket)return True, Falsereturn False, False@@ -3342,7 +3433,8 @@ def _delete_object_version(bucket: dict, bucket_name: str, key: str,(i for i, v in enumerate(versions) if v["version_id"] == version_id), None)if idx is None:- if version_id == "null" and key in bucket["objects"]:+ if (version_id == "null" and key in bucket["objects"]+ and not bucket["objects"][key].get("version_id")):_purge_current_object(bucket_name, key, bucket)return True, Falsereturn False, False@@ -3421,21 +3513,8 @@ def _delete_object(bucket_name: str, key: str, headers: dict | None = None,versioning = _bucket_versioning.get(bucket_name, "")if versioning in ("Enabled", "Suspended"):# Add a delete marker instead of removing version history- delete_marker_id = new_uuid()- vkey = (bucket_name, key)- if vkey not in _object_versions:- _object_versions[vkey] = []- # Mark all previous versions as not latest- for v in _object_versions[vkey]:- v["is_latest"] = False- _object_versions[vkey].append({- "version_id": delete_marker_id,- "last_modified": now_iso(),- "etag": "",- "size": 0,- "is_latest": True,- "is_delete_marker": True,- })+ delete_marker_id = _record_delete_marker(+ bucket_name, key, bucket["objects"].get(key))existed = key in bucket["objects"]bucket["objects"].pop(key, None)if existed:@@ -3516,8 +3595,12 @@ def _object_mtime_dt(obj: dict):def _copy_object(bucket_name: str, dest_key: str, headers: dict):- source = url_unquote(headers.get("x-amz-copy-source", "").lstrip("/"))- src_path, _, src_query = source.partition("?")+ # Split the raw header at "?" before percent-decoding: a key legitimately+ # containing "?versionId" arrives encoded (%3FversionId) and must stay+ # part of the key, while a real versionId qualifier arrives as a bare "?".+ raw_source = headers.get("x-amz-copy-source", "").lstrip("/")+ raw_path, _, src_query = raw_source.partition("?")+ src_path = url_unquote(raw_path)src_parts = src_path.split("/", 1)if len(src_parts) < 2:return _error(@@ -3556,13 +3639,18 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):404,f"/{src_bucket_name}/{src_key}",)- # Synthesize a source object from the stored version. Per-version user- # metadata isn't retained, so a COPY metadata-directive carries none.+ # Synthesize a source object from the stored version — the index keeps+ # the body plus the wire metadata, so a COPY metadata-directive carries+ # the version's user metadata and headers like a current-object copy.src_obj = {"body": ventry.get("data", b""),"etag": ventry["etag"],"size": ventry["size"],+ "last_modified": ventry["last_modified"],"content_type": ventry.get("content_type") or "application/octet-stream",+ "content_encoding": ventry.get("content_encoding"),+ "metadata": ventry.get("metadata", {}),+ "preserved_headers": ventry.get("preserved_headers", {}),"storage_class": ventry.get("storage_class") or "STANDARD","checksums": ventry.get("checksums") or {},"version_id": src_version_id,@@ -3658,6 +3746,7 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):"storage_class": dest_sc,"checksums": dest_checksums,}+ dest_prior_obj = dest_bucket["objects"].get(dest_key)dest_bucket["objects"][dest_key] = dest_obj# --- Resolve tag payload now; commit after dest version_id is assigned@@ -3703,29 +3792,10 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):resp_headers["x-amz-copy-source-version-id"] = copy_src_vidif dest_sc != "STANDARD":resp_headers["x-amz-storage-class"] = dest_sc- if _bucket_versioning.get(bucket_name) in ("Enabled", "Suspended"):- version_id = new_uuid()- dest_obj["version_id"] = version_id+ version_id = _record_object_version(+ bucket_name, dest_key, dest_prior_obj, dest_obj, src_body)+ if version_id:resp_headers["x-amz-version-id"] = version_id- vkey = (bucket_name, dest_key)- if vkey not in _object_versions:- _object_versions[vkey] = []- _object_versions[vkey].append({- "version_id": version_id,- "last_modified": dest_obj["last_modified"],- "etag": dest_obj["etag"],- "size": dest_obj["size"],- "is_latest": True,- "data": src_body,- "content_type": dest_obj.get("content_type") or "application/octet-stream",- "content_encoding": dest_obj.get("content_encoding"),- "metadata": dest_obj.get("metadata", {}),- "preserved_headers": dest_obj.get("preserved_headers", {}),- "storage_class": dest_obj.get("storage_class") or "STANDARD",- "checksums": dest_obj.get("checksums") or {},- })- for v in _object_versions[vkey][:-1]:- v["is_latest"] = False# Persist only after the versioning block: the .meta.json sidecar must# carry the version_id assigned above (#1058).@@ -4626,6 +4696,14 @@ def _delete_objects(bucket_name: str, body: bytes, headers: dict = None):bucket, bucket_name, k, version_id)deleted.append({"key": k, "version_id": version_id, "was_marker": was_marker})+ elif _bucket_versioning.get(bucket_name) in ("Enabled", "Suspended"):+ # No VersionId on a versioned bucket: create a delete marker —+ # even for a key that never existed — exactly as the single-object+ # DELETE does, and report it on the Deleted entry.+ marker_id = _record_delete_marker(bucket_name, k, bucket["objects"].get(k))+ bucket["objects"].pop(k, None)+ deleted.append({"key": k, "version_id": "", "was_marker": False,+ "marker_created": marker_id})else:# No VersionId → plain delete of the current object.bucket["objects"].pop(k, None)@@ -4647,6 +4725,10 @@ def _delete_objects(bucket_name: str, body: bytes, headers: dict = None):if d["was_marker"]:SubElement(el, "DeleteMarker").text = "true"SubElement(el, "DeleteMarkerVersionId").text = d["version_id"]+ elif d.get("marker_created"):+ # A versionless delete on a versioned bucket minted a marker.+ SubElement(el, "DeleteMarker").text = "true"+ SubElement(el, "DeleteMarkerVersionId").text = d["marker_created"]for e in errors:el = SubElement(resp, "Error")SubElement(el, "Key").text = e["key"]@@ -4765,8 +4847,12 @@ def _upload_part_copy(bucket_name: str, dest_key: str, query_params: dict, headeif upload_id not in _multipart_uploads:return _error("NoSuchUpload", "The specified multipart upload does not exist.", 404)- source = url_unquote(headers.get("x-amz-copy-source", "").lstrip("/"))- src_parts = source.split("?", 1)[0].split("/", 1)+ # Split the raw header at "?" before percent-decoding, exactly as+ # CopyObject does: a key containing "?versionId" arrives encoded and must+ # stay part of the key, while a real versionId qualifier is a bare "?".+ raw_source = headers.get("x-amz-copy-source", "").lstrip("/")+ raw_path, _, src_query = raw_source.partition("?")+ src_parts = url_unquote(raw_path).split("/", 1)if len(src_parts) < 2:return _error("InvalidArgument", "Copy Source must mention the source bucket and key", 400)@@ -4774,11 +4860,35 @@ def _upload_part_copy(bucket_name: str, dest_key: str, query_params: dict, headesrc_bucket = _ensure_bucket(src_bucket_name)if src_bucket is None:return _no_such_bucket(src_bucket_name)- if src_key not in src_bucket["objects"]:- return _error("NoSuchKey", "The specified key does not exist.", 404)- src_obj = src_bucket["objects"][src_key]- src_body = _read_body(src_bucket_name, src_key, src_obj)+ # A `?versionId=` on the copy source selects the exact version to copy the+ # range from, not the current object.+ src_version_id = None+ if src_query:+ src_version_id = _parse_qs(src_query, keep_blank_values=True).get(+ "versionId", [None]+ )[0]++ if src_version_id:+ ventry = next(+ (v for v in _object_versions.get((src_bucket_name, src_key), [])+ if v["version_id"] == src_version_id),+ None,+ )+ if ventry is None or ventry.get("is_delete_marker"):+ return _error(+ "NoSuchVersion",+ "The specified version does not exist.",+ 404,+ f"/{src_bucket_name}/{src_key}",+ )+ src_body = ventry.get("data") or b""+ else:+ if src_key not in src_bucket["objects"]:+ return _error("NoSuchKey", "The specified key does not exist.", 404)+ src_obj = src_bucket["objects"][src_key]+ src_version_id = src_obj.get("version_id")+ src_body = _read_body(src_bucket_name, src_key, src_obj)# Handle x-amz-copy-source-rangecopy_range = headers.get("x-amz-copy-source-range", "")@@ -4822,7 +4932,11 @@ def _upload_part_copy(bucket_name: str, dest_key: str, query_params: dict, headeroot = Element("CopyPartResult", xmlns=S3_NS)SubElement(root, "ETag").text = etagSubElement(root, "LastModified").text = now_iso()- return 200, {"Content-Type": "application/xml"}, _xml_body(root)+ resp_headers = {"Content-Type": "application/xml"}+ if src_version_id:+ # AWS echoes the copied source version on a versioned source.+ resp_headers["x-amz-copy-source-version-id"] = src_version_id+ return 200, resp_headers, _xml_body(root)def _complete_multipart_upload(@@ -4931,6 +5045,7 @@ def _complete_multipart_upload("storage_class": upload.get("storage_class") or "STANDARD","parts": part_records,}+ prior_obj = bucket["objects"].get(key)bucket["objects"][key] = objdel _multipart_uploads[upload_id]@@ -4944,28 +5059,9 @@ def _complete_multipart_upload()resp_headers = {"Content-Type": "application/xml"}- if _bucket_versioning.get(bucket_name) in ("Enabled", "Suspended"):- version_id = new_uuid()- obj["version_id"] = version_id+ version_id = _record_object_version(bucket_name, key, prior_obj, obj, combined)+ if version_id:resp_headers["x-amz-version-id"] = version_id- vkey = (bucket_name, key)- if vkey not in _object_versions:- _object_versions[vkey] = []- _object_versions[vkey].append({- "version_id": version_id,- "last_modified": obj["last_modified"],- "etag": obj["etag"],- "size": obj["size"],- "is_latest": True,- "data": combined,- "content_type": obj.get("content_type") or "application/octet-stream",- "content_encoding": obj.get("content_encoding"),- "metadata": obj.get("metadata", {}),- "preserved_headers": obj.get("preserved_headers", {}),- "storage_class": obj.get("storage_class") or "STANDARD",- })- for v in _object_versions[vkey][:-1]:- v["is_latest"] = False# Persist only after the versioning block: the .meta.json sidecar must# carry the version_id assigned above (#1058).diff --git a/tests/test_s3.py b/tests/test_s3.pyindex 336385a8..faca1993 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -2367,6 +2367,152 @@ def test_s3_multipart_upload_returns_version_id(s3):assert latest[0]["VersionId"] == resp2["VersionId"]+def test_s3_versioning_suspended_null_version(s3):+ """A PUT on a Suspended bucket is the "null" version: the response carries+ no VersionId, an overwrite replaces the null version rather than stacking+ a new one, and DeleteObject(VersionId='null') removes it."""+ bkt = "s3-ver-susp"+ s3.create_bucket(Bucket=bkt)+ s3.put_bucket_versioning(Bucket=bkt, VersioningConfiguration={"Status": "Enabled"})+ s3.put_bucket_versioning(Bucket=bkt, VersioningConfiguration={"Status": "Suspended"})++ resp = s3.put_object(Bucket=bkt, Key="k", Body=b"one")+ assert "VersionId" not in resp+ s3.put_object(Bucket=bkt, Key="k", Body=b"two")++ versions = s3.list_object_versions(Bucket=bkt).get("Versions", [])+ assert [(v["VersionId"], v["IsLatest"]) for v in versions] == [("null", True)]+ assert s3.get_object(Bucket=bkt, Key="k", VersionId="null")["Body"].read() == b"two"++ s3.delete_object(Bucket=bkt, Key="k", VersionId="null")+ assert "Versions" not in s3.list_object_versions(Bucket=bkt)+ s3.delete_bucket(Bucket=bkt)+++def test_s3_versioning_preserves_pre_versioning_null(s3):+ """An object written before versioning was enabled stays addressable as+ the "null" version once versioned writes land on top, and becomes current+ again when the newer version is deleted."""+ bkt = "s3-ver-null-keep"+ s3.create_bucket(Bucket=bkt)+ s3.put_object(Bucket=bkt, Key="k", Body=b"fooz")+ s3.put_bucket_versioning(Bucket=bkt, VersioningConfiguration={"Status": "Enabled"})++ v2 = s3.put_object(Bucket=bkt, Key="k", Body=b"zzz")["VersionId"]+ assert s3.get_object(Bucket=bkt, Key="k")["Body"].read() == b"zzz"+ assert s3.get_object(Bucket=bkt, Key="k", VersionId="null")["Body"].read() == b"fooz"++ s3.delete_object(Bucket=bkt, Key="k", VersionId=v2)+ assert s3.get_object(Bucket=bkt, Key="k")["Body"].read() == b"fooz"++ s3.delete_object(Bucket=bkt, Key="k", VersionId="null")+ with pytest.raises(ClientError) as exc:+ s3.get_object(Bucket=bkt, Key="k")+ assert exc.value.response["Error"]["Code"] == "NoSuchKey"+ assert "Versions" not in s3.list_object_versions(Bucket=bkt)+ s3.delete_bucket(Bucket=bkt)+++def test_s3_delete_marker_signals(s3):+ """A delete on a versioned bucket reports its marker: DeleteMarker on the+ DELETE response, x-amz-delete-marker on the subsequent 404, and the+ literal "null" marker id when versioning is Suspended."""+ bkt = "s3-ver-marker"+ s3.create_bucket(Bucket=bkt)+ s3.put_bucket_versioning(Bucket=bkt, VersioningConfiguration={"Status": "Enabled"})+ s3.put_object(Bucket=bkt, Key="k", Body=b"x")++ resp = s3.delete_object(Bucket=bkt, Key="k")+ assert resp["DeleteMarker"] is True+ assert resp["VersionId"]++ with pytest.raises(ClientError) as exc:+ s3.head_object(Bucket=bkt, Key="k")+ headers = exc.value.response["ResponseMetadata"]["HTTPHeaders"]+ assert headers.get("x-amz-delete-marker") == "true"++ s3.put_bucket_versioning(Bucket=bkt, VersioningConfiguration={"Status": "Suspended"})+ s3.put_object(Bucket=bkt, Key="k2", Body=b"x")+ resp = s3.delete_object(Bucket=bkt, Key="k2")+ assert resp["DeleteMarker"] is True+ assert resp["VersionId"] == "null"+++def test_s3_batch_delete_creates_marker(s3):+ """DeleteObjects without a VersionId on a versioned bucket creates a+ delete marker — for a key that never existed too — and reports it under+ DeleteMarker / DeleteMarkerVersionId, as AWS does."""+ bkt = "s3-ver-batch-marker"+ s3.create_bucket(Bucket=bkt)+ s3.put_bucket_versioning(Bucket=bkt, VersioningConfiguration={"Status": "Enabled"})++ resp = s3.delete_objects(Bucket=bkt, Delete={"Objects": [{"Key": "never"}]})+ deleted = resp["Deleted"][0]+ assert deleted["DeleteMarker"] is True+ marker_id = deleted["DeleteMarkerVersionId"]++ markers = s3.list_object_versions(Bucket=bkt)["DeleteMarkers"]+ assert [m["VersionId"] for m in markers] == [marker_id]+++def test_s3_upload_part_copy_versioned_source(s3):+ """UploadPartCopy with a source VersionId copies that version's bytes,+ not the current object's, and echoes x-amz-copy-source-version-id."""+ bkt = "s3-ver-partcopy"+ s3.create_bucket(Bucket=bkt)+ s3.put_bucket_versioning(Bucket=bkt, VersioningConfiguration={"Status": "Enabled"})+ v1 = s3.put_object(Bucket=bkt, Key="src", Body=b"a" * 1024)["VersionId"]+ s3.put_object(Bucket=bkt, Key="src", Body=b"b" * 1024)++ mpu = s3.create_multipart_upload(Bucket=bkt, Key="dst")+ part = s3.upload_part_copy(+ Bucket=bkt, Key="dst", UploadId=mpu["UploadId"], PartNumber=1,+ CopySource={"Bucket": bkt, "Key": "src", "VersionId": v1})+ assert part["CopySourceVersionId"] == v1+ s3.complete_multipart_upload(+ Bucket=bkt, Key="dst", UploadId=mpu["UploadId"],+ MultipartUpload={"Parts": [+ {"ETag": part["CopyPartResult"]["ETag"], "PartNumber": 1}]})+ assert s3.get_object(Bucket=bkt, Key="dst")["Body"].read() == b"a" * 1024+++def test_s3_copy_versioned_source_keeps_metadata(s3):+ """CopyObject with a source VersionId carries that version's user+ metadata, like a current-object copy does."""+ bkt = "s3-ver-copy-meta"+ s3.create_bucket(Bucket=bkt)+ s3.put_bucket_versioning(Bucket=bkt, VersioningConfiguration={"Status": "Enabled"})+ v1 = s3.put_object(Bucket=bkt, Key="src", Body=b"m",+ Metadata={"foo": "bar"})["VersionId"]+ s3.put_object(Bucket=bkt, Key="src", Body=b"n")++ s3.copy_object(Bucket=bkt, Key="dst",+ CopySource={"Bucket": bkt, "Key": "src", "VersionId": v1})+ assert s3.head_object(Bucket=bkt, Key="dst")["Metadata"] == {"foo": "bar"}+++def test_s3_copy_source_key_containing_question_mark(s3):+ """A source key literally containing "?versionId" arrives percent-encoded+ and must not be mistaken for a versionId qualifier by CopyObject or+ UploadPartCopy."""+ bkt = "s3-ver-qmark"+ s3.create_bucket(Bucket=bkt)+ s3.put_object(Bucket=bkt, Key="?versionId", Body=b"question")++ s3.copy_object(Bucket=bkt, Key="copied", CopySource={"Bucket": bkt, "Key": "?versionId"})+ assert s3.get_object(Bucket=bkt, Key="copied")["Body"].read() == b"question"++ mpu = s3.create_multipart_upload(Bucket=bkt, Key="dst")+ part = s3.upload_part_copy(+ Bucket=bkt, Key="dst", UploadId=mpu["UploadId"], PartNumber=1,+ CopySource={"Bucket": bkt, "Key": "?versionId"})+ s3.complete_multipart_upload(+ Bucket=bkt, Key="dst", UploadId=mpu["UploadId"],+ MultipartUpload={"Parts": [+ {"ETag": part["CopyPartResult"]["ETag"], "PartNumber": 1}]})+ assert s3.get_object(Bucket=bkt, Key="dst")["Body"].read() == b"question"++def test_s3_copy_object_returns_version_id(s3):"""CopyObject should return VersionId and track versions when versioning is enabled."""bkt = "s3-ver-copy"