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): eTags with versioned to return correct error code (#1476)
Nahuel Nucera37a8ef938c14
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 60714525..40d589dd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,6 +18,10 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **SSM — Run Command** — `SendCommand`, `GetCommandInvocation`, `ListCommands` and `DescribeInstanceInformation` returned `InvalidAction`, so the standard instance health probe could not run. Invocations are asynchronous as on AWS: `SendCommand` answers `Pending` and the caller polls to a terminal state. `AWS-RunShellScript` runs in the instance's container, so `Status` is `Success` or `Failed` on the real exit code, with the script's output. An instance with no agent answering is refused with `InvalidInstanceId`. Contributed by @bandle.- **EC2 — `RebootInstances` rejects unknown instance ids** — it returned `true` for any id. It now answers `InvalidInstanceID.NotFound`, matching AWS.+### Fixed+- **RDS — `DescribeDBInstances` honors SDK `Filters`** — AWS Query clients serialize filters as `Filters.Filter.N` with `Values.Value.N`, but MiniStack only parsed its internal `Filters.member.N` form, so filters such as `db-cluster-id` were ignored and unrelated instances were returned. Both wire forms are now parsed with the existing AND-across-filters and OR-across-values semantics.+- **S3 — a conditional delete of a key with no current object answers 404** — `DeleteObject` carrying `If-Match` returned 204 for a key that was absent, hidden by a delete marker, or held only delete markers, so a compare-and-swap delete reported success for work it never did. The condition is now evaluated against the current version and nothing else: no current object answers `NoSuchKey`, a differing ETag answers `PreconditionFailed`, and a matching ETag or `If-Match: *` deletes. `DeleteObjects` reports the same absent key under `<Error>` as `NoSuchKey` rather than `PreconditionFailed`, and honours `*` in the `ETag` element instead of comparing it literally.+## [1.4.21] — 2026-08-20### Addeddiff --git a/ministack/services/ec2.py b/ministack/services/ec2.pyindex b7f0c269..4dedcb9a 100644--- a/ministack/services/ec2.py+++ b/ministack/services/ec2.py@@ -1313,8 +1313,25 @@ def _image_bdm_xml(view):return f"<blockDeviceMapping>{items}</blockDeviceMapping>"+def _image_owner_matches(view, owners):+ """Owner.N: "a combination of AWS account IDs, self, amazon, aws-backup-vault, and+ aws-marketplace". Every image here belongs to the calling account, so an alias or another+ account's id matches nothing."""+ account = get_account_id()+ return view["OwnerId"] == account and any(o in ("self", account) for o in owners)+++def _image_executable_by_matches(view, users):+ """ExecutableBy.N: "Specify an AWS account ID, self (the sender of the request), or all+ (public AMIs)." Nothing here is shared by explicit launch permission, so only `all`+ selects anything and it selects the public images."""+ return "all" in users and view["IsPublic"] == "true"++def _describe_images(p):filter_ids = _parse_member_list(p, "ImageId")+ owners = _parse_member_list(p, "Owner")+ executable_by = _parse_member_list(p, "ExecutableBy")filters = _parse_filters(p)# Registered images first: those are the ones that actually boot. The stubs# stay so a workload naming one keeps launching a metadata-only instance.@@ -1326,6 +1343,10 @@ def _describe_images(p):for view in views:if filter_ids and view["ImageId"] not in filter_ids:continue+ if owners and not _image_owner_matches(view, owners):+ continue+ if executable_by and not _image_executable_by_matches(view, executable_by):+ continueif filters and not _image_matches_filters(view, filters):continue# RootDeviceName + BlockDeviceMappings are required by Terraform's AWS@@ -1974,7 +1995,6 @@ def _register_image(p):"'-', '_', '.', '/', '(', and ')'", 400)location = _p(p, "ImageLocation")mappings = _parse_register_block_device_mappings(p)- snapshot_backed = any(m.get("Ebs", {}).get("SnapshotId") for m in mappings)# Only Name is required on AWS: ImageLocation and BlockDeviceMapping.N are both optional, and# registration never checks that the result can boot. Refusing here would make MiniStack# stricter than AWS, so a registration with neither is accepted and fails at RunInstances.@@ -2076,6 +2096,21 @@ def _is_image_unavailable(exc):"no such image", "repository does not exist")))+def _image_has_entrypoint(client, ref):+ """Whether the image declares its own ENTRYPOINT, pulling it first if it is not local.++ docker-py's ``containers.run`` would pull implicitly, but the decision needs the image+ config before the container is created.+ """+ try:+ image = client.images.get(ref)+ except Exception:+ image = client.images.pull(ref)+ if isinstance(image, list): # a tagless pull returns every tag+ image = image[0]+ return bool((image.attrs.get("Config") or {}).get("Entrypoint"))++def _vm_launch(inst, image_ref):"""Boot one instance record as a container. Raises on create/start failure;the caller backs the records out and surfaces the error."""@@ -2088,6 +2123,7 @@ def _vm_launch(inst, image_ref):client.containers.get(name).remove(force=True)except Exception:pass # no stale container by that name, which is the normal case+ ref = apply_image_prefix(image_ref)kwargs = {"name": name,"detach": True,@@ -2097,15 +2133,18 @@ def _vm_launch(inst, image_ref):"account_id": get_account_id(),"region": get_region(),},- # A real instance does not exit the moment it boots, so keep the- # container alive. An image with its own ENTRYPOINT receives this as- # argv and is free to ignore it; init reaps the keepalive.+ # init reaps whatever PID 1 leaves behind, as an instance's own init would."init": True,- "command": ["sleep", "infinity"],}+ if not _image_has_entrypoint(client, ref):+ # A base image's command is usually a shell, which exits at once and would take the+ # instance down with it, so keep the box alive. An image that declares an ENTRYPOINT+ # is left exactly as it was built: overriding its command would stop its service+ # from ever starting.+ kwargs["command"] = ["sleep", "infinity"]if network:kwargs["network"] = network- container = client.containers.run(apply_image_prefix(image_ref), **kwargs)+ container = client.containers.run(ref, **kwargs)global _docker_in_use_docker_in_use = Trueinst["_container_id"] = container.iddiff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex 304920e7..8ca78e47 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -3805,16 +3805,26 @@ def _delete_object(bucket_name: str, key: str, headers: dict | None = None,if bucket is None:return _no_such_bucket(bucket_name)- # Conditional delete: If-Match against the current object's ETag. An- # object whose ETag differs fails the precondition with 412 and stays —- # S3's compare-and-swap delete. A key that is not there at all is not a- # failed precondition: deleting one is a success either way, and S3- # answers the conditional delete of an absent key 204 like any other.+ # Conditional delete. Measured against S3 in eu-west-1: the condition is+ # evaluated against the current object and nothing else, matching the+ # guide's "Conditional delete evaluations only apply to the current+ # version of the object."+ #+ # no current object (absent, or a delete marker on top) -> 404 NoSuchKey+ # current object, ETag differs -> 412+ # current object, matching ETag or If-Match: * -> 204+ #+ # S3 does not look under a delete marker, so a key whose history still+ # holds a real version is as gone as one that was never written. An+ # absent key is not an already-completed delete either: the request is+ # conditional, and there is nothing for the condition to hold against.if_match = (headers.get("if-match") or "").strip()if if_match:_cur = bucket["objects"].get(key)- if _cur is not None and if_match != "*" and (- if_match.strip('"') != _cur["etag"].strip('"')):+ if _cur is None:+ return _error("NoSuchKey", "The specified key does not exist.",+ 404, f"/{bucket_name}/{key}")+ if if_match != "*" and if_match.strip('"') != _cur["etag"].strip('"'):return _error("PreconditionFailed","At least one of the preconditions you specified did not hold.",@@ -5022,14 +5032,28 @@ def _delete_objects(bucket_name: str, body: bytes, headers: dict = None):})continue- # Conditional delete: an ObjectIdentifier with an ETag deletes only if it- # matches the current object. On mismatch the key is reported under Error- # (PreconditionFailed), not Deleted, so the object survives.+ # Conditional delete: an ObjectIdentifier carrying an ETag deletes only if it+ # matches the current object, and `*` asks only that a current object exist.+ # The condition is evaluated against the current version alone, so a key+ # hidden by a delete marker does not exist for this purpose. A failed+ # condition is reported under Error, not Deleted, and the object survives:+ # "If the precondition fails then the response for that object will be+ # captured in the <Error> element", and "If the object doesn't exist when+ # evaluating either of the preconditions, S3 rejects the request and returns+ # a Not Found error response."etag_el = _find_xml_tag(obj_el, "ETag")cond_etag = etag_el.text if (etag_el is not None and etag_el.text) else ""if cond_etag:_cur = bucket["objects"].get(k)- if _cur is None or cond_etag.strip('"') != _cur["etag"].strip('"'):+ if _cur is None:+ errors.append({+ "key": k,+ "version_id": version_id,+ "code": "NoSuchKey",+ "msg": "The specified key does not exist.",+ })+ continue+ if cond_etag != "*" and cond_etag.strip('"') != _cur["etag"].strip('"'):errors.append({"key": k,"version_id": version_id,diff --git a/tests/test_ec2.py b/tests/test_ec2.pyindex 08bc9b96..83548fc1 100644--- a/tests/test_ec2.py+++ b/tests/test_ec2.py@@ -3673,9 +3673,19 @@ class _FakeContainer:self._registry.pop(self.name, None)-def _fake_docker(run_error=None, shell=True):+def _fake_docker(run_error=None, shell=True, entrypoint=None):registry, runs = {}, []+ class _FakeImage:+ attrs = {"Config": {"Entrypoint": entrypoint}}++ class _Images:+ def get(self, ref):+ return _FakeImage()++ def pull(self, ref):+ return _FakeImage()+class _Containers:def run(self, image, **kwargs):if run_error is not None:@@ -3704,6 +3714,7 @@ def _fake_docker(run_error=None, shell=True):class _Docker:def __init__(self):self.containers = _Containers()+ self.images = _Images()def ping(self):return True@@ -4130,3 +4141,55 @@ def test_ec2_deregister_does_not_orphan_a_running_box(vm):fake._registry[inst["_container_id"]].status = "exited"ec2mod._vm_reconcile_running([inst])assert inst["State"]["Name"] == "terminated"+++def test_ec2_base_image_gets_a_keepalive(vm):+ """A base image's command is a shell that exits at once, so the box needs keeping alive."""+ fake, created = vm+ ami = _register("example/base:1")+ iids, _ = _launch(ami)+ created.extend(iids)+ assert fake._runs[0]["command"] == ["sleep", "infinity"]+++def test_ec2_image_with_an_entrypoint_is_left_alone(monkeypatch):+ """Overriding the command of an image built to run a service would stop it ever starting."""+ fake = _fake_docker(entrypoint=["/docker-entrypoint.sh"])+ monkeypatch.setattr(ec2mod, "_get_docker", lambda: fake)+ monkeypatch.setattr(ec2mod, "_get_ministack_network", lambda _c: "testnet")+ ami = _register("example/service:1")+ iids, _ = _launch(ami)+ try:+ assert "command" not in fake._runs[0]+ assert fake._runs[0]["init"] is True+ finally:+ for iid in iids:+ ec2mod._instances.pop(iid, None)+ ec2mod._images.pop(ami, None)+++def test_ec2_describe_images_scopes_by_owner(ec2):+ """Owner.N: account ids and `self` select ours; an alias or another account selects nothing."""+ ami = ec2.register_image(Name=f"owned-{_uuid_mod.uuid4().hex[:8]}",+ ImageLocation="alpine:3")["ImageId"]+ try:+ assert ami in [i["ImageId"] for i in ec2.describe_images(Owners=["self"])["Images"]]+ assert ami in [i["ImageId"] for i in+ ec2.describe_images(Owners=["000000000000"])["Images"]]+ for scope in (["amazon"], ["aws-marketplace"], ["123456789012"]):+ assert ec2.describe_images(Owners=scope)["Images"] == [], scope+ finally:+ ec2.deregister_image(ImageId=ami)+++def test_ec2_describe_images_scopes_by_executable_by(ec2):+ """ExecutableBy.N: `all` is the public images; nothing is shared with anyone here."""+ ami = ec2.register_image(Name=f"exec-{_uuid_mod.uuid4().hex[:8]}",+ ImageLocation="alpine:3")["ImageId"]+ try:+ public = [i["ImageId"] for i in ec2.describe_images(ExecutableUsers=["all"])["Images"]]+ assert "ami-0abcdef1234567890" in public+ assert ami not in public+ assert ec2.describe_images(ExecutableUsers=["self"])["Images"] == []+ finally:+ ec2.deregister_image(ImageId=ami)diff --git a/tests/test_s3.py b/tests/test_s3.pyindex b9cffcc6..b7792d83 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -5053,28 +5053,95 @@ def test_s3_bucket_owner_id_is_consistent_and_canonical(s3):s3.delete_bucket(Bucket=bkt)-def test_s3_conditional_delete_of_absent_key_succeeds(s3):- """A conditional delete of a key that is not there is a success, not a- failed precondition: S3 counts deleting an absent key as done whatever- condition the request carries. If-Match: * means "whatever is there",- so it holds against an object of any ETag."""- bucket = "intg-s3-conditional-delete-absent"+def test_s3_conditional_delete_needs_a_current_object(s3):+ """A conditional delete is evaluated against the current version and nothing+ else: "Conditional delete evaluations only apply to the current version of the+ object." With no current object there is nothing for the condition to hold+ against, so S3 answers 404 NoSuchKey whatever the If-Match carries. Measured+ against S3 in eu-west-1; the guide's 412 for the delete-marker case is a slip+ the measurement overrides."""+ bucket = "intg-s3-cond-delete-current"s3.create_bucket(Bucket=bucket)+ # Never written.for condition in ("*", "badetag"):- resp = s3.delete_object(Bucket=bucket, Key="gone", IfMatch=condition)- assert resp["ResponseMetadata"]["HTTPStatusCode"] == 204+ with pytest.raises(ClientError) as exc:+ s3.delete_object(Bucket=bucket, Key="gone", IfMatch=condition)+ assert exc.value.response["Error"]["Code"] == "NoSuchKey", condition+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404- s3.put_object(Bucket=bucket, Key="here", Body=b"x")- resp = s3.delete_object(Bucket=bucket, Key="here", IfMatch="*")- assert resp["ResponseMetadata"]["HTTPStatusCode"] == 204+ # Present: a wrong ETag fails and the object survives, the right one and `*` win.+ etag = s3.put_object(Bucket=bucket, Key="here", Body=b"x")["ETag"]with pytest.raises(ClientError) as exc:- s3.head_object(Bucket=bucket, Key="here")- assert exc.value.response["Error"]["Code"] == "404"+ s3.delete_object(Bucket=bucket, Key="here", IfMatch="badetag")+ assert exc.value.response["Error"]["Code"] == "PreconditionFailed"+ assert s3.get_object(Bucket=bucket, Key="here")["Body"].read() == b"x"+ assert s3.delete_object(Bucket=bucket, Key="here",+ IfMatch="*")["ResponseMetadata"]["HTTPStatusCode"] == 204++ s3.put_object(Bucket=bucket, Key="exact", Body=b"y")+ exact = s3.head_object(Bucket=bucket, Key="exact")["ETag"]+ assert s3.delete_object(Bucket=bucket, Key="exact",+ IfMatch=exact)["ResponseMetadata"]["HTTPStatusCode"] == 204+ assert etag # the put's ETag round-trippeds3.delete_bucket(Bucket=bucket)+def test_s3_conditional_delete_does_not_look_under_a_delete_marker(s3):+ """S3 does not peek beneath a delete marker: a key whose history still holds a+ real version is as absent as one that was never written."""+ bucket = "intg-s3-cond-delete-marker"+ s3.create_bucket(Bucket=bucket)+ s3.put_bucket_versioning(Bucket=bucket,+ VersioningConfiguration={"Status": "Enabled"})+ try:+ put = s3.put_object(Bucket=bucket, Key="obj", Body=b"v1")+ live_etag = put["ETag"]+ s3.delete_object(Bucket=bucket, Key="obj") # lays a delete marker on top++ for condition in ("*", "badetag", live_etag):+ with pytest.raises(ClientError) as exc:+ s3.delete_object(Bucket=bucket, Key="obj", IfMatch=condition)+ assert exc.value.response["Error"]["Code"] == "NoSuchKey", condition+ # The real version is still there underneath, untouched.+ versions = s3.list_object_versions(Bucket=bucket, Prefix="obj")+ assert len(versions.get("Versions", [])) == 1++ # Markers only, which is what a delete of an absent key leaves behind.+ s3.delete_object(Bucket=bucket, Key="never")+ for condition in ("*", "badetag"):+ with pytest.raises(ClientError) as exc:+ s3.delete_object(Bucket=bucket, Key="never", IfMatch=condition)+ assert exc.value.response["Error"]["Code"] == "NoSuchKey", condition+ finally:+ for v in (s3.list_object_versions(Bucket=bucket).get("Versions", [])+ + s3.list_object_versions(Bucket=bucket).get("DeleteMarkers", [])):+ s3.delete_object(Bucket=bucket, Key=v["Key"], VersionId=v["VersionId"])+ s3.delete_bucket(Bucket=bucket)+++def test_s3_batch_conditional_delete_reports_a_missing_key_not_found(s3):+ """DeleteObjects: "If the object doesn't exist when evaluating either of the+ preconditions, S3 rejects the request and returns a Not Found error response",+ and `*` in the ETag element asks only that a current object exist."""+ bucket = "intg-s3-cond-delete-batch"+ s3.create_bucket(Bucket=bucket)+ try:+ resp = s3.delete_objects(+ Bucket=bucket, Delete={"Objects": [{"Key": "gone", "ETag": "*"}]})+ assert resp["Errors"][0]["Code"] == "NoSuchKey"+ assert not resp.get("Deleted")++ s3.put_object(Bucket=bucket, Key="here", Body=b"x")+ resp = s3.delete_objects(+ Bucket=bucket, Delete={"Objects": [{"Key": "here", "ETag": "*"}]})+ assert [d["Key"] for d in resp.get("Deleted", [])] == ["here"]+ assert not resp.get("Errors")+ finally:+ s3.delete_bucket(Bucket=bucket)++def test_s3_copy_object_specific_version(s3):"""CopyObject with a source ?versionId copies that exact version, not thecurrent object. Regression for #1328."""