Skip to content

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

Fix SFN EC2 security group integration (#574)

Jay Janssene7728a51b942
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8a45444d..5dfa379a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,8 @@ All notable changes to MiniStack will be documented here.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
Versioning follows [Semantic Versioning](https://semver.org/).
+
+- **Step Functions `aws-sdk:ec2` security group compatibility** — `CreateSecurityGroup` now maps the SDK `Description` parameter to EC2's query-wire `GroupDescription` while preserving `VpcId`, and `DescribeSecurityGroups` now sends EC2-shaped filters (`Filter.1.Value.1`) instead of the generic `member.N` form. The Step Functions XML adapter also returns `SecurityGroups` instead of raw `SecurityGroupInfo`, matching AWS SDK output.
---
## [1.3.28] — 2026-05-05
@@ -16,6 +18,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **DynamoDB legacy `Expected` (PutItem / UpdateItem / DeleteItem) and `KeyConditions` (Query)** — previously ignored; SDKs and code paths that still use the pre-expression API now work. `ScanFilter` / `QueryFilter` comparison support extended to all 13 legacy operators (`EQ`, `NE`, `LE`, `LT`, `GE`, `GT`, `NOT_NULL`, `NULL`, `CONTAINS`, `NOT_CONTAINS`, `BEGINS_WITH`, `IN`, `BETWEEN`) with type-aware numeric comparison. Reported by @darkamgine
- **DynamoDB `TransactWriteItems` multi-failure reporting** — only the first failing item was marked in `CancellationReasons`; AWS returns a `ConditionalCheckFailed` entry for every failing item in the transaction. Now evaluates all conditions in a first pass and reports each failure. Reported by @anghel93 and @gnjack
+
---
## [1.3.27] — 2026-05-04
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index 6b85d58a..83044d9e 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -2425,11 +2425,16 @@ def _prefix_sdk_error(service_name: str, error_code: str) -> str:
"""Prefix an SDK error code with the service name, matching real AWS SFN behavior.
E.g., ("secretsmanager", "ResourceExistsException") -> "SecretsManager.ResourceExistsException"
- If the error already has a dot prefix or is a States.* error, return as-is.
+ States.* errors and already service-prefixed errors are returned as-is.
+ Non-EC2 dotted legacy codes are preserved for backwards compatibility.
"""
- if "." in error_code:
+ if error_code.startswith("States."):
return error_code
prefix = _AWS_SDK_ERROR_PREFIX.get(service_name, service_name.capitalize())
+ if error_code.startswith(f"{prefix}."):
+ return error_code
+ if "." in error_code and service_name != "ec2":
+ return error_code
return f"{prefix}.{error_code}"
# Static action→path maps for REST-JSON services.
@@ -2538,6 +2543,46 @@ def _flatten_query_params(data, prefix=""):
return params
+_EC2_QUERY_LIST_NAME_OVERRIDES = {
+ "Filters": "Filter",
+ "Values": "Value",
+ "GroupIds": "GroupId",
+ "GroupNames": "GroupName",
+ "TagSpecifications": "TagSpecification",
+ "Tags": "Tag",
+}
+
+
+def _flatten_ec2_query_params(data, prefix=""):
+ """Flatten EC2 query params using EC2's numbered-list convention.
+
+ Most query services in MiniStack use ``member.N`` in the Step Functions
+ adapter. EC2's Query API expects bare numbered lists for the shapes used
+ here (e.g. ``Filter.1.Value.1`` and ``GroupId.1``).
+ """
+ params = {}
+ if not isinstance(data, dict):
+ return params
+ for key, value in data.items():
+ full_key = f"{prefix}{key}" if not prefix else f"{prefix}.{key}"
+ if isinstance(value, dict):
+ params.update(_flatten_ec2_query_params(value, full_key))
+ elif isinstance(value, list):
+ list_key = _EC2_QUERY_LIST_NAME_OVERRIDES.get(key, key)
+ full_list_key = f"{prefix}{list_key}" if not prefix else f"{prefix}.{list_key}"
+ for i, item in enumerate(value, 1):
+ item_key = f"{full_list_key}.{i}"
+ if isinstance(item, dict):
+ params.update(_flatten_ec2_query_params(item, item_key))
+ else:
+ params[item_key] = str(item)
+ elif isinstance(value, bool):
+ params[full_key] = "true" if value else "false"
+ else:
+ params[full_key] = str(value)
+ return params
+
+
# Fields in AWS XML responses that should be coerced to native types in JSON.
# Only fields that Step Functions consumers rely on being non-string.
_XML_NUMERIC_FIELDS = frozenset({
@@ -2661,6 +2706,10 @@ _QUERY_PARAM_NAME_OVERRIDES = {
("rds", "RemoveFromGlobalCluster"): {
"DbClusterIdentifier": "DbClusterIdentifier",
},
+ ("ec2", "CreateSecurityGroup"): {
+ "Description": "GroupDescription",
+ "VpcId": "VpcId",
+ },
}
@@ -2747,6 +2796,57 @@ def _convert_keys_to_sfn_convention(obj):
return obj
+def _query_item_list(value):
+ if value in (None, ""):
+ return []
+ if isinstance(value, dict) and "item" in value:
+ item = value["item"]
+ return item if isinstance(item, list) else [item]
+ return value if isinstance(value, list) else [value]
+
+
+def _normalize_ec2_security_group(group):
+ if not isinstance(group, dict):
+ return group
+ if "groupDescription" in group:
+ group["Description"] = group.pop("groupDescription")
+ if "tagSet" in group:
+ group["Tags"] = _query_item_list(group.pop("tagSet"))
+
+ for permission_key in ("ipPermissions", "ipPermissionsEgress"):
+ if permission_key not in group:
+ continue
+ permissions = _query_item_list(group[permission_key])
+ for permission in permissions:
+ if not isinstance(permission, dict):
+ continue
+ for list_key in ("ipRanges", "ipv6Ranges", "prefixListIds"):
+ if list_key in permission:
+ permission[list_key] = _query_item_list(permission[list_key])
+ if "groups" in permission:
+ permission["UserIdGroupPairs"] = _query_item_list(permission.pop("groups"))
+ group[permission_key] = permissions
+ return group
+
+
+def _normalize_query_response(service_key, action, result):
+ if not isinstance(result, dict):
+ return result
+ if service_key == "ec2" and action == "DescribeSecurityGroups":
+ raw_groups = result.pop("securityGroupInfo", None)
+ if raw_groups is not None:
+ if isinstance(raw_groups, dict) and "item" in raw_groups:
+ raw_groups = raw_groups["item"]
+ if raw_groups == "":
+ groups = []
+ elif isinstance(raw_groups, list):
+ groups = raw_groups
+ else:
+ groups = [raw_groups]
+ result["SecurityGroups"] = [_normalize_ec2_security_group(group) for group in groups]
+ return result
+
+
def _dispatch_aws_sdk_query(service_info, service_name, action, input_data):
"""Dispatch an aws-sdk integration call to a query-protocol MiniStack service."""
import xml.etree.ElementTree as ET
@@ -2770,7 +2870,10 @@ def _dispatch_aws_sdk_query(service_info, service_name, action, input_data):
name_overrides = _QUERY_PARAM_NAME_OVERRIDES.get((service_key, pascal_action))
wire_data = _convert_params_to_api_names(input_data, name_overrides)
form_params = {"Action": pascal_action}
- form_params.update(_flatten_query_params(wire_data))
+ if service_key == "ec2":
+ form_params.update(_flatten_ec2_query_params(wire_data))
+ else:
+ form_params.update(_flatten_query_params(wire_data))
body = urlencode(form_params)
headers = {
@@ -2832,6 +2935,7 @@ def _dispatch_aws_sdk_query(service_info, service_name, action, input_data):
result = result[result_key]
# Drop ResponseMetadata
result.pop("ResponseMetadata", None)
+ result = _normalize_query_response(service_key, pascal_action, result)
return _convert_keys_to_sfn_convention(result)
except ET.ParseError:
raise _ExecutionError("States.Runtime", f"Failed to parse {service_name} XML response")
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index 222e2483..5174a7fe 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -687,6 +687,143 @@ def test_sfn_aws_sdk_rds_create_and_describe_cluster(sfn, sfn_sync):
sfn_sync.delete_state_machine(stateMachineArn=sm_arn)
+
+def test_sfn_aws_sdk_ec2_security_group_create_and_describe(sfn_sync, ec2):
+ """aws-sdk:ec2 CreateSecurityGroup + DescribeSecurityGroups use EC2 query shapes."""
+ import uuid as _uuid
+
+ vpc_id = ec2.create_vpc(CidrBlock="10.91.0.0/16")["Vpc"]["VpcId"]
+ group_name = f"sfn-ec2-sg-{_uuid.uuid4().hex[:8]}"
+ description = "created through sfn aws-sdk ec2"
+ sm_name = f"sdk-ec2-sg-{_uuid.uuid4().hex[:8]}"
+ sm_arn = None
+ sg_id = None
+
+ definition = json.dumps({
+ "StartAt": "CreateSecurityGroup",
+ "States": {
+ "CreateSecurityGroup": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::aws-sdk:ec2:createSecurityGroup",
+ "Parameters": {
+ "GroupName": group_name,
+ "Description": description,
+ "VpcId": vpc_id,
+ "TagSpecifications": [
+ {
+ "ResourceType": "security-group",
+ "Tags": [{"Key": "Name", "Value": group_name}],
+ }
+ ],
+ },
+ "ResultPath": "$.createResult",
+ "Next": "DescribeSecurityGroups",
+ },
+ "DescribeSecurityGroups": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::aws-sdk:ec2:describeSecurityGroups",
+ "Parameters": {
+ "Filters": [
+ {"Name": "vpc-id", "Values": [vpc_id]},
+ {"Name": "group-name", "Values": [group_name]},
+ ],
+ },
+ "ResultPath": "$.describeResult",
+ "Next": "Done",
+ },
+ "Done": {"Type": "Succeed"},
+ },
+ })
+
+ try:
+ sm_arn = sfn_sync.create_state_machine(
+ name=sm_name,
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/sfn-role",
+ )["stateMachineArn"]
+
+ resp = sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input=json.dumps({}))
+ assert resp["status"] == "SUCCEEDED", f"Execution failed: {resp.get('error')} — {resp.get('cause')}"
+ output = json.loads(resp["output"])
+
+ sg_id = output["createResult"]["GroupId"]
+ assert sg_id.startswith("sg-")
+
+ describe_result = output["describeResult"]
+ assert "SecurityGroups" in describe_result
+ assert "SecurityGroupInfo" not in describe_result
+ groups = describe_result["SecurityGroups"]
+ assert isinstance(groups, list)
+ assert len(groups) == 1
+ assert groups[0]["GroupId"] == sg_id
+ assert groups[0]["GroupName"] == group_name
+ assert groups[0]["Description"] == description
+ assert groups[0]["VpcId"] == vpc_id
+ assert groups[0]["Tags"] == [{"Key": "Name", "Value": group_name}]
+ finally:
+ if sg_id:
+ ec2.delete_security_group(GroupId=sg_id)
+ ec2.delete_vpc(VpcId=vpc_id)
+ if sm_arn:
+ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)
+
+
+def test_sfn_aws_sdk_ec2_security_group_duplicate_error(sfn_sync, ec2):
+ """aws-sdk:ec2 CreateSecurityGroup preserves AWS duplicate-name errors."""
+ import uuid as _uuid
+
+ group_name = f"sfn-ec2-sg-dup-{_uuid.uuid4().hex[:8]}"
+ sm_name = f"sdk-ec2-sg-dup-{_uuid.uuid4().hex[:8]}"
+ sm_arn = None
+
+ definition = json.dumps({
+ "StartAt": "CreateFirst",
+ "States": {
+ "CreateFirst": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::aws-sdk:ec2:createSecurityGroup",
+ "Parameters": {
+ "GroupName": group_name,
+ "Description": "first",
+ "VpcId": "vpc-00000001",
+ },
+ "Next": "CreateDuplicate",
+ },
+ "CreateDuplicate": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::aws-sdk:ec2:createSecurityGroup",
+ "Parameters": {
+ "GroupName": group_name,
+ "Description": "second",
+ "VpcId": "vpc-00000001",
+ },
+ "End": True,
+ },
+ },
+ })
+
+ try:
+ sm_arn = sfn_sync.create_state_machine(
+ name=sm_name,
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/sfn-role",
+ )["stateMachineArn"]
+
+ resp = sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input=json.dumps({}))
+ assert resp["status"] == "FAILED"
+ assert resp["error"] == "Ec2.InvalidGroup.Duplicate"
+ assert "already exists" in resp["cause"]
+ finally:
+ groups = ec2.describe_security_groups(Filters=[
+ {"Name": "vpc-id", "Values": ["vpc-00000001"]},
+ {"Name": "group-name", "Values": [group_name]},
+ ])["SecurityGroups"]
+ for group in groups:
+ ec2.delete_security_group(GroupId=group["GroupId"])
+ if sm_arn:
+ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)
+
+
def test_sfn_aws_sdk_rds_create_and_describe_instance(sfn, sfn_sync):
"""aws-sdk:rds CreateDBInstance + DescribeDBInstances via query-protocol dispatch."""
import uuid as _uuid