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
S3: object annotations (#1833)
Nathanbaaae1e70b01
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 569f4289..f485cbbc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,10 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added++- **S3 — object annotations** — `PutObjectAnnotation`, `GetObjectAnnotation`, `ListObjectAnnotations` (prefix, `max-annotation-results`, continuation tokens) and `DeleteObjectAnnotation`: named UTF-8 payloads of 1 byte to 1 MiB, up to 1,000 per object version, with S3's naming rules (`InvalidAnnotationName`, `AnnotationNameTooLong`), `AnnotationLimitExceeded`, `UnsupportedMediaType` and `x-amz-object-if-match`. Each belongs to one object version: a new version starts with none, deleting a version deletes its annotations, a delete marker keeps them, and an unversioned overwrite or delete drops them; writing one changes neither the object's ETag nor its version. `CopyObject` carries them unless `x-amz-object-annotation-directive: EXCLUDE`, and recomputes their checksums when the copy names a new algorithm. Payload checksums are verified (`BadDigest`) and default to CRC64NVME; CRC32, CRC32C, CRC64NVME, SHA1, SHA256, SHA512, MD5 and XXHASH64 are computed, while XXHASH3 and XXHASH128 are refused rather than stored unverified. Annotations take the object's encryption and are refused on SSE-C objects, replicate with the object (`COMPLETED` / `REPLICA`), respect Object Lock on every write (governance retention needs `x-amz-bypass-governance-retention` to put, overwrite or delete one; compliance retention and a legal hold refuse all three, bypass or not, each as 403 `AccessDenied` naming retention or the legal hold, as observed on AWS), persist per version with `S3_PERSIST=1`, and send `s3:ObjectAnnotation:Put` / `s3:ObjectAnnotation:Delete` events with the record's `objectAnnotation` block; a `CopyObject` event reports `hasObjectAnnotation`. Previously a `PUT ?annotation` fell through to `PutObject` and replaced the object with the payload. The S3 Metadata annotation table (`UpdateBucketMetadataAnnotationTableConfiguration`) is not included: MiniStack has no S3 Metadata configuration for it to belong to. Checked against the S3 API Reference, the S3 User Guide's "Annotating your objects" page and the botocore model; the Object Lock behaviour was validated against AWS (ap-southeast-2).+### Fixed- **DynamoDB — `DescribeTable` accepts a table ARN** — `TableName` given as the table's ARN answered `ResourceNotFoundException`, where AWS accepts either form. It now resolves through the same ARN normalization the other table operations use, and an ARN from another account or region still answers `ResourceNotFoundException`. This unblocks OpenSearch Data Prepper's DynamoDB source, which always describes the table by ARN.diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex 52aeb4da..13e6a57f 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -9,6 +9,8 @@ Supports: CreateBucket, DeleteBucket, ListBuckets, HeadBucket,DeleteObjects (batch),Multipart Upload (Create, UploadPart, Complete, Abort, List, ListParts),Object Tagging (Get, Put, Delete),+ Object Annotations (PutObjectAnnotation, GetObjectAnnotation,+ ListObjectAnnotations, DeleteObjectAnnotation; carried by CopyObject),ListObjectVersions,Bucket sub-resources (Policy, Versioning, Encryption, Lifecycle,CORS, ACL, Tagging, Notification, Logging, Accelerate, RequestPayment,@@ -142,6 +144,9 @@ _bucket_request_payment_config = AccountScopedDict()_object_tags = AccountScopedDict()_object_acl = AccountScopedDict() # (bucket, key, version_id) -> stored ACL XML string+# (bucket, key, version_id) -> {annotation name: {payload, size, etag, last_modified, checksums,+# replication_status}}; version_id is None for the object without one, as for tags.+_object_annotations = AccountScopedDict()_object_versions = AccountScopedDict() # (bucket, key) -> [{version_id, obj_record}, ...]_bucket_object_lock = AccountScopedDict()@@ -1883,6 +1888,11 @@ def _dispatch(method: str, bucket: str, key: str, headers: dict, body: bytes, quif method == "GET":if "uploadId" in query_params:return _list_parts(bucket, key, query_params)+ if "annotation" in query_params:+ # One path for both: GetObjectAnnotation names an annotation, ListObjectAnnotations does not.+ if "annotationName" in query_params:+ return _get_object_annotation(bucket, key, headers, query_params)+ return _list_object_annotations(bucket, key, query_params)if "tagging" in query_params:return _get_object_tagging(bucket, key, query_params)if "retention" in query_params:@@ -1900,6 +1910,8 @@ def _dispatch(method: str, bucket: str, key: str, headers: dict, body: bytes, quif "x-amz-copy-source" in headers:return _upload_part_copy(bucket, key, query_params, headers)return _upload_part(bucket, key, body, query_params, headers)+ if "annotation" in query_params:+ return _put_object_annotation(bucket, key, body, headers, query_params)if "tagging" in query_params:return _put_object_tagging(bucket, key, body, query_params)if "retention" in query_params:@@ -1931,6 +1943,8 @@ def _dispatch(method: str, bucket: str, key: str, headers: dict, body: bytes, quif method == "DELETE":if "uploadId" in query_params:return _abort_multipart_upload(bucket, key, query_params)+ if "annotation" in query_params:+ return _delete_object_annotation(bucket, key, headers, query_params)if "tagging" in query_params:return _delete_object_tagging(bucket, key, query_params)return _delete_object(bucket, key, headers, query_params)@@ -2228,6 +2242,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_annotations if k[0] == name]:+ del _object_annotations[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]:@@ -4414,6 +4430,7 @@ def _purge_current_object(bucket_name: str, key: str, bucket: dict):"""Remove the current object plus its key-level metadata and on-disk copy."""bucket["objects"].pop(key, None)_object_tags.pop((bucket_name, key, None), None)+ _object_annotations.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), None)@@ -4548,6 +4565,13 @@ def _record_object_version(bucket_name: str, key: str, prior_obj: dict | None, othe current-object record the write displaced (captured before theoverwrite), preserved as the null version when it predates versioning."""versioning = _bucket_versioning.get(bucket_name)+ if versioning != "Enabled":+ # An unversioned or suspended write replaces the object that has no+ # version id, and "Overwriting an object replaces its annotations with+ # whatever annotations the new version has": none, until CopyObject or+ # PutObjectAnnotation gives it some. An Enabled write mints a new+ # version, which has none of its own.+ _object_annotations.pop((bucket_name, key, None), None)if versioning not in ("Enabled", "Suspended"):return None_persist_displaced_version(bucket_name, key, prior_obj, versioning)@@ -4664,6 +4688,9 @@ def _delete_object_version(bucket: dict, bucket_name: str, key: str, version_id:# 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)+ # "Deleting a specific version ID deletes that version and all associated+ # annotations." The null version's are keyed None, as its tags are read.+ _object_annotations.pop((bucket_name, key, None if version_id == "null" else version_id), None)if not versions:# History is now empty — drop the index entry and the current object.@@ -4776,6 +4803,7 @@ def _delete_object(bucket_name: str, key: str, headers: dict | None = None, querexisted = key in bucket["objects"]bucket["objects"].pop(key, None)_object_tags.pop((bucket_name, key, None), None)+ _object_annotations.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), None)@@ -4918,6 +4946,19 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):if canned_acl and canned_acl not in _CANNED_OBJECT_ACLS:return _error("InvalidArgument", f"Invalid x-amz-acl value: {canned_acl}", 400)+ # "CopyObject – Copies annotations from the source object by default",+ # COPY or EXCLUDE (x-amz-object-annotation-directive, the botocore model's+ # AnnotationDirective). A new checksum algorithm on the copy "applies to+ # both the object and its annotations", so it must be one they can take.+ annotation_directive = headers.get("x-amz-object-annotation-directive", "COPY").upper()+ if annotation_directive not in ("COPY", "EXCLUDE"):+ return _error("InvalidArgument", f"Invalid annotation directive: {annotation_directive}", 400)+ annotation_algorithm = (+ headers.get("x-amz-checksum-algorithm") or headers.get("x-amz-sdk-checksum-algorithm") or ""+ ).upper()+ if annotation_algorithm and _annotation_checksum(annotation_algorithm, b"") is None:+ return _annotation_checksum_unsupported(annotation_algorithm)+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),@@ -5043,6 +5084,21 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):if src_tags:pending_dest_tags = dict(src_tags)+ # Annotations of the version copied, for the version the copy makes. Their+ # checksums are the source's unless the copy names another algorithm.+ pending_dest_annotations: dict | None = None+ if annotation_directive == "COPY":+ src_annotations = _object_annotations.get((src_bucket_name, src_key, src_obj.get("version_id")))+ if src_annotations:+ pending_dest_annotations = {}+ for name, entry in src_annotations.items():+ carried = {k: v for k, v in entry.items() if k != "replication_status"}+ if annotation_algorithm:+ carried["checksums"] = {+ annotation_algorithm: _annotation_checksum(annotation_algorithm, entry["payload"].encode())+ }+ pending_dest_annotations[name] = carried+# --- Preserve lock / retention ---src_retention = _object_retention.get((src_bucket_name, src_key))if src_retention:@@ -5073,9 +5129,23 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):size=dest_obj["size"],etag=new_etag,version_id=version_id,+ # "If the copied object has annotations, the event includes a+ # hasObjectAnnotation field set to true."+ object_extra={"hasObjectAnnotation": bool(pending_dest_annotations)},)dest_version_id = dest_obj.get("version_id")+ if pending_dest_annotations:+ _object_annotations[(bucket_name, dest_key, dest_version_id)] = pending_dest_annotations+ if dest_obj.get("_replica"):+ replica_bucket, replica_version = dest_obj["_replica"]+ _object_annotations[(replica_bucket, dest_key, replica_version)] = {+ name: dict(entry, replication_status="REPLICA") for name, entry in pending_dest_annotations.items()+ }+ for entry in pending_dest_annotations.values():+ entry["replication_status"] = "COMPLETED"+ else:+ _object_annotations.pop((bucket_name, dest_key, dest_version_id), None)if pending_dest_tags is not None:_object_tags[(bucket_name, dest_key, dest_version_id)] = pending_dest_tagsif dest_obj.get("_replica"):@@ -5230,6 +5300,485 @@ def _delete_object_tagging(bucket_name: str, key: str, query_params: dict | Nonereturn 204, resp_headers, b""+# ---------------------------------------------------------------------------+# Object annotations+# ---------------------------------------------------------------------------+# PutObjectAnnotation, GetObjectAnnotation, ListObjectAnnotations and+# DeleteObjectAnnotation. Evidence: the S3 API Reference pages for the four+# operations, the S3 User Guide's "Annotating your objects", "Event+# notification types and destinations" and "Event message structure" pages,+# and the botocore s3 model (1.43.63). Not validated against a real AWS+# account. Where the documentation is silent the choice is marked inference.+#+# An annotation belongs to one object version: a new version starts with none,+# deleting a version deletes its annotations, and a delete marker leaves the+# annotations of the version beneath it alone. Writing one changes nothing+# about the object (not its ETag, not its version) and sends only the+# s3:ObjectAnnotation:* events.++_ANNOTATION_MAX_PER_VERSION = 1000+_ANNOTATION_MAX_NAME_BYTES = 512+_ANNOTATION_MAX_PAYLOAD = 1024 * 1024+_ANNOTATION_NAME_PUNCTUATION = frozenset("0123456789_.-")+# The algorithms an annotation takes. MiniStack computes all but the two+# XXHASH3 variants, which have no stdlib or small-table implementation; like+# PutObject's unverifiable algorithms they are refused, never stored unchecked.+_ANNOTATION_CHECKSUM_ALGORITHMS = (+ "CRC32",+ "CRC32C",+ "CRC64NVME",+ "SHA1",+ "SHA256",+ "SHA512",+ "MD5",+ "XXHASH64",+ "XXHASH3",+ "XXHASH128",+)++# XXH64 (the xxHash specification, "XXH64 algorithm description"): plain+# 64-bit arithmetic, so it stays in the stdlib. Check values in the tests:+# xxh64(b"") == 0xEF46DB3751D8E999, xxh64(b"abc") == 0x44BC2CF5AD770999.+_XXH64_P1 = 0x9E3779B185EBCA87+_XXH64_P2 = 0xC2B2AE3D27D4EB4F+_XXH64_P3 = 0x165667B19E3779F9+_XXH64_P4 = 0x85EBCA77C2B2AE63+_XXH64_P5 = 0x27D4EB2F165667C5+_U64 = 0xFFFFFFFFFFFFFFFF+++def _rotl64(x: int, r: int) -> int:+ return ((x << r) | (x >> (64 - r))) & _U64+++def _xxh64_round(acc: int, lane: int) -> int:+ return (_rotl64((acc + lane * _XXH64_P2) & _U64, 31) * _XXH64_P1) & _U64+++def _xxh64(data: bytes, seed: int = 0) -> int:+ n = len(data)+ i = 0+ if n >= 32:+ v = [+ (seed + _XXH64_P1 + _XXH64_P2) & _U64,+ (seed + _XXH64_P2) & _U64,+ seed & _U64,+ (seed - _XXH64_P1) & _U64,+ ]+ while i + 32 <= n:+ for lane in range(4):+ v[lane] = _xxh64_round(v[lane], int.from_bytes(data[i + 8 * lane : i + 8 * lane + 8], "little"))+ i += 32+ h = (_rotl64(v[0], 1) + _rotl64(v[1], 7) + _rotl64(v[2], 12) + _rotl64(v[3], 18)) & _U64+ for acc in v:+ h = ((h ^ _xxh64_round(0, acc)) * _XXH64_P1 + _XXH64_P4) & _U64+ else:+ h = (seed + _XXH64_P5) & _U64+ h = (h + n) & _U64+ while i + 8 <= n:+ h ^= _xxh64_round(0, int.from_bytes(data[i : i + 8], "little"))+ h = (_rotl64(h, 27) * _XXH64_P1 + _XXH64_P4) & _U64+ i += 8+ if i + 4 <= n:+ h ^= (int.from_bytes(data[i : i + 4], "little") * _XXH64_P1) & _U64+ h = (_rotl64(h, 23) * _XXH64_P2 + _XXH64_P3) & _U64+ i += 4+ while i < n:+ h ^= (data[i] * _XXH64_P5) & _U64+ h = (_rotl64(h, 11) * _XXH64_P1) & _U64+ i += 1+ h ^= h >> 33+ h = (h * _XXH64_P2) & _U64+ h ^= h >> 29+ h = (h * _XXH64_P3) & _U64+ return h ^ (h >> 32)+++def _annotation_checksum(algorithm: str, data: bytes) -> str | None:+ """Base64 checksum of an annotation payload, or None for an algorithm that+ is not an annotation's or that MiniStack cannot compute."""+ algo = (algorithm or "").upper().replace("_", "")+ if algo not in _ANNOTATION_CHECKSUM_ALGORITHMS:+ return None+ if algo == "SHA512":+ return base64.b64encode(hashlib.sha512(data).digest()).decode()+ if algo == "MD5":+ return base64.b64encode(hashlib.md5(data).digest()).decode()+ if algo == "XXHASH64":+ return base64.b64encode(struct.pack(">Q", _xxh64(data))).decode()+ return _compute_s3_checksum(algo, data)+++def _annotation_checksum_unsupported(algorithm: str) -> tuple:+ supported = ", ".join(a for a in _ANNOTATION_CHECKSUM_ALGORITHMS if _annotation_checksum(a, b"") is not None)+ return _error(+ "InvalidRequest",+ f"Checksum algorithm not supported: {algorithm}. Supported: {supported}.",+ 400,+ )+++def _resolve_annotation_checksums(payload: bytes, headers: dict):+ """The checksum stored with an annotation, and the refusal for a bad one.++ One algorithm per payload: the one the client sent a value for, or named+ in x-amz-sdk-checksum-algorithm, or else CRC64NVME ("If the annotation+ doesn't have a specified checksum algorithm or checksum value, Amazon S3+ uses the CRC-64/NVME algorithm"). A value sent is checked against the+ payload (BadDigest), as PutObject checks its body; so is Content-MD5.+ Returns ``(checksums, error_or_None)``."""+ provided = {+ alg: headers[f"x-amz-checksum-{alg.lower()}"]+ for alg in _ANNOTATION_CHECKSUM_ALGORITHMS+ if headers.get(f"x-amz-checksum-{alg.lower()}")+ }+ requested = (headers.get("x-amz-sdk-checksum-algorithm") or "").upper().replace("_", "")+ if requested and requested not in _ANNOTATION_CHECKSUM_ALGORITHMS:+ return {}, _error("InvalidRequest", "Value for x-amz-sdk-checksum-algorithm header is invalid.", 400)+ if len(provided) > 1:+ return {}, _error(+ "InvalidRequest",+ "Expecting a single x-amz-checksum- header. Multiple checksum Types are not allowed.",+ 400,+ )+ algorithm = next(iter(provided), None) or requested or "CRC64NVME"+ if requested and provided and requested != algorithm:+ return {}, _error(+ "InvalidRequest",+ f"Value for x-amz-sdk-checksum-algorithm header is invalid: {requested} does not match "+ f"the x-amz-checksum-{algorithm.lower()} header sent.",+ 400,+ )+ computed = _annotation_checksum(algorithm, payload)+ if computed is None:+ return {}, _annotation_checksum_unsupported(algorithm)+ if algorithm in provided and provided[algorithm] != computed:+ return {}, _error("BadDigest", f"The {algorithm} you specified did not match the calculated checksum.", 400)+ content_md5 = headers.get("content-md5")+ if content_md5 and content_md5 != base64.b64encode(hashlib.md5(payload).digest()).decode():+ return {}, _error("BadDigest", "The Content-MD5 you specified did not match what we received.", 400)+ return {algorithm: computed}, None+++def _annotation_name_error(name: str) -> tuple | None:+ """The annotation naming rules: 1 to 512 bytes of letters (any language),+ digits, underscore, period and hyphen, not all whitespace, not starting+ with "aws" or "s3" in any case (S3 User Guide, "Annotation naming rules")."""+ if not name or not name.strip():+ return _error("InvalidAnnotationName", "The annotation name you provided is invalid.", 400)+ if len(name.encode("utf-8")) > _ANNOTATION_MAX_NAME_BYTES:+ return _error("AnnotationNameTooLong", "The annotation name exceeds 512 bytes.", 400)+ if name.lower().startswith(("aws", "s3")) or not all(+ ch.isalpha() or ch in _ANNOTATION_NAME_PUNCTUATION for ch in name+ ):+ return _error("InvalidAnnotationName", "The annotation name you provided is invalid.", 400)+ return None+++def _annotation_target(bucket_name: str, key: str, query_params: dict):+ """The object version an annotation operation acts on.++ Returns ``((bucket, version_key, record), None)`` or ``(None, error)``:+ `version_key` keys the version's annotations (None for the object without+ a version id, as for tags) and `record` is the current-object record or+ version entry, for its ETag and encryption. With no ``versionId`` it is+ the current object; a key whose current version is a delete marker is+ NoSuchKey, as a GetObject of it is. A ``versionId`` naming a delete marker+ is refused as a read of one is (inference: the documentation is silent)."""+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return None, _no_such_bucket(bucket_name)+ vid = _qp(query_params or {}, "versionId", "")+ current = bucket["objects"].get(key)+ if not vid:+ if current is None:+ status, err_headers, err_body = _error(+ "NoSuchKey", "The specified key does not exist.", 404, f"/{bucket_name}/{key}"+ )+ err_headers = dict(err_headers)+ err_headers.update(_delete_marker_404_headers(bucket_name, key))+ return None, (status, err_headers, err_body)+ return (bucket, current.get("version_id"), current), None+ if vid == "null" and current is not None and not current.get("version_id"):+ return (bucket, None, current), None+ entry = next((v for v in _object_versions.get((bucket_name, key), []) if v["version_id"] == vid), None)+ if entry is None:+ return None, _error("NoSuchVersion", "The specified version does not exist.", 404, f"/{bucket_name}/{key}")+ if entry.get("is_delete_marker"):+ return None, _delete_marker_read_refused(entry)+ return (bucket, None if vid == "null" else vid, entry), None+++def _annotation_version_header(bucket_name: str, version_key: str | None) -> dict:+ """x-amz-object-version-id: the version annotated. The object without a+ version id is "null" in a bucket that has had versioning; in one that+ never has, the header is left off, as x-amz-version-id is."""+ if version_key:+ return {"x-amz-object-version-id": version_key}+ if _bucket_versioning.get(bucket_name) in ("Enabled", "Suspended"):+ return {"x-amz-object-version-id": "null"}+ return {}+++def _annotation_sse_headers(record: dict) -> dict:+ """Annotations take the parent object's encryption: SSE-KMS and DSSE-KMS+ with the object's key, and SSE-S3 otherwise, including for an object with+ no server-side encryption (S3 User Guide, "Encryption")."""+ sse = _stored_sse_headers(record)+ out = {"x-amz-server-side-encryption": sse.get("x-amz-server-side-encryption") or "AES256"}+ if sse.get("x-amz-server-side-encryption-aws-kms-key-id"):+ out["x-amz-server-side-encryption-aws-kms-key-id"] = sse["x-amz-server-side-encryption-aws-kms-key-id"]+ return out+++def _annotation_if_match(headers: dict, record: dict) -> tuple | None:+ """x-amz-object-if-match: the operation "only succeeds if the object's ETag+ matches the provided value"; it checks the object, never the annotation."""+ expected = headers.get("x-amz-object-if-match")+ if expected and expected != "*" and expected.strip('"') != (record.get("etag") or "").strip('"'):+ return _error("PreconditionFailed", "At least one of the pre-conditions you specified did not hold", 412)+ return None+++def _annotation_checksum_headers(entry: dict) -> dict:+ out = {f"x-amz-checksum-{alg.lower()}": value for alg, value in (entry.get("checksums") or {}).items()}+ if out:+ out["x-amz-checksum-type"] = "FULL_OBJECT"+ return out+++def _annotation_lock_error(bucket_name: str, key: str, headers: dict) -> tuple | None:+ """Object Lock over an annotation write (put, overwrite or delete), as AWS answers it.++ Observed on AWS (ap-southeast-2, 2026-09-28): governance retention refuses+ both unless x-amz-bypass-governance-retention is true; compliance retention+ and a legal hold refuse both whatever the header says. Each refusal is 403+ AccessDenied, naming retention or the legal hold.+ """+ if _object_legal_hold.get((bucket_name, key)) == "ON":+ return _error("AccessDenied", "Access Denied because object protected by object lock legal hold.", 403)+ retention = _object_retention.get((bucket_name, key))+ if not retention:+ return None+ retain_until = retention.get("RetainUntilDate", "")+ if not retain_until or retain_until <= now_iso():+ return None+ mode = retention.get("Mode", "")+ bypass = headers.get("x-amz-bypass-governance-retention", "").lower() == "true"+ if mode == "COMPLIANCE" or (mode == "GOVERNANCE" and not bypass):+ return _error("AccessDenied", "Access Denied because object protected by object lock retention.", 403)+ return None+++def _put_object_annotation(bucket_name: str, key: str, body: bytes, headers: dict, query_params: dict):+ name = _qp(query_params, "annotationName", "")+ name_error = _annotation_name_error(name)+ if name_error:+ return name_error+ target, error = _annotation_target(bucket_name, key, query_params)+ if error:+ return error+ bucket, version_key, record = target+ lock_error = _annotation_lock_error(bucket_name, key, headers)+ if lock_error:+ return lock_error+ precondition = _annotation_if_match(headers, record)+ if precondition:+ return precondition+ if _stored_sse_headers(record).get("x-amz-server-side-encryption-customer-algorithm"):+ return _error("InvalidRequest", "Objects encrypted with SSE-C cannot have annotations.", 400)+ payload = body or b""+ if not payload or len(payload) > _ANNOTATION_MAX_PAYLOAD:+ return _error("InvalidRequest", "An annotation payload must be between 1 byte and 1 MiB.", 400)+ try:+ text = payload.decode("utf-8")+ except UnicodeDecodeError:+ return _error("UnsupportedMediaType", "The annotation payload is not valid UTF-8 encoded text.", 415)+ checksums, checksum_error = _resolve_annotation_checksums(payload, headers)+ if checksum_error:+ return checksum_error++ store_key = (bucket_name, key, version_key)+ annotations = dict(_object_annotations.get(store_key) or {})+ if name not in annotations and len(annotations) >= _ANNOTATION_MAX_PER_VERSION:+ return _error(+ "AnnotationLimitExceeded",+ "The request would exceed the maximum number of annotations allowed per object.",+ 400,+ )+ entry = {+ "payload": text,+ "size": len(payload),+ "etag": f'"{md5_hash(payload)}"',+ "last_modified": now_iso(),+ "checksums": checksums,+ }+ # "If you have S3 Replication configured on your bucket, Amazon S3+ # replicates annotations automatically": onto the replica of the version,+ # when it is the one this bucket replicated.+ current = bucket["objects"].get(key)+ if current is not None and current.get("version_id") == version_key and current.get("_replica"):+ replica_bucket, replica_version = current["_replica"]+ replica_key = (replica_bucket, key, replica_version)+ replica_annotations = dict(_object_annotations.get(replica_key) or {})+ replica_annotations[name] = dict(entry, replication_status="REPLICA")+ _object_annotations[replica_key] = replica_annotations+ _persist_version_state(replica_bucket, key, _buckets[replica_bucket])+ entry["replication_status"] = "COMPLETED"+ annotations[name] = entry+ _object_annotations[store_key] = annotations+ _persist_version_state(bucket_name, key, bucket)++ version_headers = _annotation_version_header(bucket_name, version_key)+ _fire_s3_event_async(+ bucket_name,+ key,+ "s3:ObjectAnnotation:Put",+ size=record.get("size", 0),+ etag=record.get("etag", ""),+ version_id=version_headers.get("x-amz-object-version-id"),+ record_extra={"objectAnnotation": [{"name": name, "size": entry["size"], "eTag": entry["etag"].strip('"')}]},+ )++ resp_headers = {"Content-Type": "application/xml", "ETag": entry["etag"]}+ resp_headers.update(version_headers)+ resp_headers.update(_annotation_checksum_headers(entry))+ resp_headers.update(_annotation_sse_headers(record))+ root = Element("PutObjectAnnotationOutput", xmlns=S3_NS)+ SubElement(root, "Key").text = key+ SubElement(root, "AnnotationName").text = name+ return 200, resp_headers, _xml_body(root)+++def _get_object_annotation(bucket_name: str, key: str, headers: dict, query_params: dict):+ name = _qp(query_params, "annotationName", "")+ name_error = _annotation_name_error(name)+ if name_error:+ return name_error+ target, error = _annotation_target(bucket_name, key, query_params)+ if error:+ return error+ _bucket, version_key, record = target+ entry = (_object_annotations.get((bucket_name, key, version_key)) or {}).get(name)+ if entry is None:+ return _error(+ "NoSuchAnnotation", "The specified annotation does not exist on this object.", 404, f"/{bucket_name}/{key}"+ )+ payload = entry["payload"].encode("utf-8")+ resp_headers = {+ "Content-Type": "application/octet-stream",+ "Content-Length": str(len(payload)),+ "ETag": entry["etag"],+ "Last-Modified": iso_to_rfc7231(entry["last_modified"]),+ }+ resp_headers.update(_annotation_version_header(bucket_name, version_key))+ resp_headers.update(_annotation_sse_headers(record))+ if entry.get("replication_status"):+ resp_headers["x-amz-replication-status"] = entry["replication_status"]+ # As for GetObject, stored checksums come back only when asked for.+ if (headers.get("x-amz-checksum-mode") or "").upper() == "ENABLED":+ resp_headers.update(_annotation_checksum_headers(entry))+ return 200, resp_headers, payload+++def _list_object_annotations(bucket_name: str, key: str, query_params: dict):+ target, error = _annotation_target(bucket_name, key, query_params)+ if error:+ return error+ _bucket, version_key, _record = target+ prefix = _qp(query_params, "annotation-prefix", "")+ if len(prefix.encode("utf-8")) > _ANNOTATION_MAX_NAME_BYTES:+ return _error("InvalidPrefix", "The annotation prefix you provided is invalid.", 400)+ raw_max = _qp(query_params, "max-annotation-results", "")+ try:+ max_results = int(raw_max) if raw_max else _ANNOTATION_MAX_PER_VERSION+ except ValueError:+ max_results = 0+ if not 1 <= max_results <= _ANNOTATION_MAX_PER_VERSION:+ return _error("InvalidArgument", "max-annotation-results must be between 1 and 1000.", 400)+ token = _qp(query_params, "continuation-token", "")+ after = ""+ if token:+ try:+ after = base64.urlsafe_b64decode(token.encode()).decode("utf-8")+ except (ValueError, UnicodeDecodeError):+ return _error("InvalidArgument", "The continuation token provided is incorrect.", 400)++ # Names in UTF-8 binary order, as S3 lists keys (inference: the operation+ # documents no order); the token is the last name returned.+ annotations = _object_annotations.get((bucket_name, key, version_key)) or {}+ names = sorted(+ (n for n in annotations if n.startswith(prefix) and (not after or n.encode() > after.encode())),+ key=lambda n: n.encode("utf-8"),+ )+ page = names[:max_results]++ root = Element("ListObjectAnnotationsOutput", xmlns=S3_NS)+ listed = SubElement(root, "Annotations")+ for name in page:+ entry = annotations[name]+ el = SubElement(listed, "AnnotationEntry")+ SubElement(el, "AnnotationName").text = name+ for alg in entry.get("checksums") or {}:+ SubElement(el, "ChecksumAlgorithm").text = alg+ SubElement(el, "ETag").text = entry["etag"]+ SubElement(el, "LastModified").text = entry["last_modified"]+ if entry.get("replication_status"):+ SubElement(el, "ReplicationStatus").text = entry["replication_status"]+ SubElement(el, "Size").text = str(entry["size"])+ SubElement(root, "Bucket").text = bucket_name+ SubElement(root, "Key").text = key+ if prefix:+ SubElement(root, "AnnotationPrefix").text = prefix+ SubElement(root, "MaxAnnotationResults").text = str(max_results)+ SubElement(root, "AnnotationCount").text = str(len(page))+ if token:+ SubElement(root, "ContinuationToken").text = token+ if len(names) > max_results:+ SubElement(root, "NextContinuationToken").text = base64.urlsafe_b64encode(page[-1].encode()).decode()+ resp_headers = {"Content-Type": "application/xml"}+ resp_headers.update(_annotation_version_header(bucket_name, version_key))+ return 200, resp_headers, _xml_body(root)+++def _delete_object_annotation(bucket_name: str, key: str, headers: dict, query_params: dict):+ name = _qp(query_params, "annotationName", "")+ name_error = _annotation_name_error(name)+ if name_error:+ return name_error+ target, error = _annotation_target(bucket_name, key, query_params)+ if error:+ return error+ bucket, version_key, record = target+ lock_error = _annotation_lock_error(bucket_name, key, headers)+ if lock_error:+ return lock_error+ precondition = _annotation_if_match(headers, record)+ if precondition:+ return precondition+ store_key = (bucket_name, key, version_key)+ annotations = dict(_object_annotations.get(store_key) or {})+ version_headers = _annotation_version_header(bucket_name, version_key)+ # Deleting an annotation that is not there succeeds, as the operation+ # documents no NoSuchAnnotation; only a real delete sends the event.+ if annotations.pop(name, None) is not None:+ if annotations:+ _object_annotations[store_key] = annotations+ else:+ _object_annotations.pop(store_key, None)+ _persist_version_state(bucket_name, key, bucket)+ _fire_s3_event_async(+ bucket_name,+ key,+ "s3:ObjectAnnotation:Delete",+ size=record.get("size", 0),+ etag=record.get("etag", ""),+ version_id=version_headers.get("x-amz-object-version-id"),+ record_extra={"objectAnnotation": [{"name": name}]},+ )+ return 204, version_headers, b""++# ---------------------------------------------------------------------------# Object Lock# ---------------------------------------------------------------------------@@ -6045,6 +6594,7 @@ def _delete_objects(bucket_name: str, body: bytes, headers: dict = None):_fire_s3_event_async(bucket_name, k, "s3:ObjectRemoved:Delete")bucket["objects"].pop(k, None)_object_tags.pop((bucket_name, k, None), None)+ _object_annotations.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), None)@@ -6790,7 +7340,7 @@ def _key_history_meta(bucket_name: str, key: str) -> dict:if versions:extra["versions"] = [{k: v for k, v in e.items() if k != "data"} for e in versions]vids = [None] + [v["version_id"] for v in versions if v["version_id"] != "null" and not v.get("is_delete_marker")]- for field, store in (("tags", _object_tags), ("acl", _object_acl)):+ for field, store in (("tags", _object_tags), ("acl", _object_acl), ("annotations", _object_annotations)):found = {vid or "null": store.get((bucket_name, key, vid)) for vid in vids}found = {vid: value for vid, value in found.items() if value is not None}if found:@@ -7110,7 +7660,7 @@ def _load_persisted_history(account_id, bucket, bucket_name, key, meta):live = {v["version_id"] for v in versions if not v.get("is_delete_marker")}if current is not None and not current.get("version_id"):live.add("null")- for field, store in (("tags", _object_tags), ("acl", _object_acl)):+ for field, store in (("tags", _object_tags), ("acl", _object_acl), ("annotations", _object_annotations)):for vid, value in (meta.get(field) or {}).items():if vid in live:store._data[(account_id, (bucket_name, key, None if vid == "null" else vid))] = value@@ -7125,7 +7675,7 @@ def reset():global _bucket_versioning, _bucket_encryption, _bucket_lifecycle, _bucket_corsglobal _bucket_acl, _bucket_websites, _bucket_logging_configglobal _bucket_accelerate_config, _bucket_request_payment_config- global _object_tags, _multipart_uploads, _object_versions, _object_acl+ global _object_tags, _multipart_uploads, _object_versions, _object_acl, _object_annotationsglobal _bucket_object_lock, _bucket_replication, _object_retention, _object_legal_holdfor d in (_buckets,@@ -7143,6 +7693,7 @@ def reset():_bucket_request_payment_config,_object_tags,_object_acl,+ _object_annotations,_multipart_uploads,_completed_multipart_uploads,_bucket_object_lock,diff --git a/tests/test_s3_annotations.py b/tests/test_s3_annotations.pynew file mode 100644index 00000000..943324e4--- /dev/null+++ b/tests/test_s3_annotations.py@@ -0,0 +1,659 @@+"""S3 object annotations: PutObjectAnnotation, GetObjectAnnotation,+ListObjectAnnotations and DeleteObjectAnnotation, and how annotations follow+object versions, CopyObject, deletes, replication, encryption, Object Lock,+restarts and event notifications.++Evidence: the S3 API Reference pages for the four operations, the S3 User+Guide's "Annotating your objects", "Event notification types and+destinations" and "Event message structure" pages, and the botocore s3 model.+Not validated against a real AWS account."""++import base64+import hashlib+import json+import os+import struct+import time+import uuid++import pytest+from botocore.exceptions import ClientError+from conftest import make_client+++def _bucket(s3, versioned=False, **create):+ name = f"annot-{uuid.uuid4().hex[:12]}"+ s3.create_bucket(Bucket=name, **create)+ if versioned:+ s3.put_bucket_versioning(Bucket=name, VersioningConfiguration={"Status": "Enabled"})+ return name+++def _code(exc):+ return exc.value.response["Error"]["Code"]+++def _status(exc):+ return exc.value.response["ResponseMetadata"]["HTTPStatusCode"]+++def _crc64nvme_bitwise(data: bytes) -> int:+ """Bit-at-a-time CRC-64/NVME, independent of the server's table."""+ crc = 0xFFFFFFFFFFFFFFFF+ for byte in data:+ crc ^= byte+ for _ in range(8):+ crc = (crc >> 1) ^ 0x9A6C9329AC4BC9B5 if crc & 1 else crc >> 1+ return crc ^ 0xFFFFFFFFFFFFFFFF+++# ── Put / Get ──────────────────────────────────────────────────────────+++def test_put_and_get_an_annotation(s3):+ bucket = _bucket(s3, versioned=True)+ payload = b'{"archive":"Images"}'+ put = s3.put_object(Bucket=bucket, Key="photo.jpg", Body=b"jpeg")+ out = s3.put_object_annotation(Bucket=bucket, Key="photo.jpg", AnnotationName="nexus.system", AnnotationPayload=payload)+ assert out["ObjectVersionId"] == put["VersionId"]+ assert out["ETag"] == f'"{hashlib.md5(payload).hexdigest()}"'+ got = s3.get_object_annotation(Bucket=bucket, Key="photo.jpg", AnnotationName="nexus.system")+ assert got["AnnotationPayload"].read() == payload+ assert got["ObjectVersionId"] == put["VersionId"]+ assert got["ContentLength"] == len(payload)+ assert got["ServerSideEncryption"] == "AES256"+++def test_an_annotation_leaves_the_object_alone(s3):+ """"Adding, updating, or removing an annotation does not modify the parent+ object's ETag", and makes no new version."""+ bucket = _bucket(s3, versioned=True)+ put = s3.put_object(Bucket=bucket, Key="k", Body=b"body")+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"1")+ head = s3.head_object(Bucket=bucket, Key="k")+ assert head["ETag"] == put["ETag"] and head["VersionId"] == put["VersionId"]+ assert len(s3.list_object_versions(Bucket=bucket)["Versions"]) == 1+ assert s3.get_object(Bucket=bucket, Key="k")["Body"].read() == b"body"+++def test_putting_again_replaces_the_payload(s3):+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="k", Body=b"x")+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"first")+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"second")+ got = s3.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="a")+ assert got["AnnotationPayload"].read() == b"second"+++def test_get_of_a_missing_annotation(s3):+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="k", Body=b"x")+ with pytest.raises(ClientError) as exc:+ s3.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="absent")+ assert (_code(exc), _status(exc)) == ("NoSuchAnnotation", 404)+++def test_annotation_on_a_missing_key_or_bucket(s3):+ bucket = _bucket(s3)+ with pytest.raises(ClientError) as exc:+ s3.put_object_annotation(Bucket=bucket, Key="nope", AnnotationName="a", AnnotationPayload=b"1")+ assert _code(exc) == "NoSuchKey"+ with pytest.raises(ClientError) as exc:+ s3.get_object_annotation(Bucket=f"missing-{uuid.uuid4().hex[:8]}", Key="k", AnnotationName="a")+ assert _code(exc) == "NoSuchBucket"+++ "name, code",+ [+ ("aws.reserved", "InvalidAnnotationName"),+ ("AWSthing", "InvalidAnnotationName"),+ ("s3-thing", "InvalidAnnotationName"),+ ("S3", "InvalidAnnotationName"),+ ("has space", "InvalidAnnotationName"),+ ("slash/name", "InvalidAnnotationName"),+ (" ", "InvalidAnnotationName"),+ ("n" * 513, "AnnotationNameTooLong"),+ ],+)+def test_annotation_naming_rules(s3, name, code):+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="k", Body=b"x")+ with pytest.raises(ClientError) as exc:+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName=name, AnnotationPayload=b"1")+ assert (_code(exc), _status(exc)) == (code, 400)+++def test_names_may_use_letters_of_any_language(s3):+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="k", Body=b"x")+ for name in ("données_1.2-3", "名前", "n" * 512):+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName=name, AnnotationPayload=b"1")+++def test_payload_limits(s3):+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="k", Body=b"x")+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="max", AnnotationPayload=b"a" * (1024 * 1024))+ with pytest.raises(ClientError) as exc:+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="big", AnnotationPayload=b"a" * (1024 * 1024 + 1))+ assert _code(exc) == "InvalidRequest"+ with pytest.raises(ClientError) as exc:+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="empty", AnnotationPayload=b"")+ assert _code(exc) == "InvalidRequest"+++def test_payload_must_be_utf8(s3):+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="k", Body=b"x")+ with pytest.raises(ClientError) as exc:+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="bin", AnnotationPayload=b"\xff\xfe")+ assert (_code(exc), _status(exc)) == ("UnsupportedMediaType", 415)+++def test_a_version_holds_at_most_1000_annotations(s3):+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="k", Body=b"x")+ for i in range(1000):+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName=f"n{i}", AnnotationPayload=b"1")+ with pytest.raises(ClientError) as exc:+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="n1000", AnnotationPayload=b"1")+ assert _code(exc) == "AnnotationLimitExceeded"+ # Replacing one of the thousand is not a new one.+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="n0", AnnotationPayload=b"2")+++def test_object_if_match(s3):+ bucket = _bucket(s3)+ etag = s3.put_object(Bucket=bucket, Key="k", Body=b"x")["ETag"]+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"1", ObjectIfMatch=etag)+ with pytest.raises(ClientError) as exc:+ s3.put_object_annotation(+ Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"2", ObjectIfMatch='"deadbeef"'+ )+ assert _status(exc) == 412+ with pytest.raises(ClientError) as exc:+ s3.delete_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", ObjectIfMatch='"deadbeef"')+ assert _status(exc) == 412+ s3.delete_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", ObjectIfMatch=etag)+++# ── Checksums ──────────────────────────────────────────────────────────+++def test_default_checksum_is_crc64nvme(s3):+ """"If the annotation doesn't have a specified checksum algorithm or+ checksum value, Amazon S3 uses the CRC-64/NVME algorithm"."""+ plain = make_client("s3", {"request_checksum_calculation": "when_required"})+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="k", Body=b"x")+ out = plain.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"123456789")+ expected = base64.b64encode(struct.pack(">Q", _crc64nvme_bitwise(b"123456789"))).decode()+ assert out["ChecksumCRC64NVME"] == expected+ got = s3.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", ChecksumMode="ENABLED")+ assert got["ChecksumCRC64NVME"] == expected+ # Only when asked: a client that does not send x-amz-checksum-mode gets none back.+ unasked = make_client("s3", {"response_checksum_validation": "when_required"})+ assert "ChecksumCRC64NVME" not in unasked.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="a")+++ "member, digest",+ [+ ("ChecksumSHA256", lambda b: hashlib.sha256(b).digest()),+ ("ChecksumSHA512", lambda b: hashlib.sha512(b).digest()),+ ("ChecksumMD5", lambda b: hashlib.md5(b).digest()),+ # XXH64's published check value for b"abc" (the xxHash reference).+ ("ChecksumXXHASH64", lambda b: struct.pack(">Q", 0x44BC2CF5AD770999)),+ ],+)+def test_a_checksum_sent_is_verified(s3, member, digest):+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="k", Body=b"x")+ good = base64.b64encode(digest(b"abc")).decode()+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"abc", **{member: good})+ got = s3.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", ChecksumMode="ENABLED")+ assert got[member] == good and got["ChecksumType"] == "FULL_OBJECT"+ bad = base64.b64encode(bytes(x ^ 0xFF for x in digest(b"abc"))).decode()+ with pytest.raises(ClientError) as exc:+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"abc", **{member: bad})+ assert _code(exc) == "BadDigest"+++def test_xxh64_check_values():+ from ministack.services import s3 as s3mod++ assert s3mod._xxh64(b"") == 0xEF46DB3751D8E999+ assert s3mod._xxh64(b"abc") == 0x44BC2CF5AD770999+ # Past the 32-byte stripe loop, against the reference implementation's output.+ assert s3mod._xxh64(b"Nobody inspects the spammish repetition") == 0xFBCEA83C8A378BF1+++def test_an_algorithm_ministack_cannot_compute_is_refused(s3):+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="k", Body=b"x")+ with pytest.raises(ClientError) as exc:+ s3.put_object_annotation(+ Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"abc", ChecksumXXHASH3="AAAAAAAAAAA="+ )+ assert _code(exc) == "InvalidRequest"+++# ── Encryption ─────────────────────────────────────────────────────────+++def test_annotations_take_the_objects_encryption(s3):+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="k", Body=b"x", ServerSideEncryption="aws:kms", SSEKMSKeyId="alias/annot")+ out = s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"1")+ assert out["ServerSideEncryption"] == "aws:kms"+ got = s3.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="a")+ assert got["ServerSideEncryption"] == "aws:kms"+++def test_sse_c_objects_cannot_have_annotations(s3):+ bucket = _bucket(s3)+ key = os.urandom(32)+ s3.put_object(+ Bucket=bucket,+ Key="k",+ Body=b"x",+ SSECustomerAlgorithm="AES256",+ SSECustomerKey=key,+ )+ with pytest.raises(ClientError) as exc:+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"1")+ assert _code(exc) == "InvalidRequest"+++# ── Versions ───────────────────────────────────────────────────────────+++def test_annotations_belong_to_one_version(s3):+ bucket = _bucket(s3, versioned=True)+ v1 = s3.put_object(Bucket=bucket, Key="k", Body=b"one")["VersionId"]+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"on v1")+ v2 = s3.put_object(Bucket=bucket, Key="k", Body=b"two")["VersionId"]+ # "Creating a new version does not copy annotations from the previous version."+ with pytest.raises(ClientError) as exc:+ s3.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="a")+ assert _code(exc) == "NoSuchAnnotation"+ got = s3.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", VersionId=v1)+ assert got["AnnotationPayload"].read() == b"on v1" and got["ObjectVersionId"] == v1+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"on v2")+ assert s3.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", VersionId=v2)["AnnotationPayload"].read() == b"on v2"+ assert s3.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", VersionId=v1)["AnnotationPayload"].read() == b"on v1"+++def test_a_delete_marker_keeps_the_versions_annotations(s3):+ bucket = _bucket(s3, versioned=True)+ v1 = s3.put_object(Bucket=bucket, Key="k", Body=b"one")["VersionId"]+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"kept")+ marker = s3.delete_object(Bucket=bucket, Key="k")["VersionId"]+ with pytest.raises(ClientError) as exc:+ s3.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="a")+ assert _code(exc) == "NoSuchKey"+ with pytest.raises(ClientError) as exc:+ s3.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", VersionId=marker)+ assert _status(exc) == 405+ assert s3.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", VersionId=v1)["AnnotationPayload"].read() == b"kept"+ # Removing the marker brings the version back with its annotations.+ s3.delete_object(Bucket=bucket, Key="k", VersionId=marker)+ assert s3.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="a")["AnnotationPayload"].read() == b"kept"+++def test_deleting_a_version_deletes_its_annotations(s3):+ bucket = _bucket(s3, versioned=True)+ v1 = s3.put_object(Bucket=bucket, Key="k", Body=b"one")["VersionId"]+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"1")+ s3.put_object(Bucket=bucket, Key="k", Body=b"two")+ s3.delete_object(Bucket=bucket, Key="k", VersionId=v1)+ with pytest.raises(ClientError) as exc:+ s3.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", VersionId=v1)+ assert _code(exc) == "NoSuchVersion"+++def test_unversioned_overwrite_and_delete_drop_annotations(s3):+ """"In a non-versioned bucket, if you delete or overwrite the object, the+ annotations are deleted with it.\""""+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="k", Body=b"one")+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"1")+ s3.put_object(Bucket=bucket, Key="k", Body=b"two")+ with pytest.raises(ClientError) as exc:+ s3.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="a")+ assert _code(exc) == "NoSuchAnnotation"+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="b", AnnotationPayload=b"1")+ s3.delete_object(Bucket=bucket, Key="k")+ s3.put_object(Bucket=bucket, Key="k", Body=b"three")+ assert s3.list_object_annotations(Bucket=bucket, Key="k")["Annotations"] == []+++def test_batch_delete_drops_annotations(s3):+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="k", Body=b"one")+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"1")+ s3.delete_objects(Bucket=bucket, Delete={"Objects": [{"Key": "k"}]})+ s3.put_object(Bucket=bucket, Key="k", Body=b"two")+ assert s3.list_object_annotations(Bucket=bucket, Key="k")["Annotations"] == []+++def test_annotations_need_no_restore_for_archived_objects(s3):+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="cold", Body=b"x", StorageClass="GLACIER")+ s3.put_object_annotation(Bucket=bucket, Key="cold", AnnotationName="a", AnnotationPayload=b"1")+ assert s3.get_object_annotation(Bucket=bucket, Key="cold", AnnotationName="a")["AnnotationPayload"].read() == b"1"+++# ── List ───────────────────────────────────────────────────────────────+++def test_list_annotations(s3):+ bucket = _bucket(s3, versioned=True)+ version = s3.put_object(Bucket=bucket, Key="k", Body=b"x")["VersionId"]+ for name, payload in (("ml.label", b"cat"), ("etl.status", b"done"), ("ml.score", b"0.97")):+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName=name, AnnotationPayload=payload, ChecksumAlgorithm="SHA256")+ out = s3.list_object_annotations(Bucket=bucket, Key="k")+ assert [a["AnnotationName"] for a in out["Annotations"]] == ["etl.status", "ml.label", "ml.score"]+ assert out["AnnotationCount"] == 3 and out["ObjectVersionId"] == version+ assert out["Bucket"] == bucket and out["Key"] == "k"+ entry = out["Annotations"][1]+ assert entry["Size"] == 3 and entry["ETag"] == f'"{hashlib.md5(b"cat").hexdigest()}"'+ assert entry["ChecksumAlgorithm"] == ["SHA256"] and "LastModified" in entry+ assert "NextContinuationToken" not in out+++def test_list_annotations_by_prefix_and_page(s3):+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="k", Body=b"x")+ for i in range(5):+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName=f"page.{i}", AnnotationPayload=b"1")+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="other", AnnotationPayload=b"1")+ first = s3.list_object_annotations(Bucket=bucket, Key="k", AnnotationPrefix="page.", MaxAnnotationResults=2)+ assert [a["AnnotationName"] for a in first["Annotations"]] == ["page.0", "page.1"]+ assert first["AnnotationPrefix"] == "page." and first["MaxAnnotationResults"] == 2+ token = first["NextContinuationToken"]+ rest = s3.list_object_annotations(Bucket=bucket, Key="k", AnnotationPrefix="page.", ContinuationToken=token)+ assert [a["AnnotationName"] for a in rest["Annotations"]] == ["page.2", "page.3", "page.4"]+ assert rest["ContinuationToken"] == token and "NextContinuationToken" not in rest+++def test_list_rejects_a_bad_page_size_or_prefix(s3):+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="k", Body=b"x")+ plain = make_client("s3", {"parameter_validation": False})+ with pytest.raises(ClientError) as exc:+ plain.list_object_annotations(Bucket=bucket, Key="k", MaxAnnotationResults=1001)+ assert _code(exc) == "InvalidArgument"+ with pytest.raises(ClientError) as exc:+ s3.list_object_annotations(Bucket=bucket, Key="k", AnnotationPrefix="p" * 513)+ assert _code(exc) == "InvalidPrefix"+++# ── Delete ─────────────────────────────────────────────────────────────+++def test_delete_an_annotation(s3):+ bucket = _bucket(s3, versioned=True)+ version = s3.put_object(Bucket=bucket, Key="k", Body=b"x")["VersionId"]+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"1")+ out = s3.delete_object_annotation(Bucket=bucket, Key="k", AnnotationName="a")+ assert out["ResponseMetadata"]["HTTPStatusCode"] == 204 and out["ObjectVersionId"] == version+ with pytest.raises(ClientError) as exc:+ s3.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="a")+ assert _code(exc) == "NoSuchAnnotation"+ # Deleting one that is not there is not an error.+ s3.delete_object_annotation(Bucket=bucket, Key="k", AnnotationName="a")+++# Observed on AWS (ap-southeast-2, 2026-09-28): annotations are writes to the object version, so Object Lock guards+# PutObjectAnnotation and DeleteObjectAnnotation alike. Governance retention yields to+# x-amz-bypass-governance-retention; compliance retention and a legal hold refuse both, bypass or not.+++def _bypassing(operation):+ raw = make_client("s3")++ def bypass(request, **_):+ request.headers["x-amz-bypass-governance-retention"] = "true"++ raw.meta.events.register(f"before-sign.s3.{operation}", bypass)+ return raw+++def _refused(call, message):+ with pytest.raises(ClientError) as exc:+ call()+ assert _code(exc) == "AccessDenied"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403+ assert exc.value.response["Error"]["Message"] == message+++def _locked(s3, **lock):+ bucket = _bucket(s3, ObjectLockEnabledForBucket=True)+ s3.put_object(Bucket=bucket, Key="k", Body=b"x", **lock)+ return bucket+++def _until():+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + 3600))+++RETENTION = "Access Denied because object protected by object lock retention."+LEGAL_HOLD = "Access Denied because object protected by object lock legal hold."+++def test_governance_retention_needs_the_bypass_to_put_or_delete_an_annotation(s3):+ bucket = _locked(s3, ObjectLockMode="GOVERNANCE", ObjectLockRetainUntilDate=_until())+ _refused(lambda: s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"1"), RETENTION)+ _bypassing("PutObjectAnnotation").put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"1")+ _refused(lambda: s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"2"), RETENTION)+ _refused(lambda: s3.delete_object_annotation(Bucket=bucket, Key="k", AnnotationName="a"), RETENTION)+ _bypassing("DeleteObjectAnnotation").delete_object_annotation(Bucket=bucket, Key="k", AnnotationName="a")+++def test_compliance_retention_refuses_annotation_writes_even_with_the_bypass(s3):+ bucket = _locked(s3, ObjectLockMode="COMPLIANCE", ObjectLockRetainUntilDate=_until())+ def put(c):+ return c.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"1")++ def delete(c):+ return c.delete_object_annotation(Bucket=bucket, Key="k", AnnotationName="a")++ _refused(lambda: put(s3), RETENTION)+ _refused(lambda: put(_bypassing("PutObjectAnnotation")), RETENTION)+ _refused(lambda: delete(s3), RETENTION)+ _refused(lambda: delete(_bypassing("DeleteObjectAnnotation")), RETENTION)+++def test_a_legal_hold_refuses_annotation_writes_even_with_the_bypass(s3):+ bucket = _locked(s3, ObjectLockLegalHoldStatus="ON")+ def put(c):+ return c.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"1")++ def delete(c):+ return c.delete_object_annotation(Bucket=bucket, Key="k", AnnotationName="a")++ _refused(lambda: put(s3), LEGAL_HOLD)+ _refused(lambda: put(_bypassing("PutObjectAnnotation")), LEGAL_HOLD)+ _refused(lambda: delete(s3), LEGAL_HOLD)+ _refused(lambda: delete(_bypassing("DeleteObjectAnnotation")), LEGAL_HOLD)+++def test_an_unlocked_object_in_a_lock_enabled_bucket_takes_annotations_freely(s3):+ bucket = _locked(s3)+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"1")+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"2")+ s3.delete_object_annotation(Bucket=bucket, Key="k", AnnotationName="a")+++# ── CopyObject ─────────────────────────────────────────────────────────+++def test_copy_carries_annotations_by_default(s3):+ src = _bucket(s3, versioned=True)+ dst = _bucket(s3, versioned=True)+ s3.put_object(Bucket=src, Key="landing/x.jpg", Body=b"x")+ s3.put_object_annotation(Bucket=src, Key="landing/x.jpg", AnnotationName="nexus.system", AnnotationPayload=b"{}")+ copied = s3.copy_object(Bucket=dst, Key="assets/x.jpg", CopySource={"Bucket": src, "Key": "landing/x.jpg"})+ got = s3.get_object_annotation(Bucket=dst, Key="assets/x.jpg", AnnotationName="nexus.system")+ assert got["AnnotationPayload"].read() == b"{}" and got["ObjectVersionId"] == copied["VersionId"]+++def test_copy_of_a_named_version_carries_that_versions_annotations(s3):+ bucket = _bucket(s3, versioned=True)+ v1 = s3.put_object(Bucket=bucket, Key="k", Body=b"one")["VersionId"]+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"v1")+ s3.put_object(Bucket=bucket, Key="k", Body=b"two")+ s3.copy_object(Bucket=bucket, Key="copy", CopySource={"Bucket": bucket, "Key": "k", "VersionId": v1})+ assert s3.get_object_annotation(Bucket=bucket, Key="copy", AnnotationName="a")["AnnotationPayload"].read() == b"v1"+++def test_copy_with_exclude_leaves_them_behind(s3):+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="src", Body=b"x")+ s3.put_object_annotation(Bucket=bucket, Key="src", AnnotationName="a", AnnotationPayload=b"1")+ s3.copy_object(Bucket=bucket, Key="dst", CopySource={"Bucket": bucket, "Key": "src"}, AnnotationDirective="EXCLUDE")+ assert s3.list_object_annotations(Bucket=bucket, Key="dst")["Annotations"] == []+++def test_copy_rejects_an_unknown_directive(s3):+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="src", Body=b"x")+ plain = make_client("s3", {"parameter_validation": False})+ with pytest.raises(ClientError) as exc:+ plain.copy_object(Bucket=bucket, Key="dst", CopySource={"Bucket": bucket, "Key": "src"}, AnnotationDirective="REPLACE")+ assert _code(exc) == "InvalidArgument"+++def test_copy_with_a_new_algorithm_rechecksums_the_annotations(s3):+ """"If you specify a different checksum algorithm in the copy request, the+ new algorithm applies to both the object and its annotations.\""""+ bucket = _bucket(s3)+ s3.put_object(Bucket=bucket, Key="src", Body=b"x")+ s3.put_object_annotation(Bucket=bucket, Key="src", AnnotationName="a", AnnotationPayload=b"abc")+ s3.copy_object(Bucket=bucket, Key="dst", CopySource={"Bucket": bucket, "Key": "src"}, ChecksumAlgorithm="SHA256")+ got = s3.get_object_annotation(Bucket=bucket, Key="dst", AnnotationName="a", ChecksumMode="ENABLED")+ assert got["ChecksumSHA256"] == base64.b64encode(hashlib.sha256(b"abc").digest()).decode()+++# ── Replication ────────────────────────────────────────────────────────+++def test_annotations_replicate(s3):+ src = _bucket(s3, versioned=True)+ dst = _bucket(s3, versioned=True)+ s3.put_bucket_replication(+ Bucket=src,+ ReplicationConfiguration={+ "Role": "arn:aws:iam::000000000000:role/repl",+ "Rules": [{"ID": "r1", "Status": "Enabled", "Prefix": "", "Destination": {"Bucket": f"arn:aws:s3:::{dst}"}}],+ },+ )+ s3.put_object(Bucket=src, Key="k", Body=b"x")+ s3.put_object_annotation(Bucket=src, Key="k", AnnotationName="a", AnnotationPayload=b"1")+ assert s3.get_object_annotation(Bucket=src, Key="k", AnnotationName="a")["ReplicationStatus"] == "COMPLETED"+ replica = s3.get_object_annotation(Bucket=dst, Key="k", AnnotationName="a")+ assert replica["AnnotationPayload"].read() == b"1" and replica["ReplicationStatus"] == "REPLICA"+ listed = s3.list_object_annotations(Bucket=dst, Key="k")["Annotations"]+ assert [(a["AnnotationName"], a["ReplicationStatus"]) for a in listed] == [("a", "REPLICA")]+++# ── Event notifications ────────────────────────────────────────────────+++def _notified(s3, sqs, events, versioned=True):+ bucket = _bucket(s3, versioned=versioned)+ url = sqs.create_queue(QueueName=bucket)["QueueUrl"]+ arn = sqs.get_queue_attributes(QueueUrl=url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]+ s3.put_bucket_notification_configuration(+ Bucket=bucket, NotificationConfiguration={"QueueConfigurations": [{"QueueArn": arn, "Events": events}]}+ )+ return bucket, url+++def _records(sqs, url, expected, timeout=10):+ records = []+ deadline = time.time() + timeout+ while len(records) < expected and time.time() < deadline:+ for m in sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=10, WaitTimeSeconds=1).get("Messages", []):+ records.extend(json.loads(m["Body"]).get("Records", []))+ sqs.delete_message(QueueUrl=url, ReceiptHandle=m["ReceiptHandle"])+ return records+++def test_annotation_events(s3, sqs):+ bucket, url = _notified(s3, sqs, ["s3:ObjectAnnotation:*", "s3:ObjectCreated:*"])+ version = s3.put_object(Bucket=bucket, Key="k", Body=b"x")["VersionId"]+ assert [r["eventName"] for r in _records(sqs, url, 1)] == ["ObjectCreated:Put"]+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"abc")+ s3.delete_object_annotation(Bucket=bucket, Key="k", AnnotationName="a")+ records = sorted(_records(sqs, url, 2), key=lambda r: r["eventName"], reverse=True)+ # "PutObjectAnnotation and DeleteObjectAnnotation send only annotation-specific events."+ assert [r["eventName"] for r in records] == ["ObjectAnnotation:Put", "ObjectAnnotation:Delete"]+ put, delete = records+ assert put["objectAnnotation"] == [{"name": "a", "size": 3, "eTag": hashlib.md5(b"abc").hexdigest()}]+ assert delete["objectAnnotation"] == [{"name": "a"}]+ assert put["s3"]["object"]["versionId"] == version+ assert "sequencer" not in put["s3"]["object"]+++def test_get_and_list_send_no_events(s3, sqs):+ bucket, url = _notified(s3, sqs, ["s3:ObjectAnnotation:*"])+ s3.put_object(Bucket=bucket, Key="k", Body=b"x")+ s3.put_object_annotation(Bucket=bucket, Key="k", AnnotationName="a", AnnotationPayload=b"1")+ assert len(_records(sqs, url, 1)) == 1+ s3.get_object_annotation(Bucket=bucket, Key="k", AnnotationName="a")+ s3.list_object_annotations(Bucket=bucket, Key="k")+ assert _records(sqs, url, 1, timeout=2) == []+++def test_copy_event_says_whether_annotations_came(s3, sqs):+ bucket, url = _notified(s3, sqs, ["s3:ObjectCreated:Copy"])+ s3.put_object(Bucket=bucket, Key="src", Body=b"x")+ s3.put_object_annotation(Bucket=bucket, Key="src", AnnotationName="a", AnnotationPayload=b"1")+ s3.copy_object(Bucket=bucket, Key="with", CopySource={"Bucket": bucket, "Key": "src"})+ s3.copy_object(Bucket=bucket, Key="without", CopySource={"Bucket": bucket, "Key": "src"}, AnnotationDirective="EXCLUDE")+ flags = {r["s3"]["object"]["key"]: r["s3"]["object"]["hasObjectAnnotation"] for r in _records(sqs, url, 2)}+ assert flags == {"with": True, "without": False}+++# ── Persistence ────────────────────────────────────────────────────────+++def s3_persist(tmp_path, monkeypatch):+ """S3 in this process with persistence on, over a throwaway DATA_DIR."""+ from ministack.core import responses as respmod+ from ministack.services import s3 as s3mod++ monkeypatch.setattr(s3mod, "DATA_DIR", str(tmp_path))+ monkeypatch.setattr(s3mod, "S3_PERSIST", True)+ monkeypatch.setattr(s3mod, "get_account_id", lambda: "000000000000")+ monkeypatch.setattr(respmod, "get_account_id", lambda: "000000000000")+ stores = (s3mod._buckets._data, s3mod._object_versions._data, s3mod._bucket_versioning._data, s3mod._object_annotations._data)+ before = [set(store) for store in stores]+ yield s3mod+ for store, keys in zip(stores, before):+ for key in set(store) - keys:+ store.pop(key, None)+++def test_annotations_survive_a_restart(s3_persist, tmp_path):+ s3mod = s3_persist+ bucket = "qa-annot-persist"+ s3mod._create_bucket(bucket, b"")+ s3mod._bucket_versioning[bucket] = "Enabled"+ v1 = s3mod._put_object(bucket, "k", b"one", {})[1]["x-amz-version-id"]+ s3mod._put_object_annotation(bucket, "k", b"on v1", {}, {"annotationName": ["a"]})+ v2 = s3mod._put_object(bucket, "k", b"two", {})[1]["x-amz-version-id"]+ s3mod._put_object_annotation(bucket, "k", b"on v2", {}, {"annotationName": ["a"]})++ s3mod._buckets._data.pop(("000000000000", bucket), None)+ for store in (s3mod._object_versions._data, s3mod._object_annotations._data):+ for k in [k for k in store if k[0] == "000000000000" and k[1][0] == bucket]:+ store.pop(k, None)+ s3mod._load_persisted_bucket("000000000000", bucket, os.path.join(str(tmp_path), "000000000000", bucket))++ assert s3mod._object_annotations[(bucket, "k", v1)]["a"]["payload"] == "on v1"+ assert s3mod._object_annotations[(bucket, "k", v2)]["a"]["payload"] == "on v2"