Skip to content

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

feat(s3): copy bucket (#1555)

Nahuel Nuceracfac4280c203
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8e170109..e1e43647 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+- **S3 — replication delivers, with `x-amz-replication-status`** — a bucket's replication configuration was stored and echoed but never acted on: no object ever reached the destination and `HeadObject` showed no replication metadata. A write (put, POST upload, copy, or multipart complete) matching an Enabled rule's prefix now lands a copy in the destination bucket with its own version, the source's metadata, storage class override, and tags; the source object answers `ReplicationStatus: COMPLETED` (or `FAILED` when the destination is gone or no longer versioned) and the replica answers `REPLICA`, on current and version-addressed reads alike. The copy is synchronous so tests see a deterministic status. Delete-marker replication and replica re-replication are not modeled. Reported by @cringdahl.
+
### Fixed
- **Step Functions — execution status changes are published to EventBridge** — real Step Functions automatically emits `source: aws.states` / `detail-type: "Step Functions Execution Status Change"` to the default bus whenever a standard execution changes status; MiniStack ran the execution and published nothing, so a rule matching those events never fired and applications waiting on them hung with no error anywhere. Every `StartExecution` now emits `RUNNING` and its completion `SUCCEEDED`, `FAILED` (with `error`/`cause` and `REDRIVABLE`) or `ABORTED` on `StopExecution`, carrying the documented detail fields with epoch-millisecond dates; payloads over 248 KiB are excluded and flagged via `inputDetails`/`outputDetails`, and `StartSyncExecution` (the express-flavored path) emits nothing, as on AWS. Reported by @moonyseven.
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index a3c8a832..e9eead85 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -1409,6 +1409,8 @@ def _object_response_headers(obj: dict, bucket_name: str = "", key: str = "", in
h.update(obj.get("metadata", {}))
if obj.get("version_id"):
h["x-amz-version-id"] = obj["version_id"]
+ if obj.get("replication_status"):
+ h["x-amz-replication-status"] = obj["replication_status"]
sc = obj.get("storage_class") or "STANDARD"
if sc != "STANDARD":
# AWS omits the header for STANDARD; SDKs default to STANDARD when absent.
@@ -3406,6 +3408,7 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):
resp_headers = {"ETag": obj["etag"], "Content-Length": "0"}
resp_headers.update(sse_headers)
+ _maybe_replicate(bucket_name, key, obj, body)
version_id = _record_object_version(bucket_name, key, prior_obj, obj, body)
if version_id:
resp_headers["x-amz-version-id"] = version_id
@@ -3417,6 +3420,9 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):
if pending_tags is not None:
_object_tags[(bucket_name, key, obj.get("version_id"))] = pending_tags
+ if obj.get("_replica"):
+ dest_name, replica_version = obj["_replica"]
+ _object_tags[(dest_name, key, replica_version)] = dict(pending_tags)
if canned_acl:
_object_acl[(bucket_name, key, obj.get("version_id"))] = _canned_acl_policy_xml(
canned_acl, _canonical_owner_id()
@@ -3629,6 +3635,7 @@ def _post_object(bucket_name: str, body: bytes, headers: dict):
_fire_s3_event_async(bucket_name, key, "s3:ObjectCreated:Post", size=obj["size"], etag=etag)
+ _maybe_replicate(bucket_name, key, obj, file_value)
version_id = _record_object_version(bucket_name, key, prior_obj, obj, file_value)
# Persist only after the versioning block: the .meta.json sidecar must
@@ -3638,6 +3645,8 @@ def _post_object(bucket_name: str, body: bytes, headers: dict):
if pending_tags is not None:
_object_tags[(bucket_name, key, version_id)] = pending_tags
+ if obj.get("_replica"):
+ _object_tags[(obj["_replica"][0], key, obj["_replica"][1])] = dict(pending_tags)
if canned_acl:
_object_acl[(bucket_name, key, version_id)] = _canned_acl_policy_xml(canned_acl, _canonical_owner_id())
@@ -4065,6 +4074,7 @@ 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 {},
+ "replication_status": v.get("replication_status"),
# 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
@@ -4089,6 +4099,7 @@ def _version_entry_from_record(obj: dict, version_id: str, data) -> dict:
"storage_class": obj.get("storage_class") or "STANDARD",
"checksums": obj.get("checksums") or {},
"parts": obj.get("parts"),
+ "replication_status": obj.get("replication_status"),
}
@@ -4106,6 +4117,63 @@ def _preserve_null_version(bucket_name: str, key: str, versions: list, prior_obj
versions.append(_version_entry_from_record(prior_obj, "null", _read_body(bucket_name, key, prior_obj)))
+def _replication_rule_for(bucket_name: str, key: str) -> dict | None:
+ """The first Enabled rule whose Prefix covers `key`, or None.
+
+ Replication runs only while the source bucket's versioning is Enabled,
+ as on AWS (a Suspended bucket stops replicating; the stored config stays).
+ """
+ config = _bucket_replication.get(bucket_name)
+ if not config or _bucket_versioning.get(bucket_name) != "Enabled":
+ return None
+ for rule in config.get("Rules", []):
+ if rule.get("Status") != "Enabled":
+ continue
+ if key.startswith(rule.get("Prefix") or ""):
+ return rule
+ return None
+
+
+def _maybe_replicate(bucket_name: str, key: str, obj: dict, data) -> None:
+ """Write the replica a matching replication rule asks for, and stamp the
+ source's x-amz-replication-status.
+
+ AWS marks the source PENDING and flips it to COMPLETED (or FAILED) once
+ the copy lands; the destination copy reads REPLICA. The emulator's copy is
+ synchronous, so the source is stamped with its final status immediately
+ and tests see a deterministic answer. Runs BEFORE the source's version
+ entry is recorded, so a version-addressed read carries the status too.
+ A destination that no longer exists or is no longer versioned stamps the
+ source FAILED, which is how AWS reports a replica it could not write.
+ """
+ rule = _replication_rule_for(bucket_name, key)
+ if rule is None:
+ return
+ dest_ref = (rule.get("Destination") or {}).get("Bucket") or ""
+ dest_name = dest_ref.split(":::")[-1] if ":::" in dest_ref else dest_ref
+ dest_bucket = _buckets.get(dest_name)
+ if (dest_bucket is None or dest_name == bucket_name
+ or _bucket_versioning.get(dest_name) != "Enabled"):
+ obj["replication_status"] = "FAILED"
+ return
+
+ replica = copy.deepcopy(obj)
+ replica["replication_status"] = "REPLICA"
+ replica.pop("version_id", None)
+ if rule.get("Destination", {}).get("StorageClass"):
+ replica["storage_class"] = rule["Destination"]["StorageClass"]
+ prior = dest_bucket["objects"].get(key)
+ dest_bucket["objects"][key] = replica
+ replica_version = _record_object_version(dest_name, key, prior, replica, data)
+ # The write paths store the source's tags after the version is cut; the
+ # pointer lets them mirror the tags onto the replica, as AWS replicates
+ # them. Internal bookkeeping only — never serialized onto a response.
+ obj["_replica"] = (dest_name, replica_version)
+ if S3_PERSIST:
+ _persist_object(dest_name, key, replica)
+ obj["replication_status"] = "COMPLETED"
+
+
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`.
@@ -4616,6 +4684,7 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):
resp_headers["x-amz-copy-source-version-id"] = copy_src_vid
if dest_sc != "STANDARD":
resp_headers["x-amz-storage-class"] = dest_sc
+ _maybe_replicate(bucket_name, dest_key, dest_obj, src_body)
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
@@ -4628,6 +4697,8 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):
dest_version_id = dest_obj.get("version_id")
if pending_dest_tags is not None:
_object_tags[(bucket_name, dest_key, dest_version_id)] = pending_dest_tags
+ if dest_obj.get("_replica"):
+ _object_tags[(dest_obj["_replica"][0], dest_key, dest_obj["_replica"][1])] = dict(pending_dest_tags)
else:
_object_tags.pop((bucket_name, dest_key, dest_version_id), None)
@@ -5993,6 +6064,7 @@ def _complete_multipart_upload(
resp_headers = {"Content-Type": "application/xml"}
resp_headers.update(_stored_sse_headers(obj))
+ _maybe_replicate(bucket_name, key, obj, combined)
version_id = _record_object_version(bucket_name, key, prior_obj, obj, combined)
if version_id:
resp_headers["x-amz-version-id"] = version_id
diff --git a/tests/test_s3.py b/tests/test_s3.py
index 9aa35d71..3e47f466 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -5979,3 +5979,110 @@ def test_s3_put_object_rejects_a_mismatched_checksum(s3):
s3.put_object(Bucket=bkt, Key="good.txt", Body=b"hello", ChecksumSHA256=good)
head = s3.head_object(Bucket=bkt, Key="good.txt", ChecksumMode="ENABLED")
assert head["ChecksumSHA256"] == good
+
+
+# ---------------------------------------------------------------------------
+# Replication data plane (x-amz-replication-status)
+# ---------------------------------------------------------------------------
+
+def _replicated_pair(s3, slug):
+ """Source + destination buckets, both versioned, one Enabled rule."""
+ src, dst = f"qa-repl-src-{slug}", f"qa-repl-dst-{slug}"
+ for b in (src, dst):
+ s3.create_bucket(Bucket=b)
+ s3.put_bucket_versioning(Bucket=b, VersioningConfiguration={"Status": "Enabled"})
+ 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}"},
+ }],
+ },
+ )
+ return src, dst
+
+
+def _purge_versioned(s3, bucket):
+ lv = s3.list_object_versions(Bucket=bucket)
+ for v in lv.get("Versions", []) + lv.get("DeleteMarkers", []):
+ s3.delete_object(Bucket=bucket, Key=v["Key"], VersionId=v["VersionId"])
+ s3.delete_bucket(Bucket=bucket)
+
+
+def test_s3_replication_copies_object_and_stamps_status(s3):
+ """A put under an Enabled rule lands in the destination; the source
+ reports COMPLETED and the replica REPLICA, per S3's replication-status
+ contract."""
+ src, dst = _replicated_pair(s3, "basic")
+ try:
+ s3.put_object(Bucket=src, Key="a/k", Body=b"payload",
+ Tagging="team=core")
+ head = s3.head_object(Bucket=src, Key="a/k")
+ assert head["ReplicationStatus"] == "COMPLETED"
+ replica = s3.get_object(Bucket=dst, Key="a/k")
+ assert replica["ReplicationStatus"] == "REPLICA"
+ assert replica["Body"].read() == b"payload"
+ tags = s3.get_object_tagging(Bucket=dst, Key="a/k")["TagSet"]
+ assert tags == [{"Key": "team", "Value": "core"}]
+ finally:
+ _purge_versioned(s3, src)
+ _purge_versioned(s3, dst)
+
+
+def test_s3_replication_honors_prefix_and_failure(s3):
+ """A key outside the rule's Prefix carries no status; a destination that
+ stops being usable stamps the source FAILED."""
+ src, dst = f"qa-repl-src-pref", f"qa-repl-dst-pref"
+ for b in (src, dst):
+ s3.create_bucket(Bucket=b)
+ s3.put_bucket_versioning(Bucket=b, VersioningConfiguration={"Status": "Enabled"})
+ s3.put_bucket_replication(
+ Bucket=src,
+ ReplicationConfiguration={
+ "Role": "arn:aws:iam::000000000000:role/repl",
+ "Rules": [{
+ "ID": "r1", "Status": "Enabled", "Prefix": "logs/",
+ "Destination": {"Bucket": f"arn:aws:s3:::{dst}"},
+ }],
+ },
+ )
+ try:
+ s3.put_object(Bucket=src, Key="other/k", Body=b"x")
+ head = s3.head_object(Bucket=src, Key="other/k")
+ assert "ReplicationStatus" not in head
+ # Destination becomes unusable: versioning suspended.
+ s3.put_bucket_versioning(Bucket=dst, VersioningConfiguration={"Status": "Suspended"})
+ s3.put_object(Bucket=src, Key="logs/k", Body=b"x")
+ assert s3.head_object(Bucket=src, Key="logs/k")["ReplicationStatus"] == "FAILED"
+ from botocore.exceptions import ClientError
+ try:
+ s3.head_object(Bucket=dst, Key="logs/k")
+ raise AssertionError("replica must not exist")
+ except ClientError:
+ pass
+ finally:
+ _purge_versioned(s3, src)
+ lv = s3.list_object_versions(Bucket=dst)
+ for v in lv.get("Versions", []) + lv.get("DeleteMarkers", []):
+ s3.delete_object(Bucket=dst, Key=v["Key"], VersionId=v["VersionId"])
+ s3.delete_bucket(Bucket=dst)
+
+
+def test_s3_replication_covers_copy_and_versioned_reads(s3):
+ """CopyObject into the source bucket replicates too, and the status rides
+ on a version-addressed read."""
+ src, dst = _replicated_pair(s3, "copy")
+ try:
+ s3.put_object(Bucket=src, Key="orig", Body=b"v")
+ s3.copy_object(Bucket=src, Key="copied",
+ CopySource={"Bucket": src, "Key": "orig"})
+ assert s3.head_object(Bucket=src, Key="copied")["ReplicationStatus"] == "COMPLETED"
+ assert s3.get_object(Bucket=dst, Key="copied")["Body"].read() == b"v"
+ vid = s3.head_object(Bucket=src, Key="copied")["VersionId"]
+ versioned = s3.head_object(Bucket=src, Key="copied", VersionId=vid)
+ assert versioned["ReplicationStatus"] == "COMPLETED"
+ finally:
+ _purge_versioned(s3, src)
+ _purge_versioned(s3, dst)