Skip to content

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

fix(ec2): accept legacy source-group params and return ReferencedGroupInfo (#916) (#929)

Yuriy R88211806c69a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f2046b6a..4f13cd6a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,7 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [1.3.64] — 2026-06-15
### Fixed
-- **EC2 — source security groups (`UserIdGroupPairs`) now returned by `DescribeSecurityGroupRules` / `DescribeSecurityGroups`** — `AuthorizeSecurityGroupIngress`/`Egress` rules that reference another security group were dropped at ingestion and never surfaced: `DescribeSecurityGroupRules` omitted `ReferencedGroupInfo` and `DescribeSecurityGroups` returned an empty `<groups>`. Source-group pairs are now parsed and emitted by both. Reported by @kamegoro.
+- **EC2 — source security groups (`UserIdGroupPairs`) now returned by `DescribeSecurityGroupRules` / `DescribeSecurityGroups`** — `AuthorizeSecurityGroupIngress`/`Egress` rules that reference another security group were dropped at ingestion and never surfaced: `DescribeSecurityGroupRules` omitted `ReferencedGroupInfo` and `DescribeSecurityGroups` returned an empty `<groups>`. Source-group pairs are now parsed and emitted by both. Reported by @kamegoro. Contributed by @kurok.
- **Step Functions — mocked `Throw` responses now route to `Catch`** — a `SFN_MOCK_CONFIG` `Throw` was raised above the state's Retry/Catch handling, so the execution always failed instead of routing to a matching `Catch` handler. The mocked error now flows through the same Retry/Catch machinery as a real task failure. Reported by @amissemer.
- **Glue — `GetUserDefinedFunctions` treats `Pattern` as a regular expression** — the pattern was matched as a glob, so regex patterns (such as the Trino Glue connector's `trino__<name>__.*`) never matched; an invalid pattern now returns `InvalidInputException`. Contributed by @yonatoasis.
- **S3 — `WebsiteRedirectLocation` is now preserved** — `x-amz-website-redirect-location` set on `PutObject` is now stored and returned by `GetObject` / `HeadObject`. Contributed by @murlock.
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index 97224d2e..c7cf0dec 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -755,6 +755,21 @@ def _sg_rule_xml(sg_id, rule, idx, is_egress=False):
f"<toPort>{rule.get('ToPort', -1)}</toPort>"
f"<cidrIpv6>{cidr6.get('CidrIpv6', '')}</cidrIpv6>"
f"</item>")
+ for pair in rule.get("UserIdGroupPairs", []):
+ ref_gid = pair.get("GroupId", "") if isinstance(pair, dict) else str(pair)
+ items += (f"<item>"
+ f"<securityGroupRuleId>{rule_id}</securityGroupRuleId>"
+ f"<groupId>{sg_id}</groupId>"
+ f"<groupOwnerId>{get_account_id()}</groupOwnerId>"
+ f"<isEgress>{'true' if is_egress else 'false'}</isEgress>"
+ f"<ipProtocol>{rule.get('IpProtocol', '-1')}</ipProtocol>"
+ f"<fromPort>{rule.get('FromPort', -1)}</fromPort>"
+ f"<toPort>{rule.get('ToPort', -1)}</toPort>"
+ f"<referencedGroupInfo>"
+ f"<groupId>{ref_gid}</groupId>"
+ f"<userId>{get_account_id()}</userId>"
+ f"</referencedGroupInfo>"
+ f"</item>")
if not items:
# No CIDR ranges — still return the rule (e.g. referenced group)
items = (f"<item>"
@@ -2669,6 +2684,48 @@ def _matches_filters(inst, filters):
return True
+def _parse_legacy_ip_permission(params):
+ """Parse the legacy single-rule top-level parameter form of
+ Authorize/RevokeSecurityGroupIngress/Egress.
+
+ The AWS CLI (`--protocol/--port/--cidr/--source-group`), older SDKs, and
+ direct API callers send a single permission as flat top-level params
+ (IpProtocol, FromPort, ToPort, CidrIp, SourceSecurityGroupId/Name/OwnerId)
+ rather than the nested IpPermissions.N.* structure. Real EC2 accepts both;
+ MiniStack previously dropped the legacy form (issue #916).
+ """
+ proto = _p(params, "IpProtocol")
+ if not proto:
+ return []
+ rule = {"IpProtocol": proto, "IpRanges": [], "Ipv6Ranges": [],
+ "PrefixListIds": [], "UserIdGroupPairs": []}
+ from_port = _p(params, "FromPort")
+ to_port = _p(params, "ToPort")
+ if from_port:
+ rule["FromPort"] = int(from_port)
+ if to_port:
+ rule["ToPort"] = int(to_port)
+ cidr = _p(params, "CidrIp")
+ if cidr:
+ rule["IpRanges"].append({"CidrIp": cidr})
+ cidr6 = _p(params, "CidrIpv6")
+ if cidr6:
+ rule["Ipv6Ranges"].append({"CidrIpv6": cidr6})
+ src_gid = _p(params, "SourceSecurityGroupId")
+ src_gname = _p(params, "SourceSecurityGroupName")
+ if src_gid or src_gname:
+ pair = {}
+ if src_gid:
+ pair["GroupId"] = src_gid
+ if src_gname:
+ pair["GroupName"] = src_gname
+ owner = _p(params, "SourceSecurityGroupOwnerId")
+ if owner:
+ pair["UserId"] = owner
+ rule["UserIdGroupPairs"].append(pair)
+ return [rule]
+
+
def _parse_ip_permissions(params, prefix):
rules = []
i = 1
@@ -2730,6 +2787,9 @@ def _parse_ip_permissions(params, prefix):
j += 1
rules.append(rule)
i += 1
+ if not rules:
+ # Fall back to the legacy flat single-rule form (CLI --source-group/--cidr).
+ return _parse_legacy_ip_permission(params)
return rules
diff --git a/tests/test_ec2.py b/tests/test_ec2.py
index 3c3ca935..cfd46ffb 100644
--- a/tests/test_ec2.py
+++ b/tests/test_ec2.py
@@ -326,6 +326,105 @@ def test_ec2_sg_authorize_ingress_idempotent_duplicate(ec2):
ec2.delete_security_group(GroupId=sg_id)
+def test_ec2_sg_authorize_ingress_legacy_source_group(ec2):
+ """Legacy top-level --source-group params (CLI/Terraform) must create a real
+ referenced-group rule visible in DescribeSecurityGroups AND
+ DescribeSecurityGroupRules, with a SecurityGroupRuleId matching the Authorize
+ response. Regression for issue #916."""
+ vpc = ec2.create_vpc(CidrBlock="10.111.0.0/16")["Vpc"]
+ sg_a = ec2.create_security_group(
+ GroupName="sg-a-916", Description="a", VpcId=vpc["VpcId"])["GroupId"]
+ sg_b = ec2.create_security_group(
+ GroupName="sg-b-916", Description="b", VpcId=vpc["VpcId"])["GroupId"]
+
+ # The AWS CLI `authorize-security-group-ingress --protocol tcp --port 8080
+ # --source-group <id>` (and older SDKs) serialize to legacy top-level
+ # parameters rather than the nested IpPermissions.N.Groups.M form. Inject
+ # exactly that wire shape so the test exercises the same code path.
+ def _inject_legacy(request, **kwargs):
+ request.data = (
+ f"Action=AuthorizeSecurityGroupIngress&Version=2016-11-15"
+ f"&GroupId={sg_b}&IpProtocol=tcp&FromPort=8080&ToPort=8080"
+ f"&SourceSecurityGroupId={sg_a}"
+ )
+
+ ec2.meta.events.register(
+ "before-sign.ec2.AuthorizeSecurityGroupIngress", _inject_legacy)
+ try:
+ resp = ec2.authorize_security_group_ingress(GroupId=sg_b)
+ finally:
+ ec2.meta.events.unregister(
+ "before-sign.ec2.AuthorizeSecurityGroupIngress", _inject_legacy)
+
+ assert resp.get("Return") is True
+ auth_rules = resp.get("SecurityGroupRules", [])
+ assert len(auth_rules) == 1, f"expected 1 rule from Authorize, got {auth_rules}"
+ auth_rule_id = auth_rules[0]["SecurityGroupRuleId"]
+ assert auth_rules[0].get("ReferencedGroupInfo", {}).get("GroupId") == sg_a
+
+ # DescribeSecurityGroups must show the UserIdGroupPairs reference.
+ perms = ec2.describe_security_groups(
+ GroupIds=[sg_b])["SecurityGroups"][0]["IpPermissions"]
+ pairs = [pair for p in perms for pair in p.get("UserIdGroupPairs", [])]
+ assert any(pair.get("GroupId") == sg_a for pair in pairs), \
+ f"UserIdGroupPairs missing reference to {sg_a}: {perms}"
+
+ # DescribeSecurityGroupRules must return the rule with ReferencedGroupInfo
+ # and a SecurityGroupRuleId matching the Authorize response.
+ sgr = ec2.describe_security_group_rules(
+ Filters=[{"Name": "group-id", "Values": [sg_b]}])["SecurityGroupRules"]
+ ref_rules = [r for r in sgr if r.get("ReferencedGroupInfo", {}).get("GroupId") == sg_a]
+ assert len(ref_rules) == 1, \
+ f"DescribeSecurityGroupRules missing referenced-group rule: {sgr}"
+ assert ref_rules[0]["SecurityGroupRuleId"] == auth_rule_id
+ assert ref_rules[0]["IsEgress"] is False
+ assert ref_rules[0]["IpProtocol"] == "tcp"
+ assert ref_rules[0]["FromPort"] == 8080
+ assert ref_rules[0]["ToPort"] == 8080
+
+ ec2.delete_security_group(GroupId=sg_b)
+ ec2.delete_security_group(GroupId=sg_a)
+
+
+def test_ec2_sg_authorize_ingress_referenced_group_nested(ec2):
+ """The nested IpPermissions form (what boto3 and the Terraform AWS provider
+ send for a source-security-group rule) must return ReferencedGroupInfo in the
+ AuthorizeSecurityGroupIngress response, with a SecurityGroupRuleId consistent
+ with DescribeSecurityGroupRules. Regression for issue #916: previously the
+ Authorize response omitted ReferencedGroupInfo for group-pair rules."""
+ vpc = ec2.create_vpc(CidrBlock="10.112.0.0/16")["Vpc"]
+ sg_a = ec2.create_security_group(
+ GroupName="sg-a-916n", Description="a", VpcId=vpc["VpcId"])["GroupId"]
+ sg_b = ec2.create_security_group(
+ GroupName="sg-b-916n", Description="b", VpcId=vpc["VpcId"])["GroupId"]
+
+ resp = ec2.authorize_security_group_ingress(
+ GroupId=sg_b,
+ IpPermissions=[{
+ "IpProtocol": "tcp", "FromPort": 8080, "ToPort": 8080,
+ "UserIdGroupPairs": [{"GroupId": sg_a}],
+ }],
+ )
+ auth_rules = resp.get("SecurityGroupRules", [])
+ assert len(auth_rules) == 1, f"expected 1 rule from Authorize, got {auth_rules}"
+ assert auth_rules[0].get("ReferencedGroupInfo", {}).get("GroupId") == sg_a, \
+ f"Authorize response missing ReferencedGroupInfo: {auth_rules}"
+ auth_rule_id = auth_rules[0]["SecurityGroupRuleId"]
+
+ # The same referenced-group rule must be discoverable (and ID-consistent) via
+ # DescribeSecurityGroupRules — this is what Terraform's create waiter polls.
+ sgr = ec2.describe_security_group_rules(
+ Filters=[{"Name": "group-id", "Values": [sg_b]}])["SecurityGroupRules"]
+ ref_rules = [r for r in sgr if r.get("ReferencedGroupInfo", {}).get("GroupId") == sg_a]
+ assert len(ref_rules) == 1, \
+ f"DescribeSecurityGroupRules missing referenced-group rule: {sgr}"
+ assert ref_rules[0]["SecurityGroupRuleId"] == auth_rule_id
+ assert ref_rules[0]["IsEgress"] is False
+
+ ec2.delete_security_group(GroupId=sg_b)
+ ec2.delete_security_group(GroupId=sg_a)
+
+
def test_ec2_key_pair_crud(ec2):
resp = ec2.create_key_pair(KeyName="qa-ec2-key")
assert resp["KeyName"] == "qa-ec2-key"