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): carry multipart checksums through to a composite (#1453)
Andrew Gaul2b8d7afe51a7
diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex b1a0830e..c2814d95 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -1028,6 +1028,78 @@ def _resolve_object_checksums(body: bytes, headers: dict):return checksums, None+def _resolve_multipart_checksum_algorithm(headers: dict):+ """Read the algorithm CreateMultipartUpload names for its parts.++ Returns ``(algorithm_or_None, error_response_or_None)``. An algorithm+ ministack cannot compute is refused here rather than at completion, where+ the caller has already uploaded every part.+ """+ raw = (headers.get("x-amz-checksum-algorithm")+ or headers.get("x-amz-sdk-checksum-algorithm"))+ if not raw:+ return None, None+ algorithm = raw.upper().replace("_", "")+ if _compute_s3_checksum(algorithm, b"") is None:+ return None, _error(+ "InvalidRequest",+ (+ f"Checksum algorithm not supported in this ministack build: "+ f"{algorithm}. Supported: SHA256, SHA1, CRC32, CRC64NVME."+ ),+ 400,+ )+ return algorithm, None+++def _resolve_part_checksums(body: bytes, headers: dict, upload: dict):+ """Build a part's checksum dict, validating whatever the caller supplied.++ A part carrying its own ``x-amz-checksum-*`` header is validated against+ the bytes the same way PutObject validates one. A part that carries none+ still gets the upload's algorithm computed for it, since the completion+ builds the composite out of every part's digest and AWS asks the caller+ for one part checksum at a time rather than for all of them.++ Returns ``(checksums_dict, error_response_or_None)``.+ """+ checksums, err = _resolve_object_checksums(body, headers)+ if err:+ return {}, err++ algorithm = upload.get("checksum_algorithm")+ if algorithm and algorithm not in checksums:+ computed = _compute_s3_checksum(algorithm, body)+ if computed is not None:+ checksums[algorithm] = computed+ return checksums, None+++def _composite_checksum(algorithm: str, part_checksums: list) -> str | None:+ """Build the multipart composite: the digest of the parts' digests.++ AWS hashes the raw part digests end to end, base64s the result and suffixes+ the part count -- so a composite reads as ``<digest>-<parts>`` and cannot be+ confused with the whole-object checksum of a single PUT. Returns None when+ a part is missing its checksum, since a composite over some of the parts+ would be a value no caller could reproduce.+ """+ if not algorithm or not part_checksums:+ return None+ digests = b""+ for value in part_checksums:+ if not value:+ return None+ try:+ digests += base64.b64decode(value)+ except ValueError: # binascii.Error subclasses it+ return None+ combined = _compute_s3_checksum(algorithm, digests)+ if combined is None:+ return None+ return f"{combined}-{len(part_checksums)}"++def _object_response_headers(obj: dict, bucket_name: str = "", key: str = "",include_checksums: bool = False) -> dict:h = {@@ -1065,9 +1137,10 @@ def _object_response_headers(obj: dict, bucket_name: str = "", key: str = "",for alg, val in stored.items():h[f"x-amz-checksum-{alg.lower()}"] = valif stored:- # Single PutObject = FULL_OBJECT; multipart-uploaded objects would- # be COMPOSITE — out of scope here.- h["x-amz-checksum-type"] = "FULL_OBJECT"+ # A single PutObject hashes the whole body; a completed multipart+ # object hashes its parts' digests, which AWS names COMPOSITE.+ h["x-amz-checksum-type"] = (obj.get("checksum_type")+ or "FULL_OBJECT")return h@@ -5023,6 +5096,10 @@ def _create_multipart_upload(bucket_name: str, key: str, headers: dict):if sse_err:return sse_err+ checksum_algorithm, csum_err = _resolve_multipart_checksum_algorithm(headers)+ if csum_err:+ return csum_err+upload_id = new_uuid()content_type = headers.get("content-type", "application/octet-stream")content_encoding = headers.get("content-encoding")@@ -5043,6 +5120,7 @@ def _create_multipart_upload(bucket_name: str, key: str, headers: dict):"content_encoding": content_encoding,"preserved_headers": preserved,"storage_class": storage_class,+ "checksum_algorithm": checksum_algorithm,"created": now_iso(),}@@ -5050,8 +5128,14 @@ def _create_multipart_upload(bucket_name: str, key: str, headers: dict):SubElement(root, "Bucket").text = bucket_nameSubElement(root, "Key").text = keySubElement(root, "UploadId").text = upload_id- # AWS echoes the upload's encryption on the initiate response.- return 200, {"Content-Type": "application/xml", **sse_headers}, _xml_body(root)+ # AWS echoes the upload's encryption on the initiate response, and the+ # checksum algorithm the parts are expected to carry.+ csum_headers = {}+ if checksum_algorithm:+ csum_headers["x-amz-checksum-algorithm"] = checksum_algorithm+ csum_headers["x-amz-checksum-type"] = "COMPOSITE"+ return (200, {"Content-Type": "application/xml", **sse_headers,+ **csum_headers}, _xml_body(root))def _upload_part(@@ -5104,14 +5188,24 @@ def _upload_part(if md5_err:return md5_err+ part_checksums, csum_err = _resolve_part_checksums(body, headers, upload)+ if csum_err:+ return csum_err+etag = f'"{md5_hash(body)}"'upload["parts"][pn] = {"body": body,"etag": etag,"size": len(body),"last_modified": now_iso(),+ "checksums": part_checksums,}- return 200, {"ETag": etag, **_stored_sse_headers(upload)}, b""+ # AWS returns the part's checksum so the caller can name it again on the+ # completion, which is where the composite is built from.+ csum_headers = {f"x-amz-checksum-{alg.lower()}": val+ for alg, val in part_checksums.items()}+ return (200, {"ETag": etag, **_stored_sse_headers(upload), **csum_headers},+ b"")def _upload_part_copy(bucket_name: str, dest_key: str, query_params: dict, headers: dict):@@ -5283,11 +5377,12 @@ def _complete_multipart_upload(400,f"/{bucket_name}/{key}",)- ordered_parts: list[tuple[int, str | None]] = []+ ordered_parts: list[tuple[int, str | None, dict]] = []for part_el in xml_root.iter():local = part_el.tag.split("}")[-1] if "}" in part_el.tag else part_el.tagif local == "Part":pn_text = etag_text = None+ part_checksums = {}for child in part_el:child_local = (child.tag.split("}")[-1] if "}" in child.tag else child.tag@@ -5296,15 +5391,20 @@ def _complete_multipart_upload(pn_text = child.textelif child_local == "ETag":etag_text = child.text+ elif child_local.startswith("Checksum"):+ part_checksums[child_local[len("Checksum"):].upper()] = (+ child.text)if pn_text is not None:- ordered_parts.append((int(pn_text), etag_text))+ ordered_parts.append((int(pn_text), etag_text, part_checksums))ordered_parts.sort(key=lambda x: x[0])md5_digests = b""combined = b""part_records = []- for pn, req_etag in ordered_parts:+ checksum_algorithm = upload.get("checksum_algorithm")+ part_digests = []+ for pn, req_etag, req_checksums in ordered_parts:if pn not in upload["parts"]:return _error("InvalidPart",@@ -5319,12 +5419,39 @@ def _complete_multipart_upload("The following part numbers are invalid: " + str(pn),400,)+ # A part checksum named here must be the one the part was stored+ # with: the composite is built from what ministack holds, so a caller+ # naming a different value would get a composite it cannot reproduce.+ stored_checksums = stored.get("checksums") or {}+ for alg, value in req_checksums.items():+ if value and stored_checksums.get(alg) != value:+ return _error(+ "InvalidPart",+ "One or more of the specified parts could not be found. "+ "The following part numbers are invalid: " + str(pn),+ 400,+ )+ if checksum_algorithm:+ part_digests.append(stored_checksums.get(checksum_algorithm))md5_digests += hashlib.md5(stored["body"]).digest()combined += stored["body"]# Retained so GetObjectAttributes can report ObjectParts (ListParts# functionality) for the completed multipart object.part_records.append({"PartNumber": pn, "Size": len(stored["body"])})+ composite = _composite_checksum(checksum_algorithm, part_digests)+ if checksum_algorithm:+ requested = (headers or {}).get(+ f"x-amz-checksum-{checksum_algorithm.lower()}")+ if requested and requested != composite:+ return _error(+ "BadDigest",+ f"The {checksum_algorithm} you specified did not match the "+ f"calculated checksum.",+ 400,+ f"/{bucket_name}/{key}",+ )+final_md5 = hashlib.md5(md5_digests).hexdigest()final_etag = f'"{final_md5}-{len(ordered_parts)}"'@@ -5339,6 +5466,8 @@ def _complete_multipart_upload("preserved_headers": upload.get("preserved_headers", {}),"storage_class": upload.get("storage_class") or "STANDARD","parts": part_records,+ "checksums": {checksum_algorithm: composite} if composite else {},+ "checksum_type": "COMPOSITE" if composite else None,}prior_obj = bucket["objects"].get(key)bucket["objects"][key] = obj@@ -5378,6 +5507,10 @@ def _complete_multipart_upload(SubElement(root, "Bucket").text = bucket_nameSubElement(root, "Key").text = keySubElement(root, "ETag").text = final_etag+ if composite:+ SubElement(+ root, f"Checksum{checksum_algorithm}").text = composite+ SubElement(root, "ChecksumType").text = "COMPOSITE"response = (200, resp_headers, _xml_body(root))# Retain the response so an idempotent retry (same upload id) replays it# rather than 404ing; the versioning block above is NOT re-run on replay,@@ -5529,6 +5662,8 @@ def _list_parts(bucket_name: str, key: str, query_params: dict):SubElement(p, "LastModified").text = part.get("last_modified", now_iso())SubElement(p, "ETag").text = part["etag"]SubElement(p, "Size").text = str(part["size"])+ for alg, value in (part.get("checksums") or {}).items():+ SubElement(p, f"Checksum{alg}").text = valueif is_truncated and sorted_parts:SubElement(root, "NextPartNumberMarker").text = str(sorted_parts[max_parts - 1])diff --git a/tests/test_s3.py b/tests/test_s3.pyindex 09821128..6102353c 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -4455,6 +4455,59 @@ def test_s3_put_object_with_explicit_sha256_value_validated(s3):s3.delete_bucket(Bucket=bucket)+def test_s3_multipart_checksum_sha256_composite(s3):+ """A checksummed multipart upload carries its parts' checksums through to+ a composite on the completed object: the part echoes its own, the+ completion answers the digest-of-digests suffixed with the part count, and+ a read asks for it with ChecksumMode."""+ import base64+ import hashlib++ from botocore.exceptions import ClientError++ bucket = "checksum-multipart-bucket"+ s3.create_bucket(Bucket=bucket)+ body = b"A" * 1024+ part_sum = base64.b64encode(hashlib.sha256(body).digest()).decode()+ composite = base64.b64encode(+ hashlib.sha256(hashlib.sha256(body).digest()).digest()).decode() + "-1"++ mpu = s3.create_multipart_upload(Bucket=bucket, Key="k",+ ChecksumAlgorithm="SHA256")+ assert mpu["ChecksumAlgorithm"] == "SHA256"+ uid = mpu["UploadId"]+ part = s3.upload_part(Bucket=bucket, Key="k", UploadId=uid, PartNumber=1,+ Body=body, ChecksumAlgorithm="SHA256",+ ChecksumSHA256=part_sum)+ assert part["ChecksumSHA256"] == part_sum+ assert s3.list_parts(Bucket=bucket, Key="k",+ UploadId=uid)["Parts"][0]["ChecksumSHA256"] == part_sum++ parts = {"Parts": [{"PartNumber": 1, "ETag": part["ETag"],+ "ChecksumSHA256": part_sum}]}++ # A composite the caller names must be the one the parts add up to.+ with pytest.raises(ClientError) as exc:+ s3.complete_multipart_upload(Bucket=bucket, Key="k", UploadId=uid,+ ChecksumSHA256="bad",+ MultipartUpload=parts)+ assert exc.value.response["Error"]["Code"] == "BadDigest"++ done = s3.complete_multipart_upload(Bucket=bucket, Key="k", UploadId=uid,+ ChecksumSHA256=composite,+ MultipartUpload=parts)+ assert done["ChecksumSHA256"] == composite++ # Silent unless the read opts in, as with any other stored checksum.+ assert "ChecksumSHA256" not in s3.head_object(Bucket=bucket, Key="k")+ head = s3.head_object(Bucket=bucket, Key="k", ChecksumMode="ENABLED")+ assert head["ChecksumSHA256"] == composite+ assert head["ChecksumType"] == "COMPOSITE"++ s3.delete_object(Bucket=bucket, Key="k")+ s3.delete_bucket(Bucket=bucket)++def test_s3_versioned_get_returns_stored_checksum(s3):"""A versioned GetObject(?versionId=X) with ChecksumMode=ENABLED mustreturn the per-version checksum that was stored at put time. Issue #831