Skip to content

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

fix(ec2, s3): az in ec2, s3 ownerid (#1470)

Nahuel Nucerae4b226685d5d
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index 5410addd..d6570f1c 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -2439,11 +2439,21 @@ def _describe_availability_zones(p):
prefix = _az_id_prefix(region)
# 3 AZs with a=1, b=2, c=3 for ministack
zones = [(f"{region}{letter}", f"{prefix}-az{n}") for n, letter in enumerate("abc", start=1)]
+ # groupName / networkBorderGroup / optInStatus are optional members, so an
+ # SDK silently returns a zone with those keys absent rather than erroring —
+ # a consumer that reads them (Terraform's aws_availability_zones exposes
+ # group_names and opt_in_status) gets an empty answer instead of a failure.
+ # Standard Availability Zones sit in the region's single zone group and
+ # never require an opt-in.
+ group_name = f"{region}-zg-1"
items = "".join(f"""<item>
<zoneName>{name}</zoneName>
<zoneState>available</zoneState>
<regionName>{region}</regionName>
<zoneId>{zone_id}</zoneId>
+ <groupName>{group_name}</groupName>
+ <networkBorderGroup>{region}</networkBorderGroup>
+ <optInStatus>opt-in-not-required</optInStatus>
</item>""" for name, zone_id in zones)
return _xml(200, "DescribeAvailabilityZonesResponse",
f"<availabilityZoneInfo>{items}</availabilityZoneInfo>")
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index c2814d95..304920e7 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -1520,10 +1520,20 @@ def _dispatch(
# ---------------------------------------------------------------------------
+def _canonical_owner_id() -> str:
+ """The S3 canonical user ID for the current account.
+
+ Real S3 reports an opaque 64-character hex canonical ID (not the account
+ ID) and returns the same value from every Owner / CanonicalUser field
+ (ListBuckets, GetBucketAcl, GetObjectAcl, object listings). MiniStack
+ derives a stable one from the account so those fields agree (#1459)."""
+ return hashlib.sha256(get_account_id().encode()).hexdigest()
+
+
def _list_buckets():
root = Element("ListAllMyBucketsResult", xmlns=S3_NS)
owner = SubElement(root, "Owner")
- SubElement(owner, "ID").text = get_account_id()
+ SubElement(owner, "ID").text = _canonical_owner_id()
SubElement(owner, "DisplayName").text = "ministack"
buckets_el = SubElement(root, "Buckets")
for name, data in sorted(_buckets.items()):
@@ -1578,7 +1588,7 @@ def _create_bucket(name: str, body: bytes, headers: dict = None):
if tags:
_bucket_tags[name] = tags
if canned_acl:
- _bucket_acl[name] = _canned_acl_policy_xml(canned_acl, get_account_id())
+ _bucket_acl[name] = _canned_acl_policy_xml(canned_acl, _canonical_owner_id())
if headers.get("x-amz-bucket-object-lock-enabled", "").lower() == "true":
_bucket_object_lock[name] = {"enabled": True, "default_retention": None}
@@ -2038,13 +2048,14 @@ def _get_bucket_acl(name: str):
stored = _bucket_acl.get(name)
if stored:
return 200, {"Content-Type": "application/xml"}, stored
+ _oid = _canonical_owner_id().encode()
body = (
XML_DECL + b"\n"
b'<AccessControlPolicy xmlns="' + S3_NS.encode() + b'">'
- b"<Owner><ID>owner-id</ID><DisplayName>ministack</DisplayName></Owner>"
+ b"<Owner><ID>" + _oid + b"</ID><DisplayName>ministack</DisplayName></Owner>"
b"<AccessControlList><Grant>"
b'<Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser">'
- b"<ID>owner-id</ID><DisplayName>ministack</DisplayName></Grantee>"
+ b"<ID>" + _oid + b"</ID><DisplayName>ministack</DisplayName></Grantee>"
b"<Permission>FULL_CONTROL</Permission>"
b"</Grant></AccessControlList></AccessControlPolicy>"
)
@@ -2067,7 +2078,7 @@ def _put_bucket_acl(name: str, body: bytes, headers: dict | None = None):
if canned not in _CANNED_BUCKET_ACLS:
return _error("InvalidArgument",
f"Invalid x-amz-acl value: {canned}", 400)
- _bucket_acl[name] = _canned_acl_policy_xml(canned, get_account_id())
+ _bucket_acl[name] = _canned_acl_policy_xml(canned, _canonical_owner_id())
return 200, {}, b""
if not body:
@@ -2317,7 +2328,7 @@ def _list_object_versions(bucket_name: str, query_params: dict):
SubElement(root, "VersionIdMarker").text = version_id_marker
SubElement(root, "MaxKeys").text = str(max_keys)
- owner_id = get_account_id()
+ owner_id = _canonical_owner_id()
# Collect all keys: from objects AND from version history (deleted objects).
# When a version-id-marker is supplied we must resume *within* key-marker,
@@ -3008,7 +3019,7 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):
_object_tags[(bucket_name, key, obj.get("version_id"))] = pending_tags
if canned_acl:
_object_acl[(bucket_name, key, obj.get("version_id"))] = (
- _canned_acl_policy_xml(canned_acl, get_account_id()))
+ _canned_acl_policy_xml(canned_acl, _canonical_owner_id()))
return 200, resp_headers, b""
@@ -3213,7 +3224,7 @@ def _post_object(bucket_name: str, body: bytes, headers: dict):
_object_tags[(bucket_name, key, version_id)] = pending_tags
if canned_acl:
_object_acl[(bucket_name, key, version_id)] = (
- _canned_acl_policy_xml(canned_acl, get_account_id()))
+ _canned_acl_policy_xml(canned_acl, _canonical_owner_id()))
location = f"http://{bucket_name}.s3.amazonaws.com/{url_quote(key, safe='/')}"
base_resp = {"ETag": etag, "Location": location}
@@ -4575,7 +4586,7 @@ def _default_object_acl_xml() -> bytes:
a single Grant of FULL_CONTROL to the bucket owner (CanonicalUser).
The canonical-user ID is derived from the request's account so cross-
account callers don't all collide on the same fake ID."""
- owner_id = get_account_id()
+ owner_id = _canonical_owner_id()
return (
XML_DECL + b"\n"
b'<AccessControlPolicy xmlns="' + S3_NS.encode() + b'">'
@@ -4641,7 +4652,7 @@ def _put_object_acl(bucket_name: str, key: str, body: bytes, headers: dict,
return _error("InvalidArgument",
f"Invalid x-amz-acl value: {canned}", 400)
_object_acl[(bucket_name, key, version_id)] = (
- _canned_acl_policy_xml(canned, get_account_id()))
+ _canned_acl_policy_xml(canned, _canonical_owner_id()))
return 200, {}, b""
if not body:
@@ -4881,7 +4892,7 @@ def _list_objects_v1(bucket_name: str, query_params: dict):
SubElement(c, "Size").text = str(obj["size"])
SubElement(c, "StorageClass").text = obj.get("storage_class") or "STANDARD"
owner = SubElement(c, "Owner")
- SubElement(owner, "ID").text = get_account_id()
+ SubElement(owner, "ID").text = _canonical_owner_id()
SubElement(owner, "DisplayName").text = "ministack"
for cp in sorted(common_prefixes):
@@ -4957,7 +4968,7 @@ def _list_objects_v2(bucket_name: str, query_params: dict):
SubElement(c, "StorageClass").text = obj.get("storage_class") or "STANDARD"
if fetch_owner:
owner = SubElement(c, "Owner")
- SubElement(owner, "ID").text = get_account_id()
+ SubElement(owner, "ID").text = _canonical_owner_id()
SubElement(owner, "DisplayName").text = "ministack"
for cp in sorted(common_prefixes):
@@ -5597,7 +5608,7 @@ def _list_multipart_uploads(bucket_name: str, query_params: dict):
SubElement(initiator, "ID").text = get_account_id()
SubElement(initiator, "DisplayName").text = "ministack"
owner = SubElement(u, "Owner")
- SubElement(owner, "ID").text = get_account_id()
+ SubElement(owner, "ID").text = _canonical_owner_id()
SubElement(owner, "DisplayName").text = "ministack"
SubElement(u, "StorageClass").text = upload.get("storage_class") or "STANDARD"
SubElement(u, "Initiated").text = upload["created"]
@@ -5645,7 +5656,7 @@ def _list_parts(bucket_name: str, key: str, query_params: dict):
SubElement(initiator, "ID").text = get_account_id()
SubElement(initiator, "DisplayName").text = "ministack"
owner = SubElement(root, "Owner")
- SubElement(owner, "ID").text = get_account_id()
+ SubElement(owner, "ID").text = _canonical_owner_id()
SubElement(owner, "DisplayName").text = "ministack"
SubElement(root, "StorageClass").text = upload.get("storage_class") or "STANDARD"
SubElement(root, "PartNumberMarker").text = str(part_marker)
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index 9600519e..da11e1d7 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -1672,6 +1672,23 @@ def _invoke_with_callback(resource, input_data, token, state_def):
else:
if "aws-sdk:" in clean_resource:
_invoke_aws_sdk_integration(clean_resource, input_data)
+ elif clean_resource.startswith(
+ "arn:aws:states:::states:startExecution"):
+ # The child execution carries the task token in its input,
+ # so it has to be started before we block on the callback.
+ _invoke_nested_start_execution(clean_resource, input_data)
+ elif clean_resource.startswith("arn:aws:states:::"):
+ # An optimized integration MiniStack does not implement.
+ # Falling through here sends nothing and then blocks on the
+ # callback until TimeoutSeconds (default 99999), so the
+ # execution hangs instead of reporting the gap. Fail loudly,
+ # matching the synchronous dispatcher in _invoke_resource.
+ raise _ExecutionError(
+ "States.Runtime",
+ f"{resource} is not yet implemented in MiniStack. Use "
+ "the generic arn:aws:states:::aws-sdk:<service>:<action> "
+ "form, or open an issue for this optimized integration.",
+ )
except _ExecutionError:
_task_tokens.pop(token, None)
raise
diff --git a/tests/test_ec2.py b/tests/test_ec2.py
index 5770c371..bcd215bd 100644
--- a/tests/test_ec2.py
+++ b/tests/test_ec2.py
@@ -110,6 +110,16 @@ def test_ec2_availability_zone_ids_are_region_coded(ec2):
assert _az_id_prefix("cn-northwest-1") == "cnnw1"
+def test_ec2_availability_zones_carry_group_and_opt_in(ec2):
+ """GroupName / NetworkBorderGroup / OptInStatus are optional members, so leaving
+ them out reads to an SDK as "no value" rather than as an error: a caller filtering
+ on opt_in_status or grouping by group_names gets a wrong answer, not a failure."""
+ zones = ec2.describe_availability_zones()["AvailabilityZones"]
+ assert all(z["GroupName"] == "us-east-1-zg-1" for z in zones)
+ assert all(z["NetworkBorderGroup"] == "us-east-1" for z in zones)
+ assert all(z["OptInStatus"] == "opt-in-not-required" for z in zones)
+
+
def test_ec2_describe_regions_returns_commercial_regions(ec2):
"""DescribeRegions must list at least the four legacy us-* regions
with opt-in-not-required, and emit the shape AWS returns."""
diff --git a/tests/test_s3.py b/tests/test_s3.py
index 6102353c..b9cffcc6 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -5035,6 +5035,24 @@ def test_s3_conditional_delete_if_match(s3):
assert s3.get_object(Bucket=bucket, Key="cond")["Body"].read() == b"x"
+def test_s3_bucket_owner_id_is_consistent_and_canonical(s3):
+ """The canonical owner ID is one stable 64-hex value across ListBuckets,
+ GetBucketAcl and GetObjectAcl — not the account id or a placeholder (#1459)."""
+ import re
+ bkt = "intg-owner-1459"
+ s3.create_bucket(Bucket=bkt)
+ try:
+ s3.put_object(Bucket=bkt, Key="k", Body=b"x")
+ lb = s3.list_buckets()["Owner"]["ID"]
+ bacl = s3.get_bucket_acl(Bucket=bkt)["Owner"]["ID"]
+ oacl = s3.get_object_acl(Bucket=bkt, Key="k")["Owner"]["ID"]
+ assert lb == bacl == oacl, (lb, bacl, oacl)
+ assert re.fullmatch(r"[0-9a-f]{64}", lb), lb
+ finally:
+ s3.delete_object(Bucket=bkt, Key="k")
+ 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