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
feat(stepfunctions): support aws-sdk:route53 tasks (#1361)
Maximilian Bandle17075dd8170f
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.pyindex 8f2b83e0..39abb0ac 100644--- a/ministack/services/stepfunctions.py+++ b/ministack/services/stepfunctions.py@@ -4264,6 +4264,7 @@ _AWS_SDK_SERVICE_MAP = {"rdsdata": {"protocol": "rest-json", "service_key": "rds-data"},# REST-XML services: per-op path templates, header/querystring routing, XML responses"s3": {"protocol": "rest-xml", "service_key": "s3"},+ "route53": {"protocol": "rest-xml", "service_key": "route53"},"lambda": {"protocol": "rest"},}@@ -5385,9 +5386,30 @@ _S3_OP_SPECS = {},}+# Route 53 wraps XML lists ("<Changes><Change/></Changes>") where S3 repeats the parent element,+# hence list_members. The zone id is substituted verbatim: botocore's fix_route53_ids runs inside+# boto3, not Step Functions, and AWS rejects the "/hostedzone/" form.+_ROUTE53_OP_SPECS = {+ "ChangeResourceRecordSets": {+ "method": "POST", "path": "/2013-04-01/hostedzone/{Id}/rrset/",+ "path_params": {"Id": "HostedZoneId"},+ "body_field": "ChangeBatch",+ # Unlike S3, the request element wraps the input field rather than being it.+ "body_wrapper": "ChangeResourceRecordSetsRequest",+ "body_xmlns": "https://route53.amazonaws.com/doc/2013-04-01/",+ "list_members": {"Changes": "Change", "ResourceRecords": "ResourceRecord"},+ },+}++# Keyed by service, like _REST_JSON_ACTION_PATHS: the protocol is shared, the op specs are not.+_REST_XML_OP_SPECS = {+ "s3": _S3_OP_SPECS,+ "route53": _ROUTE53_OP_SPECS,+}-def _s3_substitute_path(template, input_data):- """Substitute {Bucket} and {Key+} placeholders. {Key+} preserves slashes."""++def _rest_xml_substitute_path(template, input_data, spec=None):+ """Substitute path placeholders: S3's {Bucket}/{Key+}, plus the spec's path_params."""out = templateif "{Bucket}" in out:bucket = input_data.get("Bucket", "")@@ -5395,13 +5417,22 @@ def _s3_substitute_path(template, input_data):if "{Key+}" in out:key = input_data.get("Key", "")out = out.replace("{Key+}", key)+ for placeholder, field in ((spec or {}).get("path_params") or {}).items():+ out = out.replace("{" + placeholder + "}", str(input_data.get(field, "")))return out-def _s3_build_xml_body(root_name, payload):- """Build a minimal XML body for the small handful of ops that need one."""+def _rest_xml_build_body(root_name, payload, list_members=None, xmlns=None):+ """Build a minimal XML body for the small handful of ops that need one.++ A list is emitted as a repeated parent element ("<Contents/><Contents/>", S3's shape) unless+ list_members names its member element, in which case it is wrapped+ ("<Changes><Change/></Changes>", Route 53's shape). Getting this wrong is silent: the handler+ finds no members and reads the change batch as empty.+ """import xml.etree.ElementTree as ET- root = ET.Element(root_name)+ list_members = list_members or {}+ root = ET.Element(root_name, {"xmlns": xmlns} if xmlns else {})def _emit(parent, name, value):if isinstance(value, dict):@@ -5409,8 +5440,14 @@ def _s3_build_xml_body(root_name, payload):for k, v in value.items():_emit(child, k, v)elif isinstance(value, list):- for item in value:- _emit(parent, name, item)+ member = list_members.get(name)+ if member:+ wrapper = ET.SubElement(parent, name)+ for item in value:+ _emit(wrapper, member, item)+ else:+ for item in value:+ _emit(parent, name, item)else:child = ET.SubElement(parent, name)child.text = "" if value is None else str(value)@@ -5453,7 +5490,7 @@ def _s3_normalize_lists(parsed, list_fields):def _dispatch_aws_sdk_rest_xml(service_info, service_name, action, input_data):- """Dispatch an aws-sdk integration call to a REST-XML protocol service (S3)."""+ """Dispatch an aws-sdk integration call to a REST-XML protocol service."""import xml.etree.ElementTree as ETfrom urllib.parse import quote, urlencode@@ -5468,17 +5505,19 @@ def _dispatch_aws_sdk_rest_xml(service_info, service_name, action, input_data):)pascal_action = action[0].upper() + action[1:] if action else action- spec = _S3_OP_SPECS.get(pascal_action)+ op_specs = _REST_XML_OP_SPECS.get(service_key) or {}+ spec = op_specs.get(pascal_action)if not spec:+ covered = ", ".join(sorted(op_specs)) or "no operations"raise _ExecutionError("States.Runtime",f"aws-sdk:{service_name}:{action} is not yet implemented in MiniStack "- "(rest-xml dispatcher Phase 1 covers list/head/copy/delete/tagging operations)",+ f"(rest-xml dispatcher covers: {covered})",)input_data = input_data or {}method = spec["method"]- path = _s3_substitute_path(spec["path"], input_data)+ path = _rest_xml_substitute_path(spec["path"], input_data, spec)# S3 handler routes by the query_params dict, not by parsing the path —# so build the dict and ALSO append a query string for handlers that@@ -5510,7 +5549,13 @@ def _dispatch_aws_sdk_rest_xml(service_info, service_name, action, input_data):body = b""body_field = spec.get("body_field")if body_field and body_field in input_data:- body = _s3_build_xml_body(spec.get("body_root", body_field), input_data[body_field])+ wrapper = spec.get("body_wrapper")+ root_name = wrapper or spec.get("body_root", body_field)+ payload = {body_field: input_data[body_field]} if wrapper else input_data[body_field]+ # SDK-convention names have to go out as wire names: route53 ignores <Ttl> and stores no TTL.+ payload = _convert_params_to_api_names(payload)+ body = _rest_xml_build_body(root_name, payload, spec.get("list_members"),+ spec.get("body_xmlns"))headers["content-type"] = "application/xml"headers["content-length"] = str(len(body))@@ -5537,20 +5582,29 @@ def _dispatch_aws_sdk_rest_xml(service_info, service_name, action, input_data):norm_resp_headers = {k.lower(): v for k, v in (resp_headers or {}).items()}if status >= 400:- code = "S3Exception"- message = decoded or f"S3 returned status {status}"+ # Same shape as before for S3 ("S3.S3Exception", "S3 returned status 404") without+ # hardcoding it: the prefix map already knows what each service is called.+ prefix = _AWS_SDK_ERROR_PREFIX.get(service_name, service_name.capitalize())+ code = f"{prefix}Exception"+ message = decoded or f"{prefix} returned status {status}"if decoded:try:err_root = ET.fromstring(decoded)- code_el = err_root.find("Code")- msg_el = err_root.find("Message")- if code_el is not None and code_el.text:- code = code_el.text- if msg_el is not None and msg_el.text:- message = msg_el.text+ # Route 53 nests Code/Message under <Error> with a default xmlns, so match local+ # names anywhere rather than find("Code").+ found = {}+ for el in err_root.iter():+ local = el.tag.split("}")[-1] if "}" in el.tag else el.tag+ if local in ("Code", "Message") and local not in found and el.text:+ found[local] = el.text+ code = found.get("Code", code)+ message = found.get("Message", message)except ET.ParseError:pass- raise _ExecutionError(f"S3.{code}", message)+ # Named after the SDK exception class: S3.NoSuchBucketException.+ if not code.endswith("Exception"):+ code += "Exception"+ raise _ExecutionError(_prefix_sdk_error(service_name, code), message)result = {}if decoded.strip():diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.pyindex cd0080f6..c3285663 100644--- a/tests/test_stepfunctions.py+++ b/tests/test_stepfunctions.py@@ -5557,6 +5557,196 @@ def test_sfn_aws_sdk_s3_op_specs_cover_issue_573_request():assert "ListObjectsV2" in _S3_OP_SPECSassert "CopyObject" in _S3_OP_SPECS+++def test_sfn_aws_sdk_s3_error_names_the_sdk_exception(sfn_sync):+ """A failing S3 op is named after the SDK exception class, as real Step Functions names it."""+ tag = _uuid_mod.uuid4().hex[:8]++ sm_arn = sfn_sync.create_state_machine(+ name=f"sdk-s3-err-{tag}",+ definition=json.dumps({+ "StartAt": "Del",+ "States": {+ "Del": {+ "Type": "Task",+ "Resource": "arn:aws:states:::aws-sdk:s3:deleteBucket",+ "Parameters": {"Bucket": f"absent-{tag}"},+ "End": True,+ },+ },+ }),+ roleArn="arn:aws:iam::000000000000:role/sfn-role",+ )["stateMachineArn"]+ try:+ resp = sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input=json.dumps({}))+ assert resp["status"] == "FAILED"+ assert resp.get("error") == "S3.NoSuchBucketException", resp.get("error")+ finally:+ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)+++# ---------------------------------------------------------------------------+# REST-XML aws-sdk dispatch (Route 53)+# ---------------------------------------------------------------------------+++def _r53_change_task(sfn_sync, tag, params, action="changeResourceRecordSets"):+ """Run one aws-sdk:route53 task to completion and return the sync-execution response."""+ arn = sfn_sync.create_state_machine(+ name=f"sdk-r53-{tag}-{_uuid_mod.uuid4().hex[:6]}",+ definition=json.dumps({+ "StartAt": "Change",+ "States": {+ "Change": {+ "Type": "Task",+ "Resource": f"arn:aws:states:::aws-sdk:route53:{action}",+ "Parameters": params,+ "End": True,+ },+ },+ }),+ roleArn="arn:aws:iam::000000000000:role/sfn-role",+ )["stateMachineArn"]+ try:+ return sfn_sync.start_sync_execution(stateMachineArn=arn, input=json.dumps({}))+ finally:+ sfn_sync.delete_state_machine(stateMachineArn=arn)+++def test_sfn_aws_sdk_route53_change_resource_record_sets(sfn_sync, r53):+ """aws-sdk:route53:changeResourceRecordSets writes the record, and deletes it again."""+ tag = _uuid_mod.uuid4().hex[:8]+ zone_name = f"sfn-r53-{tag}.example.com."+ record = f"api.{zone_name}"+ values = ["10.0.0.1", "10.0.0.2"]+ zone_id = None++ def batch(action):+ return {"Comment": f"sfn {tag}",+ "Changes": [{"Action": action,+ "ResourceRecordSet": {"Name": record, "Type": "A", "TTL": 60,+ "ResourceRecords": [{"Value": v}+ for v in values]}}]}++ def a_records(zone):+ return [rs for rs in r53.list_resource_record_sets(HostedZoneId=zone)["ResourceRecordSets"]+ if rs["Name"] == record and rs["Type"] == "A"]++ try:+ zone_id = r53.create_hosted_zone(+ Name=zone_name, CallerReference=f"sfn-{tag}")["HostedZone"]["Id"]+ bare_id = zone_id.rsplit("/", 1)[-1]++ resp = _r53_change_task(sfn_sync, tag, {"HostedZoneId": bare_id,+ "ChangeBatch": batch("UPSERT")})+ assert resp["status"] == "SUCCEEDED", f"{resp.get('error')} — {resp.get('cause')}"+ info = json.loads(resp["output"])["ChangeInfo"]+ assert info["Id"].startswith("/change/")+ assert info["Status"] in ("PENDING", "INSYNC")+ assert info["SubmittedAt"]++ # Task success is not the assertion: a flattened XML body loses values silently.+ got = a_records(bare_id)+ assert len(got) == 1, got+ assert sorted(r["Value"] for r in got[0]["ResourceRecords"]) == values+ assert str(got[0]["TTL"]) == "60"++ # The bare id is the only form that works; AWS rejects "/hostedzone/Z..." unchanged.+ resp = _r53_change_task(sfn_sync, tag, {"HostedZoneId": bare_id,+ "ChangeBatch": batch("DELETE")})+ assert resp["status"] == "SUCCEEDED", f"{resp.get('error')} — {resp.get('cause')}"+ assert a_records(bare_id) == []+ finally:+ if zone_id:+ try:+ r53.delete_hosted_zone(Id=zone_id)+ except ClientError:+ pass+++def test_sfn_aws_sdk_route53_request_matches_botocore():+ """The request this dispatcher builds must be the one boto3 would have sent."""+ import botocore.session+ from botocore.serialize import create_serializer++ from ministack.services.stepfunctions import (+ _ROUTE53_OP_SPECS,+ _rest_xml_build_body,+ _rest_xml_substitute_path,+ )++ change_batch = {+ "Comment": "c",+ "Changes": [{"Action": "UPSERT",+ "ResourceRecordSet": {"Name": "a.example.com", "Type": "A", "TTL": 60,+ "ResourceRecords": [{"Value": "1.2.3.4"},+ {"Value": "5.6.7.8"}]}}],+ }+ params = {"HostedZoneId": "Z123ABC", "ChangeBatch": change_batch}++ op = botocore.session.get_session().get_service_model("route53").operation_model(+ "ChangeResourceRecordSets")+ want = create_serializer("rest-xml").serialize_to_request(params, op)+ want_body = want["body"].decode("utf-8") if isinstance(want["body"], bytes) else want["body"]++ spec = _ROUTE53_OP_SPECS["ChangeResourceRecordSets"]+ assert _rest_xml_substitute_path(spec["path"], params, spec) == want["url_path"]+ assert _rest_xml_build_body(spec["body_wrapper"], {"ChangeBatch": change_batch},+ spec["list_members"],+ spec["body_xmlns"]).decode("utf-8") == want_body++ # Verbatim: fix_route53_ids runs inside boto3, not Step Functions, and AWS rejects this form.+ assert _rest_xml_substitute_path(+ spec["path"], {"HostedZoneId": "/hostedzone/Z123ABC"}, spec) == (+ "/2013-04-01/hostedzone//hostedzone/Z123ABC/rrset/")+++def test_sfn_aws_sdk_route53_ttl_uses_the_sdk_spelling(sfn_sync, r53):+ """"Ttl" in Parameters has to reach route53 as <TTL>, or the record loses its TTL silently."""+ tag = _uuid_mod.uuid4().hex[:8]+ zone = r53.create_hosted_zone(Name=f"ttl-{tag}.example.com.",+ CallerReference=_uuid_mod.uuid4().hex)["HostedZone"]+ zone_id = zone["Id"].rsplit("/", 1)[-1]+ name = f"rec.ttl-{tag}.example.com."++ resp = _r53_change_task(sfn_sync, tag, {+ "HostedZoneId": zone_id,+ "ChangeBatch": {"Changes": [{"Action": "UPSERT", "ResourceRecordSet": {+ "Name": name, "Type": "A", "Ttl": 60,+ "ResourceRecords": [{"Value": "10.0.0.1"}]}}]},+ })+ assert resp["status"] == "SUCCEEDED", resp.get("cause")++ got = [r for r in r53.list_resource_record_sets(HostedZoneId=zone_id)["ResourceRecordSets"]+ if r["Name"] == name]+ assert len(got) == 1, got+ assert got[0].get("TTL") == 60, f"TTL dropped, record stored as {got[0]}"+++def test_sfn_aws_sdk_route53_errors_name_their_service(sfn_sync):+ """A route53 failure is Route53.<Code>Exception, and an unmapped op names the covered ops."""+ tag = _uuid_mod.uuid4().hex[:8]++ resp = _r53_change_task(sfn_sync, tag, {+ "HostedZoneId": "Z00000000000000000000",+ "ChangeBatch": {"Changes": [{"Action": "UPSERT",+ "ResourceRecordSet": {"Name": f"x.{tag}.example.com.",+ "Type": "A", "TTL": 60,+ "ResourceRecords": [+ {"Value": "10.0.0.9"}]}}]},+ })+ # Route 53 nests Code under <Error> with a default xmlns; both have to be seen through.+ assert resp["status"] == "FAILED"+ assert resp.get("error") == "Route53.NoSuchHostedZoneException", resp.get("cause")++ # An operation with no spec names the ones that do have one, per service.+ resp = _r53_change_task(sfn_sync, tag, {"MaxItems": "1"}, action="listHostedZones")+ assert resp["status"] == "FAILED"+ cause = resp.get("cause") or ""+ assert "not yet implemented" in cause and "ChangeResourceRecordSets" in cause++# ---------------------------------------------------------------------------# Terraform compatibility tests# ---------------------------------------------------------------------------