Skip to content

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

fix(multi): catch up (#927)

Nahuel Nucera057e2512dff0
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index e5558179..97224d2e 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -2355,13 +2355,25 @@ def _perm_xml(r):
f"<item><cidrIp>{ip['CidrIp']}</cidrIp></item>"
for ip in r.get("IpRanges", [])
)
+ groups = ""
+ for pair in r.get("UserIdGroupPairs", []):
+ if isinstance(pair, dict):
+ gid = pair.get("GroupId", "")
+ uid = pair.get("UserId") or get_account_id()
+ gname = f"<groupName>{_esc(pair['GroupName'])}</groupName>" if pair.get("GroupName") else ""
+ vpc = f"<vpcId>{_esc(pair['VpcId'])}</vpcId>" if pair.get("VpcId") else ""
+ desc = f"<description>{_esc(pair['Description'])}</description>" if pair.get("Description") else ""
+ else:
+ gid, uid, gname, vpc, desc = str(pair), get_account_id(), "", "", ""
+ groups += (f"<item><userId>{uid}</userId><groupId>{gid}</groupId>"
+ f"{gname}{vpc}{desc}</item>")
from_port = f"<fromPort>{r['FromPort']}</fromPort>" if "FromPort" in r else ""
to_port = f"<toPort>{r['ToPort']}</toPort>" if "ToPort" in r else ""
return f"""<item>
<ipProtocol>{r.get('IpProtocol','-1')}</ipProtocol>
{from_port}{to_port}
<ipRanges>{ranges}</ipRanges>
- <ipv6Ranges/><prefixListIds/><groups/>
+ <ipv6Ranges/><prefixListIds/><groups>{groups}</groups>
</item>"""
@@ -2694,6 +2706,28 @@ def _parse_ip_permissions(params, prefix):
entry["Description"] = desc
rule["Ipv6Ranges"].append(entry)
j += 1
+ j = 1
+ while True:
+ gid = _p(params, f"{prefix}.{i}.Groups.{j}.GroupId")
+ gname = _p(params, f"{prefix}.{i}.Groups.{j}.GroupName")
+ if not gid and not gname:
+ break
+ pair = {}
+ if gid:
+ pair["GroupId"] = gid
+ if gname:
+ pair["GroupName"] = gname
+ uid = _p(params, f"{prefix}.{i}.Groups.{j}.UserId")
+ if uid:
+ pair["UserId"] = uid
+ vpc = _p(params, f"{prefix}.{i}.Groups.{j}.VpcId")
+ if vpc:
+ pair["VpcId"] = vpc
+ desc = _p(params, f"{prefix}.{i}.Groups.{j}.Description")
+ if desc:
+ pair["Description"] = desc
+ rule["UserIdGroupPairs"].append(pair)
+ j += 1
rules.append(rule)
i += 1
return rules
@@ -4163,6 +4197,21 @@ def _describe_security_group_rules(p):
<toPort>{rule.get('ToPort', -1)}</toPort>
<cidrIpv4>{cidr.get('CidrIp', '')}</cidrIpv4>
</item>"""
+ for pair in rule.get("UserIdGroupPairs", []):
+ gid = pair.get("GroupId", "") if isinstance(pair, dict) else str(pair)
+ items += f"""<item>
+ <securityGroupRuleId>{rule_id}</securityGroupRuleId>
+ <groupId>{sg_id}</groupId>
+ <groupOwnerId>{get_account_id()}</groupOwnerId>
+ <isEgress>false</isEgress>
+ <ipProtocol>{rule.get('IpProtocol', '-1')}</ipProtocol>
+ <fromPort>{rule.get('FromPort', -1)}</fromPort>
+ <toPort>{rule.get('ToPort', -1)}</toPort>
+ <referencedGroupInfo>
+ <groupId>{gid}</groupId>
+ <userId>{get_account_id()}</userId>
+ </referencedGroupInfo>
+ </item>"""
for i, rule in enumerate(sg.get("IpPermissionsEgress", [])):
rule_id = f"sgr-{sg_id[3:]}-egress-{i}"
for cidr in rule.get("IpRanges", []):
@@ -4176,6 +4225,21 @@ def _describe_security_group_rules(p):
<toPort>{rule.get('ToPort', -1)}</toPort>
<cidrIpv4>{cidr.get('CidrIp', '')}</cidrIpv4>
</item>"""
+ for pair in rule.get("UserIdGroupPairs", []):
+ gid = pair.get("GroupId", "") if isinstance(pair, dict) else str(pair)
+ items += f"""<item>
+ <securityGroupRuleId>{rule_id}</securityGroupRuleId>
+ <groupId>{sg_id}</groupId>
+ <groupOwnerId>{get_account_id()}</groupOwnerId>
+ <isEgress>true</isEgress>
+ <ipProtocol>{rule.get('IpProtocol', '-1')}</ipProtocol>
+ <fromPort>{rule.get('FromPort', -1)}</fromPort>
+ <toPort>{rule.get('ToPort', -1)}</toPort>
+ <referencedGroupInfo>
+ <groupId>{gid}</groupId>
+ <userId>{get_account_id()}</userId>
+ </referencedGroupInfo>
+ </item>"""
return _xml(200, "DescribeSecurityGroupRulesResponse", f"<securityGroupRuleSet>{items}</securityGroupRuleSet>")
diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.py
index 58dfc9ca..88dffd55 100644
--- a/ministack/services/eventbridge.py
+++ b/ministack/services/eventbridge.py
@@ -993,16 +993,22 @@ def _apply_input_transformer(transformer, event, rule=None):
except (KeyError, TypeError, IndexError):
replacements[var_name] = ""
+ # AWS generates ingestion-time when the event is received by EventBridge
+ # (always present, ISO-8601) — it is NOT the event's own `time` field and
+ # cannot be overwritten by an InputPathsMap entry.
+ ingestion_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
reserved = {
"aws.events.event.json": json.dumps(event_envelope),
"aws.events.event": json.dumps({k: v for k, v in event_envelope.items() if k != "detail"}),
- "aws.events.event.ingestion-time": event_envelope.get("time", ""),
+ "aws.events.event.ingestion-time": ingestion_time,
}
if rule:
reserved["aws.events.rule-name"] = rule.get("Name", "")
reserved["aws.events.rule-arn"] = rule.get("Arn", "")
for k, v in reserved.items():
replacements.setdefault(k, v)
+ # ingestion-time is reserved and uneditable, even if InputPathsMap declares it.
+ replacements["aws.events.event.ingestion-time"] = ingestion_time
result = template
for var_name, val in replacements.items():
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index d006d89a..e7d95c79 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -1347,6 +1347,7 @@ def _execute_task(state_def, raw_input, execution, ctx):
query_language = _state_query_language(state_def, ctx)
# SFN mock config — return canned response if configured (AWS SFN Local format)
+ _mock_throw = None
if _sfn_mock_config and execution:
test_case = execution.get("testCase", "")
sm_name = ctx.get("StateMachine", {}).get("Name", "")
@@ -1357,24 +1358,27 @@ def _execute_task(state_def, raw_input, execution, ctx):
if mock is not None:
attempts[state_name] = attempt + 1
if "Throw" in mock:
- raise _ExecutionError(
+ # Feed the mocked error into the same Retry/Catch machinery a real
+ # task failure uses (#903). Raising here bypassed Catch entirely.
+ _mock_throw = _ExecutionError(
mock["Throw"].get("Error", "MockError"),
mock["Throw"].get("Cause", "Mocked failure"))
- mock_result = mock.get("Return", {})
- if query_language == "JSONata":
- output = _apply_jsonata_output(
- state_def,
- raw_input,
- ctx,
- result=mock_result,
- default=mock_result,
- )
- _apply_state_assign(state_def, raw_input, ctx, result=mock_result)
else:
- result = _apply_result_selector(state_def, mock_result)
- output = _apply_result_path(state_def, raw_input, result)
- output = _apply_output_path(state_def, output)
- return output, _next_or_end(state_def)
+ mock_result = mock.get("Return", {})
+ if query_language == "JSONata":
+ output = _apply_jsonata_output(
+ state_def,
+ raw_input,
+ ctx,
+ result=mock_result,
+ default=mock_result,
+ )
+ _apply_state_assign(state_def, raw_input, ctx, result=mock_result)
+ else:
+ result = _apply_result_selector(state_def, mock_result)
+ output = _apply_result_path(state_def, raw_input, result)
+ output = _apply_output_path(state_def, output)
+ return output, _next_or_end(state_def)
if is_callback:
ctx["Task"] = {"Token": new_uuid()}
@@ -1401,6 +1405,9 @@ def _execute_task(state_def, raw_input, execution, ctx):
},
})
+ if _mock_throw is not None:
+ raise _mock_throw
+
if is_callback:
task_result = _invoke_with_callback(
resource, effective, ctx["Task"]["Token"], state_def)
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index ec951cfe..ab7354c6 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -2628,6 +2628,59 @@ def test_sfn_mock_config_throw(sfn):
assert desc["status"] == "FAILED"
_ministack_config({"stepfunctions._sfn_mock_config": {}})
+
+def test_sfn_mock_config_throw_routes_to_catch(sfn):
+ """SFN_MOCK_CONFIG Throw must route to a matching Catch (not bypass it). #903."""
+ from conftest import _ministack_config
+
+ mock_cfg = {
+ "StateMachines": {
+ "qa-sfn-mock-throw-catch": {
+ "TestCases": {"FailPath": {"CallService": "MockedFailure"}}
+ }
+ },
+ "MockedResponses": {
+ "MockedFailure": {
+ "0": {"Throw": {"Error": "ServiceDown", "Cause": "mocked failure"}},
+ }
+ },
+ }
+ _ministack_config({"stepfunctions._sfn_mock_config": mock_cfg})
+
+ definition = json.dumps({
+ "StartAt": "CallService",
+ "States": {
+ "CallService": {
+ "Type": "Task",
+ "Resource": "arn:aws:lambda:us-east-1:000000000000:function:nonexistent",
+ "Catch": [{"ErrorEquals": ["ServiceDown"], "Next": "Recovered"}],
+ "End": True,
+ },
+ "Recovered": {"Type": "Pass", "Result": {"recovered": True}, "End": True},
+ },
+ })
+ sm_arn = sfn.create_state_machine(
+ name="qa-sfn-mock-throw-catch",
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/r",
+ )["stateMachineArn"]
+
+ exec_arn = sfn.start_execution(
+ stateMachineArn=sm_arn + "#FailPath", input="{}",
+ )["executionArn"]
+ for _ in range(20):
+ time.sleep(0.3)
+ desc = sfn.describe_execution(executionArn=exec_arn)
+ if desc["status"] != "RUNNING":
+ break
+
+ assert desc["status"] == "SUCCEEDED", f"Throw bypassed Catch: {desc.get('status')}"
+ # Reached the Catch's Next state ("Recovered"), proving the throw routed
+ # through Catch rather than failing the execution.
+ assert json.loads(desc["output"]) == {"recovered": True}
+ _ministack_config({"stepfunctions._sfn_mock_config": {}})
+
+
def test_sfn_mock_config_jsonata_assign_applied(sfn):
"""SFN_MOCK_CONFIG + JSONata Task with Assign — variable must be visible downstream.