Skip to content

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

bug fix 597, 596, 594, 593 (#599)

Nahuel Nucerabdde87622daf
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index e6a0131f..d14de38e 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -736,7 +736,16 @@ def _query(data):
else:
candidates = list(table["items"].get(pk_val, {}).values())
- if sk_name:
+ if is_gsi or index_name:
+ # GSI/LSI: order by (INDEX_SORT, BASE_PK, BASE_SK). The base-table keys
+ # tiebreak rows with equal INDEX_SORT (or hash-only GSIs), matching
+ # real DynamoDB's hidden ordering and making pagination cursors stable.
+ sort_keys = _index_order_keys(table, sk_name)
+ candidates.sort(
+ key=lambda it: tuple(_index_order_value(it, n, t) for n, t in sort_keys),
+ reverse=not scan_forward,
+ )
+ elif sk_name:
sk_type = _get_attr_type(table, sk_name)
candidates.sort(key=lambda it: _sort_key_value(it.get(sk_name), sk_type), reverse=not scan_forward)
@@ -746,7 +755,7 @@ def _query(data):
candidates = [it for it in candidates if _evaluate_condition(key_cond, it, eav, ean)]
if esk:
- candidates = _apply_exclusive_start_key(candidates, esk, pk_name, sk_name, scan_forward)
+ candidates = _apply_exclusive_start_key(candidates, esk, pk_name, sk_name, scan_forward, table=table)
has_more = False
if limit is not None and len(candidates) > limit:
@@ -2506,11 +2515,39 @@ def _extract_pk_from_condition(condition, attr_values, attr_names, pk_name):
# Pagination helpers
# ---------------------------------------------------------------------------
-def _apply_exclusive_start_key(candidates, esk, pk_name, sk_name, scan_forward=True):
+def _index_order_value(item, name, type_hint):
+ """Single position in the GSI/LSI ordering tuple. Hash-only items, sparse
+ GSIs, or items missing a key get a stable filler so tuples remain
+ comparable across the candidate set."""
+ if not name or name not in item:
+ return Decimal(0) if type_hint == "N" else ""
+ return _sort_key_value(item.get(name), type_hint)
+
+
+def _index_order_keys(table, sk_name):
+ """Ordered list of (attr_name, attr_type) used to sort a GSI/LSI Query
+ result deterministically: (INDEX_SORT, BASE_PK, BASE_SK). Real DynamoDB
+ orders by (INDEX_HASH, INDEX_SORT, BASE_PK, BASE_SK); INDEX_HASH is fixed
+ per Query so it drops out of the ordering. The base-table keys break ties
+ when multiple items share the same INDEX_SORT value (or when the GSI is
+ hash-only)."""
+ seen = set()
+ keys = []
+ for n in (sk_name, table.get("pk_name"), table.get("sk_name")):
+ if n and n not in seen:
+ seen.add(n)
+ keys.append((n, _get_attr_type(table, n)))
+ return keys
+
+
+def _apply_exclusive_start_key(candidates, esk, pk_name, sk_name, scan_forward=True, table=None):
+ """Skip past the ESK cursor item, breaking ties on the GSI sort key with
+ the base table's primary key — same hidden ordering real DynamoDB uses."""
if not esk or not candidates:
return candidates
- # Hash-only table: no sort key — find the item matching the PK and return everything after it
- if not sk_name or sk_name not in esk:
+ # Hash-only base-table query — candidates are uniquely keyed by pk, so a
+ # cursor at all simply means "we already returned this one item."
+ if table is None and not sk_name:
start_pk = _extract_key_val(esk.get(pk_name, {}))
found = False
result = []
@@ -2520,17 +2557,30 @@ def _apply_exclusive_start_key(candidates, esk, pk_name, sk_name, scan_forward=T
elif _extract_key_val(item.get(pk_name, {})) == start_pk:
found = True
return result
- start_sk = esk[sk_name]
+ keys = _index_order_keys(table, sk_name) if table is not None else []
+ if not keys:
+ # Fall back to the legacy single-key compare for callers that didn't
+ # pass `table` (no GSI tiebreak available).
+ if not sk_name or sk_name not in esk:
+ return candidates
+ start_sk = esk[sk_name]
+ result = []
+ for item in candidates:
+ if item.get(sk_name) is None:
+ continue
+ op = '>' if scan_forward else '<'
+ if _compare_ddb(item.get(sk_name), op, start_sk):
+ result.append(item)
+ return result
+ cursor = tuple(_index_order_value(esk, n, t) for n, t in keys)
result = []
for item in candidates:
- item_sk = item.get(sk_name)
- if item_sk is None:
- continue
+ item_tuple = tuple(_index_order_value(item, n, t) for n, t in keys)
if scan_forward:
- if _compare_ddb(item_sk, '>', start_sk):
+ if item_tuple > cursor:
result.append(item)
else:
- if _compare_ddb(item_sk, '<', start_sk):
+ if item_tuple < cursor:
result.append(item)
return result
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index 9bfd3bf3..b6d60437 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -309,10 +309,22 @@ def _run_instances(p):
sg_ids = [_DEFAULT_SG_ID]
now = _now_ts()
+ # Optional caller-provided values: respect them if set; fall back to defaults otherwise.
+ requested_private_ip = _p(p, "PrivateIpAddress")
+ iam_arn = _p(p, "IamInstanceProfile.Arn")
+ iam_name = _p(p, "IamInstanceProfile.Name")
+ iam_profile = None
+ if iam_arn or iam_name:
+ # Real AWS returns both Arn and Id. We synthesize a stable Id from the
+ # name/arn so DescribeInstances reads back as it does on AWS.
+ if not iam_arn and iam_name:
+ iam_arn = f"arn:aws:iam::{get_account_id()}:instance-profile/{iam_name}"
+ iam_id = "AIPA" + new_uuid().replace("-", "").upper()[:17]
+ iam_profile = {"Arn": iam_arn, "Id": iam_id}
created = []
for _ in range(max(1, min(min_count, max_count))):
instance_id = _new_instance_id()
- private_ip = _random_ip("10.0")
+ private_ip = requested_private_ip or _random_ip("10.0.")
# Synthesize a real root EBS volume so DescribeVolumes / DescribeInstances
# surface the same volume id, matching real AWS where every EBS-backed AMI
# auto-attaches a root volume regardless of whether the launch request
@@ -380,6 +392,7 @@ def _run_instances(p):
"UserData": user_data,
"LaunchTime": now,
"BlockDeviceMappings": block_device_mappings,
+ "IamInstanceProfile": iam_profile,
}
created.append(_instances[instance_id])
@@ -2186,7 +2199,7 @@ def _instance_xml(inst):
<rootDeviceType>{inst['RootDeviceType']}</rootDeviceType>
<rootDeviceName>{inst['RootDeviceName']}</rootDeviceName>
<blockDeviceMapping>{_inst_bdm_xml(inst)}</blockDeviceMapping>
- <virtualizationType>{inst['Virtualization']}</virtualizationType>
+ {_inst_iam_xml(inst)}<virtualizationType>{inst['Virtualization']}</virtualizationType>
<hypervisor>{inst['Hypervisor']}</hypervisor>
<monitoring><state>{inst['Monitoring']['State']}</state></monitoring>
<groupSet>{sgs}</groupSet>
@@ -2195,6 +2208,19 @@ def _instance_xml(inst):
</item>"""
+def _inst_iam_xml(inst):
+ """Emit <iamInstanceProfile> block when an IAM profile is attached."""
+ iip = inst.get("IamInstanceProfile")
+ if not iip or not (iip.get("Arn") or iip.get("Id")):
+ return ""
+ return (
+ "<iamInstanceProfile>"
+ f"<arn>{_esc(iip.get('Arn', ''))}</arn>"
+ f"<id>{_esc(iip.get('Id', ''))}</id>"
+ "</iamInstanceProfile>"
+ )
+
+
def _inst_bdm_xml(inst):
"""Emit the running-instance BlockDeviceMapping shape. Distinct from the
launch-spec shape which carries VolumeSize/VolumeType/Encrypted; the
@@ -2604,7 +2630,8 @@ def _new_igw_id():
def _random_ip(prefix):
- return f"{prefix}{random.randint(1,254)}.{random.randint(1,254)}"
+ sep = "" if prefix.endswith(".") else "."
+ return f"{prefix}{sep}{random.randint(1,254)}.{random.randint(1,254)}"
def _now_ts():
diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.py
index d584b53d..ed74a968 100644
--- a/tests/test_dynamodb.py
+++ b/tests/test_dynamodb.py
@@ -1053,6 +1053,125 @@ def test_dynamodb_ttl_expiry(ddb):
assert desc["TimeToLiveStatus"] == "ENABLED"
assert desc["AttributeName"] == "expires_at"
+def test_dynamodb_gsi_query_pagination_with_collisions(ddb):
+ """GSI Query with ExclusiveStartKey must paginate correctly when multiple
+ items share the same GSI sort-key value. Real DynamoDB tiebreaks on the
+ base table's primary key — emulator must do the same or pagination silently
+ drops items from page 2 onwards. Regression for issue #597."""
+ table = "t_gsi_pag_collide"
+ ddb.create_table(
+ TableName=table,
+ KeySchema=[
+ {"AttributeName": "pk", "KeyType": "HASH"},
+ {"AttributeName": "sk", "KeyType": "RANGE"},
+ ],
+ AttributeDefinitions=[
+ {"AttributeName": "pk", "AttributeType": "S"},
+ {"AttributeName": "sk", "AttributeType": "S"},
+ {"AttributeName": "gsi1pk", "AttributeType": "S"},
+ {"AttributeName": "gsi1sk", "AttributeType": "S"},
+ ],
+ GlobalSecondaryIndexes=[
+ {
+ "IndexName": "gsi1",
+ "KeySchema": [
+ {"AttributeName": "gsi1pk", "KeyType": "HASH"},
+ {"AttributeName": "gsi1sk", "KeyType": "RANGE"},
+ ],
+ "Projection": {"ProjectionType": "ALL"},
+ }
+ ],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ # Five items sharing the SAME (gsi1pk, gsi1sk); only base pk differs.
+ for i in range(5):
+ ddb.put_item(
+ TableName=table,
+ Item={
+ "pk": {"S": f"item-{i}"},
+ "sk": {"S": "X"},
+ "gsi1pk": {"S": "GROUP"},
+ "gsi1sk": {"S": "X"},
+ },
+ )
+
+ seen, last_key, pages = [], None, 0
+ while True:
+ pages += 1
+ kwargs = dict(
+ TableName=table,
+ IndexName="gsi1",
+ KeyConditionExpression="gsi1pk = :v",
+ ExpressionAttributeValues={":v": {"S": "GROUP"}},
+ Limit=3,
+ )
+ if last_key is not None:
+ kwargs["ExclusiveStartKey"] = last_key
+ out = ddb.query(**kwargs)
+ seen.extend(it["pk"]["S"] for it in out.get("Items", []))
+ last_key = out.get("LastEvaluatedKey")
+ if last_key is None or pages >= 10:
+ break
+
+ assert pages < 10, f"pagination did not terminate: {pages} pages, seen={seen}"
+ assert sorted(seen) == [f"item-{i}" for i in range(5)], (
+ f"expected all 5 items via cursor, got {seen}"
+ )
+
+
+def test_dynamodb_gsi_hash_only_query_pagination(ddb):
+ """GSI with no sort key must paginate without cycling through the same
+ items. Regression for issue #593."""
+ table = "t_gsi_hash_only_pag"
+ ddb.create_table(
+ TableName=table,
+ KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
+ AttributeDefinitions=[
+ {"AttributeName": "id", "AttributeType": "S"},
+ {"AttributeName": "bucket", "AttributeType": "N"},
+ ],
+ GlobalSecondaryIndexes=[
+ {
+ "IndexName": "bucket-index",
+ "KeySchema": [{"AttributeName": "bucket", "KeyType": "HASH"}],
+ "Projection": {"ProjectionType": "ALL"},
+ }
+ ],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ n = 25
+ for i in range(n):
+ ddb.put_item(
+ TableName=table,
+ Item={
+ "id": {"S": f"row-{i:04d}"},
+ "bucket": {"N": "0"},
+ },
+ )
+
+ seen, last_key, pages = [], None, 0
+ while True:
+ pages += 1
+ kwargs = dict(
+ TableName=table,
+ IndexName="bucket-index",
+ KeyConditionExpression="bucket = :v",
+ ExpressionAttributeValues={":v": {"N": "0"}},
+ Limit=8,
+ )
+ if last_key is not None:
+ kwargs["ExclusiveStartKey"] = last_key
+ out = ddb.query(**kwargs)
+ seen.extend(it["id"]["S"] for it in out.get("Items", []))
+ last_key = out.get("LastEvaluatedKey")
+ if last_key is None or pages >= 10:
+ break
+
+ assert pages < 10, f"pagination did not terminate: {pages} pages, seen={seen}"
+ assert len(seen) == n, f"expected {n} unique items, got {len(seen)}: {seen}"
+ assert len(set(seen)) == n, f"items duplicated across pages: {seen}"
+
+
def test_dynamodb_query_pagination_hash_only(ddb):
"""Pagination on a hash-only table (no sort key) must return results after the ESK."""
table = "t_hash_paginate"
diff --git a/tests/test_ec2.py b/tests/test_ec2.py
index 8b9d0fdd..c9d708c8 100644
--- a/tests/test_ec2.py
+++ b/tests/test_ec2.py
@@ -64,6 +64,54 @@ def test_ec2_run_describe_terminate_instances(ec2):
assert term["TerminatingInstances"][0]["CurrentState"]["Name"] == "terminated"
+def test_ec2_run_instances_honors_private_ip_and_iam_profile(ec2):
+ """RunInstances must reflect --private-ip-address and --iam-instance-profile
+ on the created instance and in DescribeInstances. Regression for issue #594."""
+ profile_arn = "arn:aws:iam::000000000000:instance-profile/ec2-test-profile"
+ resp = ec2.run_instances(
+ ImageId="ami-12345678",
+ MinCount=1,
+ MaxCount=1,
+ InstanceType="t3.micro",
+ PrivateIpAddress="172.31.0.42",
+ IamInstanceProfile={"Arn": profile_arn},
+ )
+ inst = resp["Instances"][0]
+ iid = inst["InstanceId"]
+ try:
+ # PrivateIpAddress is the value the caller passed, not a random one,
+ # and is well-formed (4 octets ≤ 255).
+ assert inst["PrivateIpAddress"] == "172.31.0.42"
+ assert all(0 <= int(o) <= 255 for o in inst["PrivateIpAddress"].split("."))
+ # PrivateDnsName is derived from the assigned IP, not malformed.
+ assert inst["PrivateDnsName"] == "ip-172-31-0-42.ec2.internal"
+ # IamInstanceProfile is attached and surfaced.
+ assert inst["IamInstanceProfile"]["Arn"] == profile_arn
+ assert inst["IamInstanceProfile"]["Id"]
+
+ # DescribeInstances surfaces the same.
+ desc = ec2.describe_instances(InstanceIds=[iid])
+ d_inst = desc["Reservations"][0]["Instances"][0]
+ assert d_inst["PrivateIpAddress"] == "172.31.0.42"
+ assert d_inst["IamInstanceProfile"]["Arn"] == profile_arn
+ finally:
+ ec2.terminate_instances(InstanceIds=[iid])
+
+
+def test_ec2_run_instances_default_private_ip_is_well_formed(ec2):
+ """When the caller does not pass --private-ip-address, the auto-generated
+ address must still be a valid IPv4. Regression for the 10.0193.216 bug
+ in #594 (missing dot separator in _random_ip prefix)."""
+ resp = ec2.run_instances(ImageId="ami-1", MinCount=1, MaxCount=1)
+ inst = resp["Instances"][0]
+ try:
+ octets = inst["PrivateIpAddress"].split(".")
+ assert len(octets) == 4, f"malformed IP: {inst['PrivateIpAddress']}"
+ assert all(0 <= int(o) <= 255 for o in octets)
+ finally:
+ ec2.terminate_instances(InstanceIds=[inst["InstanceId"]])
+
+
def test_ec2_run_instances_emits_default_root_block_device_mapping(ec2):
"""RunInstances without an explicit BDM must auto-attach a root EBS volume,
matching real AWS. Cloud Custodian / AWS Config use BlockDeviceMappings to