Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(elbv2): read rule conditions sent as a typed config (#1551)
Jacob Schooley920e1b10bab2
diff --git a/ministack/services/alb.py b/ministack/services/alb.pyindex 2ee8d25a..4be07f1a 100644--- a/ministack/services/alb.py+++ b/ministack/services/alb.py@@ -253,20 +253,49 @@ def _parse_actions(params, prefix="DefaultActions"):return actions+# A rule condition carries its values either in the flat legacy ``Values`` list or+# in a per-field typed config. The Terraform AWS provider sends the typed form, so a+# parser that reads only ``Values`` records an empty condition, and the rule then+# matches nothing and the listener falls through to its default action.+_CONDITION_VALUE_KEYS = {+ "path-pattern": "PathPatternConfig",+ "host-header": "HostHeaderConfig",+ "http-request-method": "HttpRequestMethodConfig",+ "source-ip": "SourceIpConfig",+}+++def _parse_condition_values(params, base):+ """Read a condition's values from whichever shape the caller used."""+ def _values_at(prefix):+ out, j = [], 1+ while True:+ v = _p(params, f"{prefix}.member.{j}")+ if not v:+ break+ out.append(v)+ j += 1+ return out++ values = _values_at(f"{base}.Values")+ if values:+ return values++ for config_key in _CONDITION_VALUE_KEYS.values():+ values = _values_at(f"{base}.{config_key}.Values")+ if values:+ return values+ return []++def _parse_conditions(params, prefix="Conditions"):conditions, i = [], 1while True:- field = _p(params, f"{prefix}.member.{i}.Field")+ base = f"{prefix}.member.{i}"+ field = _p(params, f"{base}.Field")if not field:break- values, j = [], 1- while True:- v = _p(params, f"{prefix}.member.{i}.Values.member.{j}")- if not v:- break- values.append(v)- j += 1- conditions.append({"Field": field, "Values": values})+ conditions.append({"Field": field, "Values": _parse_condition_values(params, base)})i += 1return conditions@@ -429,13 +458,25 @@ def _listener_xml(l):)+def _condition_xml(c):+ """Render a condition the way AWS does: the flat Values list *and*, for the+ fields that have one, the typed config carrying the same values.++ A client that reads only the typed config — the Terraform provider does, for+ path_pattern and host_header — sees an empty condition otherwise, and plans a+ change on every run to put the values back.+ """+ values = c.get("Values", [])+ members = "".join(f"<member>{v}</member>" for v in values)+ xml = f"<member><Field>{c['Field']}</Field><Values>{members}</Values>"+ config_key = _CONDITION_VALUE_KEYS.get(c.get("Field"))+ if config_key:+ xml += f"<{config_key}><Values>{members}</Values></{config_key}>"+ return xml + "</member>"++def _rule_xml(r):- conds = "".join(- f"<member><Field>{c['Field']}</Field>"- f"<Values>{''.join(f'<member>{v}</member>' for v in c.get('Values',[]))}</Values>"- f"</member>"- for c in r.get("Conditions", [])- )+ conds = "".join(_condition_xml(c) for c in r.get("Conditions", []))acts = "".join(_action_xml(a) for a in r.get("Actions", []))return (f"<member>"diff --git a/tests/test_alb.py b/tests/test_alb.pyindex 07175ebc..67e047b1 100644--- a/tests/test_alb.py+++ b/tests/test_alb.py@@ -1189,3 +1189,91 @@ def test_alb_load_balancers_are_region_isolated(elbv2):assert arn not in westfinally:elbv2.delete_load_balancer(LoadBalancerArn=arn)+++def test_alb_rule_condition_accepts_typed_config_shape(elbv2):+ """A rule condition's values may arrive as PathPatternConfig, not a flat Values list.++ The Terraform AWS provider sends the typed form. Parsing only the legacy flat+ list records an empty condition, so the rule matches nothing and every request+ falls through to the listener's default action.+ """+ vpc = "vpc-typedcond"+ lb = elbv2.create_load_balancer(Name="typedcond-lb", Subnets=["subnet-1"])["LoadBalancers"][0]+ tg = elbv2.create_target_group(Name="typedcond-tg", Port=80, Protocol="HTTP", VpcId=vpc)["TargetGroups"][0]+ listener = elbv2.create_listener(+ LoadBalancerArn=lb["LoadBalancerArn"], Protocol="HTTP", Port=80,+ DefaultActions=[{+ "Type": "fixed-response",+ "FixedResponseConfig": {"StatusCode": "200", "ContentType": "text/plain", "MessageBody": "OK"},+ }],+ )["Listeners"][0]++ # botocore serialises this as Conditions.member.1.PathPatternConfig.Values.member.1+ elbv2.create_rule(+ ListenerArn=listener["ListenerArn"],+ Priority=1,+ Conditions=[{"Field": "path-pattern", "PathPatternConfig": {"Values": ["/q"]}}],+ Actions=[{"Type": "forward", "TargetGroupArn": tg["TargetGroupArn"]}],+ )++ rules = elbv2.describe_rules(ListenerArn=listener["ListenerArn"])["Rules"]+ rule = next(r for r in rules if r.get("Priority") == "1")+ cond = rule["Conditions"][0]+ assert cond["Field"] == "path-pattern"+ assert cond["Values"] == ["/q"], f"condition values were dropped: {cond}"+ # AWS answers with both shapes. A client reading only the typed config — the+ # Terraform provider does — sees an empty condition without this, and plans a+ # change on every run to put the values back.+ assert cond["PathPatternConfig"]["Values"] == ["/q"], f"typed config not returned: {cond}"+++def test_alb_rule_condition_still_accepts_flat_values(elbv2):+ """The legacy flat Values list must keep working."""+ vpc = "vpc-flatcond"+ lb = elbv2.create_load_balancer(Name="flatcond-lb", Subnets=["subnet-1"])["LoadBalancers"][0]+ tg = elbv2.create_target_group(Name="flatcond-tg", Port=80, Protocol="HTTP", VpcId=vpc)["TargetGroups"][0]+ listener = elbv2.create_listener(+ LoadBalancerArn=lb["LoadBalancerArn"], Protocol="HTTP", Port=80,+ DefaultActions=[{"Type": "forward", "TargetGroupArn": tg["TargetGroupArn"]}],+ )["Listeners"][0]++ elbv2.create_rule(+ ListenerArn=listener["ListenerArn"],+ Priority=5,+ Conditions=[{"Field": "path-pattern", "Values": ["/legacy"]}],+ Actions=[{"Type": "forward", "TargetGroupArn": tg["TargetGroupArn"]}],+ )++ rules = elbv2.describe_rules(ListenerArn=listener["ListenerArn"])["Rules"]+ rule = next(r for r in rules if r.get("Priority") == "5")+ assert rule["Conditions"][0]["Values"] == ["/legacy"]+++def test_alb_rule_conditions_round_trip_in_both_shapes(elbv2):+ """host-header and http-request-method must also come back in their typed config."""+ vpc = "vpc-bothshapes"+ lb = elbv2.create_load_balancer(Name="bothshapes-lb", Subnets=["subnet-1"])["LoadBalancers"][0]+ tg = elbv2.create_target_group(Name="bothshapes-tg", Port=80, Protocol="HTTP", VpcId=vpc)["TargetGroups"][0]+ listener = elbv2.create_listener(+ LoadBalancerArn=lb["LoadBalancerArn"], Protocol="HTTP", Port=80,+ DefaultActions=[{"Type": "forward", "TargetGroupArn": tg["TargetGroupArn"]}],+ )["Listeners"][0]++ cases = [+ (20, {"Field": "host-header", "HostHeaderConfig": {"Values": ["api.example.com"]}},+ "HostHeaderConfig", ["api.example.com"]),+ (21, {"Field": "http-request-method", "HttpRequestMethodConfig": {"Values": ["POST"]}},+ "HttpRequestMethodConfig", ["POST"]),+ ]+ for priority, condition, config_key, expected in cases:+ elbv2.create_rule(+ ListenerArn=listener["ListenerArn"], Priority=priority, Conditions=[condition],+ Actions=[{"Type": "forward", "TargetGroupArn": tg["TargetGroupArn"]}],+ )++ rules = {r["Priority"]: r for r in elbv2.describe_rules(ListenerArn=listener["ListenerArn"])["Rules"]}+ for priority, _cond, config_key, expected in cases:+ cond = rules[str(priority)]["Conditions"][0]+ assert cond["Values"] == expected+ assert cond[config_key]["Values"] == expected, f"{config_key} not returned: {cond}"